2 Copyright (C) 1996-1997 Id Software, Inc.
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.
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.
13 See the GNU General Public License for more details.
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.
20 // models.c -- model loading and caching
22 // models are the only shared resource between a client and server running
23 // on the same machine.
30 cvar_t r_mipskins = {CVAR_SAVE, "r_mipskins", "0", "mipmaps model skins so they render faster in the distance and do not display noise artifacts, can cause discoloration of skins if they contain undesirable border colors"};
31 cvar_t r_mipnormalmaps = {CVAR_SAVE, "r_mipnormalmaps", "1", "mipmaps normalmaps (turning it off looks sharper but may have aliasing)"};
32 cvar_t mod_generatelightmaps_unitspersample = {CVAR_SAVE, "mod_generatelightmaps_unitspersample", "8", "lightmap resolution"};
33 cvar_t mod_generatelightmaps_borderpixels = {CVAR_SAVE, "mod_generatelightmaps_borderpixels", "2", "extra space around polygons to prevent sampling artifacts"};
34 cvar_t mod_generatelightmaps_texturesize = {CVAR_SAVE, "mod_generatelightmaps_texturesize", "1024", "size of lightmap textures"};
35 cvar_t mod_generatelightmaps_lightmapsamples = {CVAR_SAVE, "mod_generatelightmaps_lightmapsamples", "16", "number of shadow tests done per lightmap pixel"};
36 cvar_t mod_generatelightmaps_vertexsamples = {CVAR_SAVE, "mod_generatelightmaps_vertexsamples", "16", "number of shadow tests done per vertex"};
37 cvar_t mod_generatelightmaps_gridsamples = {CVAR_SAVE, "mod_generatelightmaps_gridsamples", "64", "number of shadow tests done per lightgrid cell"};
38 cvar_t mod_generatelightmaps_lightmapradius = {CVAR_SAVE, "mod_generatelightmaps_lightmapradius", "16", "sampling area around each lightmap pixel"};
39 cvar_t mod_generatelightmaps_vertexradius = {CVAR_SAVE, "mod_generatelightmaps_vertexradius", "16", "sampling area around each vertex"};
40 cvar_t mod_generatelightmaps_gridradius = {CVAR_SAVE, "mod_generatelightmaps_gridradius", "64", "sampling area around each lightgrid cell center"};
42 dp_model_t *loadmodel;
44 static mempool_t *mod_mempool;
45 static memexpandablearray_t models;
47 static mempool_t* q3shaders_mem;
48 typedef struct q3shader_hash_entry_s
50 q3shaderinfo_t shader;
51 struct q3shader_hash_entry_s* chain;
52 } q3shader_hash_entry_t;
53 #define Q3SHADER_HASH_SIZE 1021
54 typedef struct q3shader_data_s
56 memexpandablearray_t hash_entries;
57 q3shader_hash_entry_t hash[Q3SHADER_HASH_SIZE];
58 memexpandablearray_t char_ptrs;
60 static q3shader_data_t* q3shader_data;
62 static void mod_start(void)
65 int nummodels = Mem_ExpandableArray_IndexRange(&models);
68 SCR_PushLoadingScreen(false, "Loading models", 1.0);
70 for (i = 0;i < nummodels;i++)
71 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
74 for (i = 0;i < nummodels;i++)
75 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
78 SCR_PushLoadingScreen(true, mod->name, 1.0 / count);
79 Mod_LoadModel(mod, true, false);
80 SCR_PopLoadingScreen(false);
82 SCR_PopLoadingScreen(false);
85 static void mod_shutdown(void)
88 int nummodels = Mem_ExpandableArray_IndexRange(&models);
91 for (i = 0;i < nummodels;i++)
92 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && (mod->loaded || mod->mempool))
96 Mod_Skeletal_FreeBuffers();
99 static void mod_newmap(void)
102 int i, j, k, surfacenum, ssize, tsize;
103 int nummodels = Mem_ExpandableArray_IndexRange(&models);
106 for (i = 0;i < nummodels;i++)
108 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->mempool)
110 for (j = 0;j < mod->num_textures && mod->data_textures;j++)
112 for (k = 0;k < mod->data_textures[j].numskinframes;k++)
113 R_SkinFrame_MarkUsed(mod->data_textures[j].skinframes[k]);
114 for (k = 0;k < mod->data_textures[j].backgroundnumskinframes;k++)
115 R_SkinFrame_MarkUsed(mod->data_textures[j].backgroundskinframes[k]);
117 if (mod->brush.solidskyskinframe)
118 R_SkinFrame_MarkUsed(mod->brush.solidskyskinframe);
119 if (mod->brush.alphaskyskinframe)
120 R_SkinFrame_MarkUsed(mod->brush.alphaskyskinframe);
124 if (!cl_stainmaps_clearonload.integer)
127 for (i = 0;i < nummodels;i++)
129 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->mempool && mod->data_surfaces)
131 for (surfacenum = 0, surface = mod->data_surfaces;surfacenum < mod->num_surfaces;surfacenum++, surface++)
133 if (surface->lightmapinfo && surface->lightmapinfo->stainsamples)
135 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
136 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
137 memset(surface->lightmapinfo->stainsamples, 255, ssize * tsize * 3);
138 mod->brushq1.lightmapupdateflags[surfacenum] = true;
150 static void Mod_Print(void);
151 static void Mod_Precache (void);
152 static void Mod_Decompile_f(void);
153 static void Mod_GenerateLightmaps_f(void);
156 mod_mempool = Mem_AllocPool("modelinfo", 0, NULL);
157 Mem_ExpandableArray_NewArray(&models, mod_mempool, sizeof(dp_model_t), 16);
163 Cvar_RegisterVariable(&r_mipskins);
164 Cvar_RegisterVariable(&r_mipnormalmaps);
165 Cvar_RegisterVariable(&mod_generatelightmaps_unitspersample);
166 Cvar_RegisterVariable(&mod_generatelightmaps_borderpixels);
167 Cvar_RegisterVariable(&mod_generatelightmaps_texturesize);
169 Cvar_RegisterVariable(&mod_generatelightmaps_lightmapsamples);
170 Cvar_RegisterVariable(&mod_generatelightmaps_vertexsamples);
171 Cvar_RegisterVariable(&mod_generatelightmaps_gridsamples);
172 Cvar_RegisterVariable(&mod_generatelightmaps_lightmapradius);
173 Cvar_RegisterVariable(&mod_generatelightmaps_vertexradius);
174 Cvar_RegisterVariable(&mod_generatelightmaps_gridradius);
176 Cmd_AddCommand ("modellist", Mod_Print, "prints a list of loaded models");
177 Cmd_AddCommand ("modelprecache", Mod_Precache, "load a model");
178 Cmd_AddCommand ("modeldecompile", Mod_Decompile_f, "exports a model in several formats for editing purposes");
179 Cmd_AddCommand ("mod_generatelightmaps", Mod_GenerateLightmaps_f, "rebuilds lighting on current worldmodel");
182 void Mod_RenderInit(void)
184 R_RegisterModule("Models", mod_start, mod_shutdown, mod_newmap, NULL, NULL);
187 void Mod_UnloadModel (dp_model_t *mod)
189 char name[MAX_QPATH];
191 dp_model_t *parentmodel;
193 if (developer_loading.integer)
194 Con_Printf("unloading model %s\n", mod->name);
196 strlcpy(name, mod->name, sizeof(name));
197 parentmodel = mod->brush.parentmodel;
201 if (mod->surfmesh.vertexpositionbuffer)
202 R_Mesh_DestroyMeshBuffer(mod->surfmesh.vertexpositionbuffer);
203 mod->surfmesh.vertexpositionbuffer = NULL;
204 if (mod->surfmesh.vertexmeshbuffer)
205 R_Mesh_DestroyMeshBuffer(mod->surfmesh.vertexmeshbuffer);
206 mod->surfmesh.vertexmeshbuffer = NULL;
207 if (mod->surfmesh.data_element3i_indexbuffer)
208 R_Mesh_DestroyMeshBuffer(mod->surfmesh.data_element3i_indexbuffer);
209 mod->surfmesh.data_element3i_indexbuffer = NULL;
210 if (mod->surfmesh.data_element3s_indexbuffer)
211 R_Mesh_DestroyMeshBuffer(mod->surfmesh.data_element3s_indexbuffer);
212 mod->surfmesh.data_element3s_indexbuffer = NULL;
213 if (mod->surfmesh.vbo_vertexbuffer)
214 R_Mesh_DestroyMeshBuffer(mod->surfmesh.vbo_vertexbuffer);
215 mod->surfmesh.vbo_vertexbuffer = NULL;
217 // free textures/memory attached to the model
218 R_FreeTexturePool(&mod->texturepool);
219 Mem_FreePool(&mod->mempool);
220 // clear the struct to make it available
221 memset(mod, 0, sizeof(dp_model_t));
222 // restore the fields we want to preserve
223 strlcpy(mod->name, name, sizeof(mod->name));
224 mod->brush.parentmodel = parentmodel;
229 void R_Model_Null_Draw(entity_render_t *ent)
235 typedef void (*mod_framegroupify_parsegroups_t) (unsigned int i, int start, int len, float fps, qboolean loop, void *pass);
237 int Mod_FrameGroupify_ParseGroups(const char *buf, mod_framegroupify_parsegroups_t cb, void *pass)
250 if (!COM_ParseToken_Simple(&bufptr, true, false))
252 if (!strcmp(com_token, "\n"))
253 continue; // empty line
254 start = atoi(com_token);
255 if (!COM_ParseToken_Simple(&bufptr, true, false))
257 if (!strcmp(com_token, "\n"))
259 Con_Printf("framegroups file: missing number of frames\n");
262 len = atoi(com_token);
263 if (!COM_ParseToken_Simple(&bufptr, true, false))
265 // we default to looping as it's usually wanted, so to NOT loop you append a 0
266 if (strcmp(com_token, "\n"))
268 fps = atof(com_token);
269 if (!COM_ParseToken_Simple(&bufptr, true, false))
271 if (strcmp(com_token, "\n"))
272 loop = atoi(com_token) != 0;
283 cb(i, start, len, fps, loop, pass);
290 void Mod_FrameGroupify_ParseGroups_Count (unsigned int i, int start, int len, float fps, qboolean loop, void *pass)
292 unsigned int *cnt = (unsigned int *) pass;
296 void Mod_FrameGroupify_ParseGroups_Store (unsigned int i, int start, int len, float fps, qboolean loop, void *pass)
298 dp_model_t *mod = (dp_model_t *) pass;
299 animscene_t *anim = &mod->animscenes[i];
300 dpsnprintf(anim->name, sizeof(anim[i].name), "groupified_%d_anim", i);
301 anim->firstframe = bound(0, start, mod->num_poses - 1);
302 anim->framecount = bound(1, len, mod->num_poses - anim->firstframe);
303 anim->framerate = max(1, fps);
305 //Con_Printf("frame group %d is %d %d %f %d\n", i, start, len, fps, loop);
308 void Mod_FrameGroupify(dp_model_t *mod, const char *buf)
313 cnt = Mod_FrameGroupify_ParseGroups(buf, NULL, NULL);
316 Con_Printf("no scene found in framegroups file, aborting\n");
319 mod->numframes = cnt;
322 // (we do not free the previous animscenes, but model unloading will free the pool owning them, so it's okay)
323 mod->animscenes = (animscene_t *) Mem_Alloc(mod->mempool, sizeof(animscene_t) * mod->numframes);
326 Mod_FrameGroupify_ParseGroups(buf, Mod_FrameGroupify_ParseGroups_Store, mod);
329 void Mod_FindPotentialDeforms(dp_model_t *mod)
333 mod->wantnormals = false;
334 mod->wanttangents = false;
335 for (i = 0;i < mod->num_textures;i++)
337 texture = mod->data_textures + i;
338 if (texture->tcgen.tcgen == Q3TCGEN_ENVIRONMENT)
339 mod->wantnormals = true;
340 for (j = 0;j < Q3MAXDEFORMS;j++)
342 if (texture->deforms[j].deform == Q3DEFORM_AUTOSPRITE)
344 mod->wanttangents = true;
345 mod->wantnormals = true;
348 if (texture->deforms[j].deform != Q3DEFORM_NONE)
349 mod->wantnormals = true;
361 dp_model_t *Mod_LoadModel(dp_model_t *mod, qboolean crash, qboolean checkdisk)
366 fs_offset_t filesize = 0;
370 if (mod->name[0] == '*') // submodel
373 if (!strcmp(mod->name, "null"))
378 if (mod->loaded || mod->mempool)
379 Mod_UnloadModel(mod);
381 if (developer_loading.integer)
382 Con_Printf("loading model %s\n", mod->name);
385 mod->crc = (unsigned int)-1;
388 VectorClear(mod->normalmins);
389 VectorClear(mod->normalmaxs);
390 VectorClear(mod->yawmins);
391 VectorClear(mod->yawmaxs);
392 VectorClear(mod->rotatedmins);
393 VectorClear(mod->rotatedmaxs);
395 mod->modeldatatypestring = "null";
396 mod->type = mod_null;
397 mod->Draw = R_Model_Null_Draw;
401 // no fatal errors occurred, so this model is ready to use.
410 // even if the model is loaded it still may need reloading...
412 // if it is not loaded or checkdisk is true we need to calculate the crc
413 if (!mod->loaded || checkdisk)
415 if (checkdisk && mod->loaded)
416 Con_DPrintf("checking model %s\n", mod->name);
417 buf = FS_LoadFile (mod->name, tempmempool, false, &filesize);
420 crc = CRC_Block((unsigned char *)buf, filesize);
421 // we need to reload the model if the crc does not match
427 // if the model is already loaded and checks passed, just return
435 if (developer_loading.integer)
436 Con_Printf("loading model %s\n", mod->name);
438 SCR_PushLoadingScreen(true, mod->name, 1);
440 // LordHavoc: unload the existing model in this slot (if there is one)
441 if (mod->loaded || mod->mempool)
442 Mod_UnloadModel(mod);
447 // errors can prevent the corresponding mod->loaded = true;
450 // default model radius and bounding box (mainly for missing models)
452 VectorSet(mod->normalmins, -mod->radius, -mod->radius, -mod->radius);
453 VectorSet(mod->normalmaxs, mod->radius, mod->radius, mod->radius);
454 VectorSet(mod->yawmins, -mod->radius, -mod->radius, -mod->radius);
455 VectorSet(mod->yawmaxs, mod->radius, mod->radius, mod->radius);
456 VectorSet(mod->rotatedmins, -mod->radius, -mod->radius, -mod->radius);
457 VectorSet(mod->rotatedmaxs, mod->radius, mod->radius, mod->radius);
461 // load q3 shaders for the first time, or after a level change
467 char *bufend = (char *)buf + filesize;
469 // all models use memory, so allocate a memory pool
470 mod->mempool = Mem_AllocPool(mod->name, 0, NULL);
472 num = LittleLong(*((int *)buf));
473 // call the apropriate loader
475 if (!strcasecmp(FS_FileExtension(mod->name), "obj")) Mod_OBJ_Load(mod, buf, bufend);
476 else if (!memcmp(buf, "IDPO", 4)) Mod_IDP0_Load(mod, buf, bufend);
477 else if (!memcmp(buf, "IDP2", 4)) Mod_IDP2_Load(mod, buf, bufend);
478 else if (!memcmp(buf, "IDP3", 4)) Mod_IDP3_Load(mod, buf, bufend);
479 else if (!memcmp(buf, "IDSP", 4)) Mod_IDSP_Load(mod, buf, bufend);
480 else if (!memcmp(buf, "IDS2", 4)) Mod_IDS2_Load(mod, buf, bufend);
481 else if (!memcmp(buf, "IBSP", 4)) Mod_IBSP_Load(mod, buf, bufend);
482 else if (!memcmp(buf, "ZYMOTICMODEL", 12)) Mod_ZYMOTICMODEL_Load(mod, buf, bufend);
483 else if (!memcmp(buf, "DARKPLACESMODEL", 16)) Mod_DARKPLACESMODEL_Load(mod, buf, bufend);
484 else if (!memcmp(buf, "ACTRHEAD", 8)) Mod_PSKMODEL_Load(mod, buf, bufend);
485 else if (!memcmp(buf, "INTERQUAKEMODEL", 16)) Mod_INTERQUAKEMODEL_Load(mod, buf, bufend);
486 else if (strlen(mod->name) >= 4 && !strcmp(mod->name + strlen(mod->name) - 4, ".map")) Mod_MAP_Load(mod, buf, bufend);
487 else if (num == BSPVERSION || num == 30) Mod_Q1BSP_Load(mod, buf, bufend);
488 else Con_Printf("Mod_LoadModel: model \"%s\" is of unknown/unsupported type\n", mod->name);
491 Mod_FindPotentialDeforms(mod);
493 buf = FS_LoadFile (va("%s.framegroups", mod->name), tempmempool, false, &filesize);
496 Mod_FrameGroupify(mod, (const char *)buf);
504 // LordHavoc: Sys_Error was *ANNOYING*
505 Con_Printf ("Mod_LoadModel: %s not found\n", mod->name);
508 // no fatal errors occurred, so this model is ready to use.
511 SCR_PopLoadingScreen(false);
516 void Mod_ClearUsed(void)
519 int nummodels = Mem_ExpandableArray_IndexRange(&models);
521 for (i = 0;i < nummodels;i++)
522 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0])
526 void Mod_PurgeUnused(void)
529 int nummodels = Mem_ExpandableArray_IndexRange(&models);
531 for (i = 0;i < nummodels;i++)
533 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && !mod->used)
535 Mod_UnloadModel(mod);
536 Mem_ExpandableArray_FreeRecord(&models, mod);
547 dp_model_t *Mod_FindName(const char *name, const char *parentname)
556 // if we're not dedicatd, the renderer calls will crash without video
559 nummodels = Mem_ExpandableArray_IndexRange(&models);
562 Host_Error ("Mod_ForName: NULL name");
564 // search the currently loaded models
565 for (i = 0;i < nummodels;i++)
567 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))))
574 // no match found, create a new one
575 mod = (dp_model_t *) Mem_ExpandableArray_AllocRecord(&models);
576 strlcpy(mod->name, name, sizeof(mod->name));
578 mod->brush.parentmodel = Mod_FindName(parentname, NULL);
580 mod->brush.parentmodel = NULL;
590 Loads in a model for the given name
593 dp_model_t *Mod_ForName(const char *name, qboolean crash, qboolean checkdisk, const char *parentname)
596 model = Mod_FindName(name, parentname);
597 if (!model->loaded || checkdisk)
598 Mod_LoadModel(model, crash, checkdisk);
606 Reloads all models if they have changed
609 void Mod_Reload(void)
612 int nummodels = Mem_ExpandableArray_IndexRange(&models);
615 SCR_PushLoadingScreen(false, "Reloading models", 1.0);
617 for (i = 0;i < nummodels;i++)
618 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*' && mod->used)
620 for (i = 0;i < nummodels;i++)
621 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*' && mod->used)
623 SCR_PushLoadingScreen(true, mod->name, 1.0 / count);
624 Mod_LoadModel(mod, true, true);
625 SCR_PopLoadingScreen(false);
627 SCR_PopLoadingScreen(false);
630 unsigned char *mod_base;
633 //=============================================================================
640 static void Mod_Print(void)
643 int nummodels = Mem_ExpandableArray_IndexRange(&models);
646 Con_Print("Loaded models:\n");
647 for (i = 0;i < nummodels;i++)
649 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
651 if (mod->brush.numsubmodels)
652 Con_Printf("%4iK %s (%i submodels)\n", mod->mempool ? (int)((mod->mempool->totalsize + 1023) / 1024) : 0, mod->name, mod->brush.numsubmodels);
654 Con_Printf("%4iK %s\n", mod->mempool ? (int)((mod->mempool->totalsize + 1023) / 1024) : 0, mod->name);
664 static void Mod_Precache(void)
667 Mod_ForName(Cmd_Argv(1), false, true, Cmd_Argv(1)[0] == '*' ? cl.model_name[1] : NULL);
669 Con_Print("usage: modelprecache <filename>\n");
672 int Mod_BuildVertexRemapTableFromElements(int numelements, const int *elements, int numvertices, int *remapvertices)
676 used = (unsigned char *)Mem_Alloc(tempmempool, numvertices);
677 memset(used, 0, numvertices);
678 for (i = 0;i < numelements;i++)
679 used[elements[i]] = 1;
680 for (i = 0, count = 0;i < numvertices;i++)
681 remapvertices[i] = used[i] ? count++ : -1;
687 // fast way, using an edge hash
688 #define TRIANGLEEDGEHASH 8192
689 void Mod_BuildTriangleNeighbors(int *neighbors, const int *elements, int numtriangles)
691 int i, j, p, e1, e2, *n, hashindex, count, match;
693 typedef struct edgehashentry_s
695 struct edgehashentry_s *next;
700 static edgehashentry_t **edgehash;
701 edgehashentry_t *edgehashentries, *hash;
704 edgehash = (edgehashentry_t **)Mem_Alloc(tempmempool, TRIANGLEEDGEHASH * sizeof(*edgehash));
705 // if there are too many triangles for the stack array, allocate larger buffer
706 edgehashentries = (edgehashentry_t *)Mem_Alloc(tempmempool, numtriangles * 3 * sizeof(edgehashentry_t));
707 // find neighboring triangles
708 for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
710 for (j = 0, p = 2;j < 3;p = j, j++)
714 // this hash index works for both forward and backward edges
715 hashindex = (unsigned int)(e1 + e2) % TRIANGLEEDGEHASH;
716 hash = edgehashentries + i * 3 + j;
717 hash->next = edgehash[hashindex];
718 edgehash[hashindex] = hash;
720 hash->element[0] = e1;
721 hash->element[1] = e2;
724 for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
726 for (j = 0, p = 2;j < 3;p = j, j++)
730 // this hash index works for both forward and backward edges
731 hashindex = (unsigned int)(e1 + e2) % TRIANGLEEDGEHASH;
734 for (hash = edgehash[hashindex];hash;hash = hash->next)
736 if (hash->element[0] == e2 && hash->element[1] == e1)
738 if (hash->triangle != i)
739 match = hash->triangle;
742 else if ((hash->element[0] == e1 && hash->element[1] == e2))
745 // detect edges shared by three triangles and make them seams
751 // also send a keepalive here (this can take a while too!)
752 CL_KeepaliveMessage(false);
754 // free the allocated buffer
755 Mem_Free(edgehashentries);
759 // very slow but simple way
760 static int Mod_FindTriangleWithEdge(const int *elements, int numtriangles, int start, int end, int ignore)
765 for (i = 0;i < numtriangles;i++, elements += 3)
767 if ((elements[0] == start && elements[1] == end)
768 || (elements[1] == start && elements[2] == end)
769 || (elements[2] == start && elements[0] == end))
775 else if ((elements[1] == start && elements[0] == end)
776 || (elements[2] == start && elements[1] == end)
777 || (elements[0] == start && elements[2] == end))
780 // detect edges shared by three triangles and make them seams
786 void Mod_BuildTriangleNeighbors(int *neighbors, const int *elements, int numtriangles)
790 for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
792 n[0] = Mod_FindTriangleWithEdge(elements, numtriangles, e[1], e[0], i);
793 n[1] = Mod_FindTriangleWithEdge(elements, numtriangles, e[2], e[1], i);
794 n[2] = Mod_FindTriangleWithEdge(elements, numtriangles, e[0], e[2], i);
799 void Mod_ValidateElements(int *elements, int numtriangles, int firstvertex, int numverts, const char *filename, int fileline)
801 int i, warned = false, endvertex = firstvertex + numverts;
802 for (i = 0;i < numtriangles * 3;i++)
804 if (elements[i] < firstvertex || elements[i] >= endvertex)
809 Con_Printf("Mod_ValidateElements: out of bounds elements detected at %s:%d\n", filename, fileline);
811 elements[i] = firstvertex;
816 // warning: this is an expensive function!
817 void Mod_BuildNormals(int firstvertex, int numvertices, int numtriangles, const float *vertex3f, const int *elements, float *normal3f, qboolean areaweighting)
824 memset(normal3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
825 // process each vertex of each triangle and accumulate the results
826 // use area-averaging, to make triangles with a big area have a bigger
827 // weighting on the vertex normal than triangles with a small area
828 // to do so, just add the 'normals' together (the bigger the area
829 // the greater the length of the normal is
831 for (i = 0; i < numtriangles; i++, element += 3)
834 vertex3f + element[0] * 3,
835 vertex3f + element[1] * 3,
836 vertex3f + element[2] * 3,
841 VectorNormalize(areaNormal);
843 for (j = 0;j < 3;j++)
845 vectorNormal = normal3f + element[j] * 3;
846 vectorNormal[0] += areaNormal[0];
847 vectorNormal[1] += areaNormal[1];
848 vectorNormal[2] += areaNormal[2];
851 // and just normalize the accumulated vertex normal in the end
852 vectorNormal = normal3f + 3 * firstvertex;
853 for (i = 0; i < numvertices; i++, vectorNormal += 3)
854 VectorNormalize(vectorNormal);
857 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)
859 float f, tangentcross[3], v10[3], v20[3], tc10[2], tc20[2];
860 // 79 add/sub/negate/multiply (1 cycle), 1 compare (3 cycle?), total cycles not counting load/store/exchange roughly 82 cycles
861 // 6 add, 28 subtract, 39 multiply, 1 compare, 50% chance of 6 negates
863 // 6 multiply, 9 subtract
864 VectorSubtract(v1, v0, v10);
865 VectorSubtract(v2, v0, v20);
866 normal3f[0] = v20[1] * v10[2] - v20[2] * v10[1];
867 normal3f[1] = v20[2] * v10[0] - v20[0] * v10[2];
868 normal3f[2] = v20[0] * v10[1] - v20[1] * v10[0];
869 // 12 multiply, 10 subtract
870 tc10[1] = tc1[1] - tc0[1];
871 tc20[1] = tc2[1] - tc0[1];
872 svector3f[0] = tc10[1] * v20[0] - tc20[1] * v10[0];
873 svector3f[1] = tc10[1] * v20[1] - tc20[1] * v10[1];
874 svector3f[2] = tc10[1] * v20[2] - tc20[1] * v10[2];
875 tc10[0] = tc1[0] - tc0[0];
876 tc20[0] = tc2[0] - tc0[0];
877 tvector3f[0] = tc10[0] * v20[0] - tc20[0] * v10[0];
878 tvector3f[1] = tc10[0] * v20[1] - tc20[0] * v10[1];
879 tvector3f[2] = tc10[0] * v20[2] - tc20[0] * v10[2];
880 // 12 multiply, 4 add, 6 subtract
881 f = DotProduct(svector3f, normal3f);
882 svector3f[0] -= f * normal3f[0];
883 svector3f[1] -= f * normal3f[1];
884 svector3f[2] -= f * normal3f[2];
885 f = DotProduct(tvector3f, normal3f);
886 tvector3f[0] -= f * normal3f[0];
887 tvector3f[1] -= f * normal3f[1];
888 tvector3f[2] -= f * normal3f[2];
889 // if texture is mapped the wrong way (counterclockwise), the tangents
890 // have to be flipped, this is detected by calculating a normal from the
891 // two tangents, and seeing if it is opposite the surface normal
892 // 9 multiply, 2 add, 3 subtract, 1 compare, 50% chance of: 6 negates
893 CrossProduct(tvector3f, svector3f, tangentcross);
894 if (DotProduct(tangentcross, normal3f) < 0)
896 VectorNegate(svector3f, svector3f);
897 VectorNegate(tvector3f, tvector3f);
901 // warning: this is a very expensive function!
902 void Mod_BuildTextureVectorsFromNormals(int firstvertex, int numvertices, int numtriangles, const float *vertex3f, const float *texcoord2f, const float *normal3f, const int *elements, float *svector3f, float *tvector3f, qboolean areaweighting)
905 float sdir[3], tdir[3], normal[3], *sv, *tv;
906 const float *v0, *v1, *v2, *tc0, *tc1, *tc2, *n;
907 float f, tangentcross[3], v10[3], v20[3], tc10[2], tc20[2];
910 memset(svector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
911 memset(tvector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
912 // process each vertex of each triangle and accumulate the results
913 for (tnum = 0, e = elements;tnum < numtriangles;tnum++, e += 3)
915 v0 = vertex3f + e[0] * 3;
916 v1 = vertex3f + e[1] * 3;
917 v2 = vertex3f + e[2] * 3;
918 tc0 = texcoord2f + e[0] * 2;
919 tc1 = texcoord2f + e[1] * 2;
920 tc2 = texcoord2f + e[2] * 2;
922 // 79 add/sub/negate/multiply (1 cycle), 1 compare (3 cycle?), total cycles not counting load/store/exchange roughly 82 cycles
923 // 6 add, 28 subtract, 39 multiply, 1 compare, 50% chance of 6 negates
925 // calculate the edge directions and surface normal
926 // 6 multiply, 9 subtract
927 VectorSubtract(v1, v0, v10);
928 VectorSubtract(v2, v0, v20);
929 normal[0] = v20[1] * v10[2] - v20[2] * v10[1];
930 normal[1] = v20[2] * v10[0] - v20[0] * v10[2];
931 normal[2] = v20[0] * v10[1] - v20[1] * v10[0];
933 // calculate the tangents
934 // 12 multiply, 10 subtract
935 tc10[1] = tc1[1] - tc0[1];
936 tc20[1] = tc2[1] - tc0[1];
937 sdir[0] = tc10[1] * v20[0] - tc20[1] * v10[0];
938 sdir[1] = tc10[1] * v20[1] - tc20[1] * v10[1];
939 sdir[2] = tc10[1] * v20[2] - tc20[1] * v10[2];
940 tc10[0] = tc1[0] - tc0[0];
941 tc20[0] = tc2[0] - tc0[0];
942 tdir[0] = tc10[0] * v20[0] - tc20[0] * v10[0];
943 tdir[1] = tc10[0] * v20[1] - tc20[0] * v10[1];
944 tdir[2] = tc10[0] * v20[2] - tc20[0] * v10[2];
946 // if texture is mapped the wrong way (counterclockwise), the tangents
947 // have to be flipped, this is detected by calculating a normal from the
948 // two tangents, and seeing if it is opposite the surface normal
949 // 9 multiply, 2 add, 3 subtract, 1 compare, 50% chance of: 6 negates
950 CrossProduct(tdir, sdir, tangentcross);
951 if (DotProduct(tangentcross, normal) < 0)
953 VectorNegate(sdir, sdir);
954 VectorNegate(tdir, tdir);
959 VectorNormalize(sdir);
960 VectorNormalize(tdir);
962 for (i = 0;i < 3;i++)
964 VectorAdd(svector3f + e[i]*3, sdir, svector3f + e[i]*3);
965 VectorAdd(tvector3f + e[i]*3, tdir, tvector3f + e[i]*3);
968 // make the tangents completely perpendicular to the surface normal, and
969 // then normalize them
970 // 16 assignments, 2 divide, 2 sqrt, 2 negates, 14 adds, 24 multiplies
971 for (i = 0, sv = svector3f + 3 * firstvertex, tv = tvector3f + 3 * firstvertex, n = normal3f + 3 * firstvertex;i < numvertices;i++, sv += 3, tv += 3, n += 3)
973 f = -DotProduct(sv, n);
974 VectorMA(sv, f, n, sv);
976 f = -DotProduct(tv, n);
977 VectorMA(tv, f, n, tv);
982 void Mod_AllocSurfMesh(mempool_t *mempool, int numvertices, int numtriangles, qboolean lightmapoffsets, qboolean vertexcolors, qboolean neighbors)
985 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));
986 loadmodel->surfmesh.num_vertices = numvertices;
987 loadmodel->surfmesh.num_triangles = numtriangles;
988 if (loadmodel->surfmesh.num_vertices)
990 loadmodel->surfmesh.data_vertex3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
991 loadmodel->surfmesh.data_svector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
992 loadmodel->surfmesh.data_tvector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
993 loadmodel->surfmesh.data_normal3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
994 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
995 loadmodel->surfmesh.data_texcoordlightmap2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
997 loadmodel->surfmesh.data_lightmapcolor4f = (float *)data, data += sizeof(float[4]) * loadmodel->surfmesh.num_vertices;
999 loadmodel->surfmesh.data_lightmapoffsets = (int *)data, data += sizeof(int) * loadmodel->surfmesh.num_vertices;
1001 if (loadmodel->surfmesh.num_triangles)
1003 loadmodel->surfmesh.data_element3i = (int *)data, data += sizeof(int[3]) * loadmodel->surfmesh.num_triangles;
1005 loadmodel->surfmesh.data_neighbor3i = (int *)data, data += sizeof(int[3]) * loadmodel->surfmesh.num_triangles;
1006 if (loadmodel->surfmesh.num_vertices <= 65536)
1007 loadmodel->surfmesh.data_element3s = (unsigned short *)data, data += sizeof(unsigned short[3]) * loadmodel->surfmesh.num_triangles;
1011 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)
1013 shadowmesh_t *newmesh;
1014 unsigned char *data;
1016 size = sizeof(shadowmesh_t);
1017 size += maxverts * sizeof(float[3]);
1019 size += maxverts * sizeof(float[11]);
1020 size += maxtriangles * sizeof(int[3]);
1021 if (maxverts <= 65536)
1022 size += maxtriangles * sizeof(unsigned short[3]);
1024 size += maxtriangles * sizeof(int[3]);
1026 size += SHADOWMESHVERTEXHASH * sizeof(shadowmeshvertexhash_t *) + maxverts * sizeof(shadowmeshvertexhash_t);
1027 data = (unsigned char *)Mem_Alloc(mempool, size);
1028 newmesh = (shadowmesh_t *)data;data += sizeof(*newmesh);
1029 newmesh->map_diffuse = map_diffuse;
1030 newmesh->map_specular = map_specular;
1031 newmesh->map_normal = map_normal;
1032 newmesh->maxverts = maxverts;
1033 newmesh->maxtriangles = maxtriangles;
1034 newmesh->numverts = 0;
1035 newmesh->numtriangles = 0;
1036 memset(newmesh->sideoffsets, 0, sizeof(newmesh->sideoffsets));
1037 memset(newmesh->sidetotals, 0, sizeof(newmesh->sidetotals));
1039 newmesh->vertex3f = (float *)data;data += maxverts * sizeof(float[3]);
1042 newmesh->svector3f = (float *)data;data += maxverts * sizeof(float[3]);
1043 newmesh->tvector3f = (float *)data;data += maxverts * sizeof(float[3]);
1044 newmesh->normal3f = (float *)data;data += maxverts * sizeof(float[3]);
1045 newmesh->texcoord2f = (float *)data;data += maxverts * sizeof(float[2]);
1047 newmesh->element3i = (int *)data;data += maxtriangles * sizeof(int[3]);
1050 newmesh->neighbor3i = (int *)data;data += maxtriangles * sizeof(int[3]);
1054 newmesh->vertexhashtable = (shadowmeshvertexhash_t **)data;data += SHADOWMESHVERTEXHASH * sizeof(shadowmeshvertexhash_t *);
1055 newmesh->vertexhashentries = (shadowmeshvertexhash_t *)data;data += maxverts * sizeof(shadowmeshvertexhash_t);
1057 if (maxverts <= 65536)
1058 newmesh->element3s = (unsigned short *)data;data += maxtriangles * sizeof(unsigned short[3]);
1062 shadowmesh_t *Mod_ShadowMesh_ReAlloc(mempool_t *mempool, shadowmesh_t *oldmesh, int light, int neighbors)
1064 shadowmesh_t *newmesh;
1065 newmesh = Mod_ShadowMesh_Alloc(mempool, oldmesh->numverts, oldmesh->numtriangles, oldmesh->map_diffuse, oldmesh->map_specular, oldmesh->map_normal, light, neighbors, false);
1066 newmesh->numverts = oldmesh->numverts;
1067 newmesh->numtriangles = oldmesh->numtriangles;
1068 memcpy(newmesh->sideoffsets, oldmesh->sideoffsets, sizeof(oldmesh->sideoffsets));
1069 memcpy(newmesh->sidetotals, oldmesh->sidetotals, sizeof(oldmesh->sidetotals));
1071 memcpy(newmesh->vertex3f, oldmesh->vertex3f, oldmesh->numverts * sizeof(float[3]));
1072 if (newmesh->svector3f && oldmesh->svector3f)
1074 memcpy(newmesh->svector3f, oldmesh->svector3f, oldmesh->numverts * sizeof(float[3]));
1075 memcpy(newmesh->tvector3f, oldmesh->tvector3f, oldmesh->numverts * sizeof(float[3]));
1076 memcpy(newmesh->normal3f, oldmesh->normal3f, oldmesh->numverts * sizeof(float[3]));
1077 memcpy(newmesh->texcoord2f, oldmesh->texcoord2f, oldmesh->numverts * sizeof(float[2]));
1079 memcpy(newmesh->element3i, oldmesh->element3i, oldmesh->numtriangles * sizeof(int[3]));
1080 if (newmesh->neighbor3i && oldmesh->neighbor3i)
1081 memcpy(newmesh->neighbor3i, oldmesh->neighbor3i, oldmesh->numtriangles * sizeof(int[3]));
1085 int Mod_ShadowMesh_AddVertex(shadowmesh_t *mesh, float *vertex14f)
1087 int hashindex, vnum;
1088 shadowmeshvertexhash_t *hash;
1089 // this uses prime numbers intentionally
1090 hashindex = (unsigned int) (vertex14f[0] * 2003 + vertex14f[1] * 4001 + vertex14f[2] * 7919) % SHADOWMESHVERTEXHASH;
1091 for (hash = mesh->vertexhashtable[hashindex];hash;hash = hash->next)
1093 vnum = (hash - mesh->vertexhashentries);
1094 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]))
1095 && (mesh->svector3f == NULL || (mesh->svector3f[vnum * 3 + 0] == vertex14f[3] && mesh->svector3f[vnum * 3 + 1] == vertex14f[4] && mesh->svector3f[vnum * 3 + 2] == vertex14f[5]))
1096 && (mesh->tvector3f == NULL || (mesh->tvector3f[vnum * 3 + 0] == vertex14f[6] && mesh->tvector3f[vnum * 3 + 1] == vertex14f[7] && mesh->tvector3f[vnum * 3 + 2] == vertex14f[8]))
1097 && (mesh->normal3f == NULL || (mesh->normal3f[vnum * 3 + 0] == vertex14f[9] && mesh->normal3f[vnum * 3 + 1] == vertex14f[10] && mesh->normal3f[vnum * 3 + 2] == vertex14f[11]))
1098 && (mesh->texcoord2f == NULL || (mesh->texcoord2f[vnum * 2 + 0] == vertex14f[12] && mesh->texcoord2f[vnum * 2 + 1] == vertex14f[13])))
1099 return hash - mesh->vertexhashentries;
1101 vnum = mesh->numverts++;
1102 hash = mesh->vertexhashentries + vnum;
1103 hash->next = mesh->vertexhashtable[hashindex];
1104 mesh->vertexhashtable[hashindex] = hash;
1105 if (mesh->vertex3f) {mesh->vertex3f[vnum * 3 + 0] = vertex14f[0];mesh->vertex3f[vnum * 3 + 1] = vertex14f[1];mesh->vertex3f[vnum * 3 + 2] = vertex14f[2];}
1106 if (mesh->svector3f) {mesh->svector3f[vnum * 3 + 0] = vertex14f[3];mesh->svector3f[vnum * 3 + 1] = vertex14f[4];mesh->svector3f[vnum * 3 + 2] = vertex14f[5];}
1107 if (mesh->tvector3f) {mesh->tvector3f[vnum * 3 + 0] = vertex14f[6];mesh->tvector3f[vnum * 3 + 1] = vertex14f[7];mesh->tvector3f[vnum * 3 + 2] = vertex14f[8];}
1108 if (mesh->normal3f) {mesh->normal3f[vnum * 3 + 0] = vertex14f[9];mesh->normal3f[vnum * 3 + 1] = vertex14f[10];mesh->normal3f[vnum * 3 + 2] = vertex14f[11];}
1109 if (mesh->texcoord2f) {mesh->texcoord2f[vnum * 2 + 0] = vertex14f[12];mesh->texcoord2f[vnum * 2 + 1] = vertex14f[13];}
1113 void Mod_ShadowMesh_AddTriangle(mempool_t *mempool, shadowmesh_t *mesh, rtexture_t *map_diffuse, rtexture_t *map_specular, rtexture_t *map_normal, float *vertex14f)
1115 if (mesh->numtriangles == 0)
1117 // set the properties on this empty mesh to be more favorable...
1118 // (note: this case only occurs for the first triangle added to a new mesh chain)
1119 mesh->map_diffuse = map_diffuse;
1120 mesh->map_specular = map_specular;
1121 mesh->map_normal = map_normal;
1123 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)
1125 if (mesh->next == NULL)
1126 mesh->next = Mod_ShadowMesh_Alloc(mempool, max(mesh->maxverts, 300), max(mesh->maxtriangles, 100), map_diffuse, map_specular, map_normal, mesh->svector3f != NULL, mesh->neighbor3i != NULL, true);
1129 mesh->element3i[mesh->numtriangles * 3 + 0] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 0);
1130 mesh->element3i[mesh->numtriangles * 3 + 1] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 1);
1131 mesh->element3i[mesh->numtriangles * 3 + 2] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 2);
1132 mesh->numtriangles++;
1135 void Mod_ShadowMesh_AddMesh(mempool_t *mempool, shadowmesh_t *mesh, rtexture_t *map_diffuse, rtexture_t *map_specular, rtexture_t *map_normal, const float *vertex3f, const float *svector3f, const float *tvector3f, const float *normal3f, const float *texcoord2f, int numtris, const int *element3i)
1138 float vbuf[3*14], *v;
1139 memset(vbuf, 0, sizeof(vbuf));
1140 for (i = 0;i < numtris;i++)
1142 for (j = 0, v = vbuf;j < 3;j++, v += 14)
1147 v[0] = vertex3f[e * 3 + 0];
1148 v[1] = vertex3f[e * 3 + 1];
1149 v[2] = vertex3f[e * 3 + 2];
1153 v[3] = svector3f[e * 3 + 0];
1154 v[4] = svector3f[e * 3 + 1];
1155 v[5] = svector3f[e * 3 + 2];
1159 v[6] = tvector3f[e * 3 + 0];
1160 v[7] = tvector3f[e * 3 + 1];
1161 v[8] = tvector3f[e * 3 + 2];
1165 v[9] = normal3f[e * 3 + 0];
1166 v[10] = normal3f[e * 3 + 1];
1167 v[11] = normal3f[e * 3 + 2];
1171 v[12] = texcoord2f[e * 2 + 0];
1172 v[13] = texcoord2f[e * 2 + 1];
1175 Mod_ShadowMesh_AddTriangle(mempool, mesh, map_diffuse, map_specular, map_normal, vbuf);
1178 // the triangle calculation can take a while, so let's do a keepalive here
1179 CL_KeepaliveMessage(false);
1182 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)
1184 // the preparation before shadow mesh initialization can take a while, so let's do a keepalive here
1185 CL_KeepaliveMessage(false);
1187 return Mod_ShadowMesh_Alloc(mempool, maxverts, maxtriangles, map_diffuse, map_specular, map_normal, light, neighbors, expandable);
1190 static void Mod_ShadowMesh_CreateVBOs(shadowmesh_t *mesh, mempool_t *mempool)
1192 if (!mesh->numverts)
1195 // build r_vertexmesh_t array
1196 // (compressed interleaved array for faster rendering)
1197 if (!mesh->vertexmesh && mesh->texcoord2f)
1200 int numvertices = mesh->numverts;
1201 r_vertexmesh_t *vertexmesh;
1202 mesh->vertexmesh = vertexmesh = (r_vertexmesh_t*)Mem_Alloc(mempool, numvertices * sizeof(*mesh->vertexmesh));
1203 for (vertexindex = 0;vertexindex < numvertices;vertexindex++, vertexmesh++)
1205 VectorCopy(mesh->vertex3f + 3*vertexindex, vertexmesh->vertex3f);
1206 VectorScale(mesh->svector3f + 3*vertexindex, 1.0f, vertexmesh->svector3f);
1207 VectorScale(mesh->tvector3f + 3*vertexindex, 1.0f, vertexmesh->tvector3f);
1208 VectorScale(mesh->normal3f + 3*vertexindex, 1.0f, vertexmesh->normal3f);
1209 Vector2Copy(mesh->texcoord2f + 2*vertexindex, vertexmesh->texcoordtexture2f);
1213 // build r_vertexposition_t array
1214 if (!mesh->vertexposition)
1217 int numvertices = mesh->numverts;
1218 r_vertexposition_t *vertexposition;
1219 mesh->vertexposition = vertexposition = (r_vertexposition_t*)Mem_Alloc(loadmodel->mempool, numvertices * sizeof(*mesh->vertexposition));
1220 for (vertexindex = 0;vertexindex < numvertices;vertexindex++, vertexposition++)
1221 VectorCopy(mesh->vertex3f + 3*vertexindex, vertexposition->vertex3f);
1224 // upload r_vertexmesh_t array as a buffer
1225 if (mesh->vertexmesh && !mesh->vertexmeshbuffer)
1226 mesh->vertexmeshbuffer = R_Mesh_CreateMeshBuffer(mesh->vertexmesh, mesh->numverts * sizeof(*mesh->vertexmesh), loadmodel->name, false, false, false);
1228 // upload r_vertexposition_t array as a buffer
1229 if (mesh->vertexposition && !mesh->vertexpositionbuffer)
1230 mesh->vertexpositionbuffer = R_Mesh_CreateMeshBuffer(mesh->vertexposition, mesh->numverts * sizeof(*mesh->vertexposition), loadmodel->name, false, false, false);
1232 // upload short indices as a buffer
1233 if (mesh->element3s && !mesh->element3s_indexbuffer)
1234 mesh->element3s_indexbuffer = R_Mesh_CreateMeshBuffer(mesh->element3s, mesh->numtriangles * sizeof(short[3]), loadmodel->name, true, false, true);
1236 // upload int indices as a buffer
1237 if (mesh->element3i && !mesh->element3i_indexbuffer && !mesh->element3s)
1238 mesh->element3i_indexbuffer = R_Mesh_CreateMeshBuffer(mesh->element3i, mesh->numtriangles * sizeof(int[3]), loadmodel->name, true, false, false);
1240 // vertex buffer is several arrays and we put them in the same buffer
1242 // is this wise? the texcoordtexture2f array is used with dynamic
1243 // vertex/svector/tvector/normal when rendering animated models, on the
1244 // other hand animated models don't use a lot of vertices anyway...
1245 if (!mesh->vbo_vertexbuffer)
1250 mesh->vbooffset_vertex3f = size;if (mesh->vertex3f ) size += mesh->numverts * sizeof(float[3]);
1251 mesh->vbooffset_svector3f = size;if (mesh->svector3f ) size += mesh->numverts * sizeof(float[3]);
1252 mesh->vbooffset_tvector3f = size;if (mesh->tvector3f ) size += mesh->numverts * sizeof(float[3]);
1253 mesh->vbooffset_normal3f = size;if (mesh->normal3f ) size += mesh->numverts * sizeof(float[3]);
1254 mesh->vbooffset_texcoord2f = size;if (mesh->texcoord2f ) size += mesh->numverts * sizeof(float[2]);
1255 mem = (unsigned char *)Mem_Alloc(tempmempool, size);
1256 if (mesh->vertex3f ) memcpy(mem + mesh->vbooffset_vertex3f , mesh->vertex3f , mesh->numverts * sizeof(float[3]));
1257 if (mesh->svector3f ) memcpy(mem + mesh->vbooffset_svector3f , mesh->svector3f , mesh->numverts * sizeof(float[3]));
1258 if (mesh->tvector3f ) memcpy(mem + mesh->vbooffset_tvector3f , mesh->tvector3f , mesh->numverts * sizeof(float[3]));
1259 if (mesh->normal3f ) memcpy(mem + mesh->vbooffset_normal3f , mesh->normal3f , mesh->numverts * sizeof(float[3]));
1260 if (mesh->texcoord2f ) memcpy(mem + mesh->vbooffset_texcoord2f , mesh->texcoord2f , mesh->numverts * sizeof(float[2]));
1261 mesh->vbo_vertexbuffer = R_Mesh_CreateMeshBuffer(mem, size, "shadowmesh", false, false, false);
1266 shadowmesh_t *Mod_ShadowMesh_Finish(mempool_t *mempool, shadowmesh_t *firstmesh, qboolean light, qboolean neighbors, qboolean createvbo)
1268 shadowmesh_t *mesh, *newmesh, *nextmesh;
1269 // reallocate meshs to conserve space
1270 for (mesh = firstmesh, firstmesh = NULL;mesh;mesh = nextmesh)
1272 nextmesh = mesh->next;
1273 if (mesh->numverts >= 3 && mesh->numtriangles >= 1)
1275 newmesh = Mod_ShadowMesh_ReAlloc(mempool, mesh, light, neighbors);
1276 newmesh->next = firstmesh;
1277 firstmesh = newmesh;
1278 if (newmesh->element3s)
1281 for (i = 0;i < newmesh->numtriangles*3;i++)
1282 newmesh->element3s[i] = newmesh->element3i[i];
1285 Mod_ShadowMesh_CreateVBOs(newmesh, mempool);
1290 // this can take a while, so let's do a keepalive here
1291 CL_KeepaliveMessage(false);
1296 void Mod_ShadowMesh_CalcBBox(shadowmesh_t *firstmesh, vec3_t mins, vec3_t maxs, vec3_t center, float *radius)
1300 vec3_t nmins, nmaxs, ncenter, temp;
1301 float nradius2, dist2, *v;
1305 for (mesh = firstmesh;mesh;mesh = mesh->next)
1307 if (mesh == firstmesh)
1309 VectorCopy(mesh->vertex3f, nmins);
1310 VectorCopy(mesh->vertex3f, nmaxs);
1312 for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
1314 if (nmins[0] > v[0]) nmins[0] = v[0];if (nmaxs[0] < v[0]) nmaxs[0] = v[0];
1315 if (nmins[1] > v[1]) nmins[1] = v[1];if (nmaxs[1] < v[1]) nmaxs[1] = v[1];
1316 if (nmins[2] > v[2]) nmins[2] = v[2];if (nmaxs[2] < v[2]) nmaxs[2] = v[2];
1319 // calculate center and radius
1320 ncenter[0] = (nmins[0] + nmaxs[0]) * 0.5f;
1321 ncenter[1] = (nmins[1] + nmaxs[1]) * 0.5f;
1322 ncenter[2] = (nmins[2] + nmaxs[2]) * 0.5f;
1324 for (mesh = firstmesh;mesh;mesh = mesh->next)
1326 for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
1328 VectorSubtract(v, ncenter, temp);
1329 dist2 = DotProduct(temp, temp);
1330 if (nradius2 < dist2)
1336 VectorCopy(nmins, mins);
1338 VectorCopy(nmaxs, maxs);
1340 VectorCopy(ncenter, center);
1342 *radius = sqrt(nradius2);
1345 void Mod_ShadowMesh_Free(shadowmesh_t *mesh)
1347 shadowmesh_t *nextmesh;
1348 for (;mesh;mesh = nextmesh)
1350 if (mesh->vertexpositionbuffer)
1351 R_Mesh_DestroyMeshBuffer(mesh->vertexpositionbuffer);
1352 if (mesh->vertexmeshbuffer)
1353 R_Mesh_DestroyMeshBuffer(mesh->vertexmeshbuffer);
1354 if (mesh->element3i_indexbuffer)
1355 R_Mesh_DestroyMeshBuffer(mesh->element3i_indexbuffer);
1356 if (mesh->element3s_indexbuffer)
1357 R_Mesh_DestroyMeshBuffer(mesh->element3s_indexbuffer);
1358 if (mesh->vbo_vertexbuffer)
1359 R_Mesh_DestroyMeshBuffer(mesh->vbo_vertexbuffer);
1360 nextmesh = mesh->next;
1365 void Mod_CreateCollisionMesh(dp_model_t *mod)
1367 int k, numcollisionmeshtriangles;
1368 qboolean usesinglecollisionmesh = false;
1369 const msurface_t *surface = NULL;
1371 mempool_t *mempool = mod->mempool;
1372 if (!mempool && mod->brush.parentmodel)
1373 mempool = mod->brush.parentmodel->mempool;
1374 // make a single combined collision mesh for physics engine use
1375 // TODO rewrite this to use the collision brushes as source, to fix issues with e.g. common/caulk which creates no drawsurface
1376 numcollisionmeshtriangles = 0;
1377 for (k = 0;k < mod->nummodelsurfaces;k++)
1379 surface = mod->data_surfaces + mod->firstmodelsurface + k;
1380 if (!strcmp(surface->texture->name, "collision")) // found collision mesh
1382 usesinglecollisionmesh = true;
1383 numcollisionmeshtriangles = surface->num_triangles;
1386 if (!(surface->texture->supercontents & SUPERCONTENTS_SOLID))
1388 numcollisionmeshtriangles += surface->num_triangles;
1390 mod->brush.collisionmesh = Mod_ShadowMesh_Begin(mempool, numcollisionmeshtriangles * 3, numcollisionmeshtriangles, NULL, NULL, NULL, false, false, true);
1391 if (usesinglecollisionmesh)
1392 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));
1395 for (k = 0;k < mod->nummodelsurfaces;k++)
1397 surface = mod->data_surfaces + mod->firstmodelsurface + k;
1398 if (!(surface->texture->supercontents & SUPERCONTENTS_SOLID))
1400 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));
1403 mod->brush.collisionmesh = Mod_ShadowMesh_Finish(mempool, mod->brush.collisionmesh, false, true, false);
1406 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)
1411 if (ix >= 0 && iy >= 0 && ix < imagewidth && iy < imageheight)
1412 v[2] = (imagepixels[((iy*imagewidth)+ix)*4+0] + imagepixels[((iy*imagewidth)+ix)*4+1] + imagepixels[((iy*imagewidth)+ix)*4+2]) * (1.0f / 765.0f);
1415 Matrix4x4_Transform(pixelstepmatrix, v, vertex3f);
1416 Matrix4x4_Transform(pixeltexturestepmatrix, v, tc);
1417 texcoord2f[0] = tc[0];
1418 texcoord2f[1] = tc[1];
1421 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)
1423 float vup[3], vdown[3], vleft[3], vright[3];
1424 float tcup[3], tcdown[3], tcleft[3], tcright[3];
1425 float sv[3], tv[3], nl[3];
1426 Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, pixelstepmatrix, pixeltexturestepmatrix);
1427 Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy - 1, vup, tcup, pixelstepmatrix, pixeltexturestepmatrix);
1428 Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy + 1, vdown, tcdown, pixelstepmatrix, pixeltexturestepmatrix);
1429 Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix - 1, iy, vleft, tcleft, pixelstepmatrix, pixeltexturestepmatrix);
1430 Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix + 1, iy, vright, tcright, pixelstepmatrix, pixeltexturestepmatrix);
1431 Mod_BuildBumpVectors(vertex3f, vup, vright, texcoord2f, tcup, tcright, svector3f, tvector3f, normal3f);
1432 Mod_BuildBumpVectors(vertex3f, vright, vdown, texcoord2f, tcright, tcdown, sv, tv, nl);
1433 VectorAdd(svector3f, sv, svector3f);
1434 VectorAdd(tvector3f, tv, tvector3f);
1435 VectorAdd(normal3f, nl, normal3f);
1436 Mod_BuildBumpVectors(vertex3f, vdown, vleft, texcoord2f, tcdown, tcleft, sv, tv, nl);
1437 VectorAdd(svector3f, sv, svector3f);
1438 VectorAdd(tvector3f, tv, tvector3f);
1439 VectorAdd(normal3f, nl, normal3f);
1440 Mod_BuildBumpVectors(vertex3f, vleft, vup, texcoord2f, tcleft, tcup, sv, tv, nl);
1441 VectorAdd(svector3f, sv, svector3f);
1442 VectorAdd(tvector3f, tv, tvector3f);
1443 VectorAdd(normal3f, nl, normal3f);
1446 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)
1448 int x, y, ix, iy, *e;
1450 for (y = 0;y < height;y++)
1452 for (x = 0;x < width;x++)
1454 e[0] = (y + 1) * (width + 1) + (x + 0);
1455 e[1] = (y + 0) * (width + 1) + (x + 0);
1456 e[2] = (y + 1) * (width + 1) + (x + 1);
1457 e[3] = (y + 0) * (width + 1) + (x + 0);
1458 e[4] = (y + 0) * (width + 1) + (x + 1);
1459 e[5] = (y + 1) * (width + 1) + (x + 1);
1463 Mod_BuildTriangleNeighbors(neighbor3i, element3i, width*height*2);
1464 for (y = 0, iy = y1;y < height + 1;y++, iy++)
1465 for (x = 0, ix = x1;x < width + 1;x++, ix++, vertex3f += 3, texcoord2f += 2, svector3f += 3, tvector3f += 3, normal3f += 3)
1466 Mod_GetTerrainVertexFromBGRA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, svector3f, tvector3f, normal3f, pixelstepmatrix, pixeltexturestepmatrix);
1470 void Mod_Terrain_SurfaceRecurseChunk(dp_model_t *model, int stepsize, int x, int y)
1474 float chunkwidth = min(stepsize, model->terrain.width - 1 - x);
1475 float chunkheight = min(stepsize, model->terrain.height - 1 - y);
1476 float viewvector[3];
1477 unsigned int firstvertex;
1480 if (chunkwidth < 2 || chunkheight < 2)
1482 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]);
1483 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]);
1484 viewvector[0] = bound(mins[0], localvieworigin, maxs[0]) - model->terrain.vieworigin[0];
1485 viewvector[1] = bound(mins[1], localvieworigin, maxs[1]) - model->terrain.vieworigin[1];
1486 viewvector[2] = bound(mins[2], localvieworigin, maxs[2]) - model->terrain.vieworigin[2];
1487 if (stepsize > 1 && VectorLength(viewvector) < stepsize*model->terrain.scale[0]*r_terrain_lodscale.value)
1489 // too close for this stepsize, emit as 4 chunks instead
1491 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x, y);
1492 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x+stepsize, y);
1493 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x, y+stepsize);
1494 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x+stepsize, y+stepsize);
1497 // emit the geometry at stepsize into our vertex buffer / index buffer
1498 // we add two columns and two rows for skirt
1499 outwidth = chunkwidth+2;
1500 outheight = chunkheight+2;
1501 outwidth2 = outwidth-1;
1502 outheight2 = outheight-1;
1503 outwidth3 = outwidth+1;
1504 outheight3 = outheight+1;
1505 firstvertex = numvertices;
1506 e = model->terrain.element3i + numtriangles;
1507 numtriangles += chunkwidth*chunkheight*2+chunkwidth*2*2+chunkheight*2*2;
1508 v = model->terrain.vertex3f + numvertices;
1509 numvertices += (chunkwidth+1)*(chunkheight+1)+(chunkwidth+1)*2+(chunkheight+1)*2;
1510 // emit the triangles (note: the skirt is treated as two extra rows and two extra columns)
1511 for (ty = 0;ty < outheight;ty++)
1513 for (tx = 0;tx < outwidth;tx++)
1515 *e++ = firstvertex + (ty )*outwidth3+(tx );
1516 *e++ = firstvertex + (ty )*outwidth3+(tx+1);
1517 *e++ = firstvertex + (ty+1)*outwidth3+(tx+1);
1518 *e++ = firstvertex + (ty )*outwidth3+(tx );
1519 *e++ = firstvertex + (ty+1)*outwidth3+(tx+1);
1520 *e++ = firstvertex + (ty+1)*outwidth3+(tx );
1523 // TODO: emit surface vertices (x+tx*stepsize, y+ty*stepsize)
1524 for (ty = 0;ty <= outheight;ty++)
1526 skirtrow = ty == 0 || ty == outheight;
1527 ry = y+bound(1, ty, outheight)*stepsize;
1528 for (tx = 0;tx <= outwidth;tx++)
1530 skirt = skirtrow || tx == 0 || tx == outwidth;
1531 rx = x+bound(1, tx, outwidth)*stepsize;
1534 v[2] = heightmap[ry*terrainwidth+rx]*scale[2];
1538 // TODO: emit skirt vertices
1541 void Mod_Terrain_UpdateSurfacesForViewOrigin(dp_model_t *model)
1543 for (y = 0;y < model->terrain.size[1];y += model->terrain.
1544 Mod_Terrain_SurfaceRecurseChunk(model, model->terrain.maxstepsize, x, y);
1545 Mod_Terrain_BuildChunk(model,
1549 int Mod_LoadQ3Shaders_EnumerateWaveFunc(const char *s)
1552 if (!strncasecmp(s, "user", 4)) // parse stuff like "user1sin", always user<n>func
1554 offset = bound(0, s[4] - '0', 9);
1555 offset = (offset + 1) << Q3WAVEFUNC_USER_SHIFT;
1560 if (!strcasecmp(s, "sin")) return offset | Q3WAVEFUNC_SIN;
1561 if (!strcasecmp(s, "square")) return offset | Q3WAVEFUNC_SQUARE;
1562 if (!strcasecmp(s, "triangle")) return offset | Q3WAVEFUNC_TRIANGLE;
1563 if (!strcasecmp(s, "sawtooth")) return offset | Q3WAVEFUNC_SAWTOOTH;
1564 if (!strcasecmp(s, "inversesawtooth")) return offset | Q3WAVEFUNC_INVERSESAWTOOTH;
1565 if (!strcasecmp(s, "noise")) return offset | Q3WAVEFUNC_NOISE;
1566 if (!strcasecmp(s, "none")) return offset | Q3WAVEFUNC_NONE;
1567 Con_DPrintf("Mod_LoadQ3Shaders: unknown wavefunc %s\n", s);
1568 return offset | Q3WAVEFUNC_NONE;
1571 void Mod_FreeQ3Shaders(void)
1573 Mem_FreePool(&q3shaders_mem);
1576 static void Q3Shader_AddToHash (q3shaderinfo_t* shader)
1578 unsigned short hash = CRC_Block_CaseInsensitive ((const unsigned char *)shader->name, strlen (shader->name));
1579 q3shader_hash_entry_t* entry = q3shader_data->hash + (hash % Q3SHADER_HASH_SIZE);
1580 q3shader_hash_entry_t* lastEntry = NULL;
1581 while (entry != NULL)
1583 if (strcasecmp (entry->shader.name, shader->name) == 0)
1585 unsigned char *start, *end, *start2;
1586 start = (unsigned char *) (&shader->Q3SHADERINFO_COMPARE_START);
1587 end = ((unsigned char *) (&shader->Q3SHADERINFO_COMPARE_END)) + sizeof(shader->Q3SHADERINFO_COMPARE_END);
1588 start2 = (unsigned char *) (&entry->shader.Q3SHADERINFO_COMPARE_START);
1589 if(memcmp(start, start2, end - start))
1590 Con_DPrintf("Shader '%s' already defined, ignoring mismatching redeclaration\n", shader->name);
1592 Con_DPrintf("Shader '%s' already defined\n", shader->name);
1596 entry = entry->chain;
1600 if (lastEntry->shader.name[0] != 0)
1603 q3shader_hash_entry_t* newEntry = (q3shader_hash_entry_t*)
1604 Mem_ExpandableArray_AllocRecord (&q3shader_data->hash_entries);
1606 while (lastEntry->chain != NULL) lastEntry = lastEntry->chain;
1607 lastEntry->chain = newEntry;
1608 newEntry->chain = NULL;
1609 lastEntry = newEntry;
1611 /* else: head of chain, in hash entry array */
1614 memcpy (&entry->shader, shader, sizeof (q3shaderinfo_t));
1617 extern cvar_t mod_q3shader_default_offsetmapping;
1618 extern cvar_t mod_q3shader_default_polygonoffset;
1619 extern cvar_t mod_q3shader_default_polygonfactor;
1620 void Mod_LoadQ3Shaders(void)
1627 q3shaderinfo_t shader;
1628 q3shaderinfo_layer_t *layer;
1630 char parameter[TEXTURE_MAXFRAMES + 4][Q3PATHLENGTH];
1631 char *custsurfaceparmnames[256]; // VorteX: q3map2 has 64 but well, someone will need more
1632 unsigned long custsurfaceparms[256];
1633 int numcustsurfaceparms;
1635 Mod_FreeQ3Shaders();
1637 q3shaders_mem = Mem_AllocPool("q3shaders", 0, NULL);
1638 q3shader_data = (q3shader_data_t*)Mem_Alloc (q3shaders_mem,
1639 sizeof (q3shader_data_t));
1640 Mem_ExpandableArray_NewArray (&q3shader_data->hash_entries,
1641 q3shaders_mem, sizeof (q3shader_hash_entry_t), 256);
1642 Mem_ExpandableArray_NewArray (&q3shader_data->char_ptrs,
1643 q3shaders_mem, sizeof (char**), 256);
1645 // parse custinfoparms.txt
1646 numcustsurfaceparms = 0;
1647 if ((text = f = (char *)FS_LoadFile("scripts/custinfoparms.txt", tempmempool, false, NULL)) != NULL)
1649 if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1650 Con_DPrintf("scripts/custinfoparms.txt: contentflags section parsing error - expected \"{\", found \"%s\"\n", com_token);
1653 while (COM_ParseToken_QuakeC(&text, false))
1654 if (!strcasecmp(com_token, "}"))
1656 // custom surfaceflags section
1657 if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1658 Con_DPrintf("scripts/custinfoparms.txt: surfaceflags section parsing error - expected \"{\", found \"%s\"\n", com_token);
1661 while(COM_ParseToken_QuakeC(&text, false))
1663 if (!strcasecmp(com_token, "}"))
1665 // register surfaceflag
1666 if (numcustsurfaceparms >= 256)
1668 Con_Printf("scripts/custinfoparms.txt: surfaceflags section parsing error - max 256 surfaceflags exceeded\n");
1672 j = strlen(com_token)+1;
1673 custsurfaceparmnames[numcustsurfaceparms] = (char *)Mem_Alloc(tempmempool, j);
1674 strlcpy(custsurfaceparmnames[numcustsurfaceparms], com_token, j+1);
1676 if (COM_ParseToken_QuakeC(&text, false))
1677 custsurfaceparms[numcustsurfaceparms] = strtol(com_token, NULL, 0);
1679 custsurfaceparms[numcustsurfaceparms] = 0;
1680 numcustsurfaceparms++;
1688 search = FS_Search("scripts/*.shader", true, false);
1691 for (fileindex = 0;fileindex < search->numfilenames;fileindex++)
1693 text = f = (char *)FS_LoadFile(search->filenames[fileindex], tempmempool, false, NULL);
1696 while (COM_ParseToken_QuakeC(&text, false))
1698 memset (&shader, 0, sizeof(shader));
1699 shader.reflectmin = 0;
1700 shader.reflectmax = 1;
1701 shader.refractfactor = 1;
1702 Vector4Set(shader.refractcolor4f, 1, 1, 1, 1);
1703 shader.reflectfactor = 1;
1704 Vector4Set(shader.reflectcolor4f, 1, 1, 1, 1);
1705 shader.r_water_wateralpha = 1;
1706 shader.offsetmapping = (mod_q3shader_default_offsetmapping.value) ? OFFSETMAPPING_DEFAULT : OFFSETMAPPING_OFF;
1707 shader.offsetscale = 1;
1708 shader.specularscalemod = 1;
1709 shader.specularpowermod = 1;
1710 shader.biaspolygonoffset = mod_q3shader_default_polygonoffset.value;
1711 shader.biaspolygonfactor = mod_q3shader_default_polygonfactor.value;
1713 strlcpy(shader.name, com_token, sizeof(shader.name));
1714 if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1716 Con_DPrintf("%s parsing error - expected \"{\", found \"%s\"\n", search->filenames[fileindex], com_token);
1719 while (COM_ParseToken_QuakeC(&text, false))
1721 if (!strcasecmp(com_token, "}"))
1723 if (!strcasecmp(com_token, "{"))
1725 static q3shaderinfo_layer_t dummy;
1726 if (shader.numlayers < Q3SHADER_MAXLAYERS)
1728 layer = shader.layers + shader.numlayers++;
1732 // parse and process it anyway, just don't store it (so a map $lightmap or such stuff still is found)
1733 memset(&dummy, 0, sizeof(dummy));
1736 layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1737 layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1738 layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1739 layer->blendfunc[0] = GL_ONE;
1740 layer->blendfunc[1] = GL_ZERO;
1741 while (COM_ParseToken_QuakeC(&text, false))
1743 if (!strcasecmp(com_token, "}"))
1745 if (!strcasecmp(com_token, "\n"))
1748 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1750 if (j < TEXTURE_MAXFRAMES + 4)
1752 // remap dp_water to dpwater, dp_reflect to dpreflect, etc.
1753 if(j == 0 && !strncasecmp(com_token, "dp_", 3))
1754 dpsnprintf(parameter[j], sizeof(parameter[j]), "dp%s", &com_token[3]);
1756 strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1757 numparameters = j + 1;
1759 if (!COM_ParseToken_QuakeC(&text, true))
1762 //for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1763 // parameter[j][0] = 0;
1764 if (developer_insane.integer)
1766 Con_DPrintf("%s %i: ", shader.name, shader.numlayers - 1);
1767 for (j = 0;j < numparameters;j++)
1768 Con_DPrintf(" %s", parameter[j]);
1771 if (numparameters >= 2 && !strcasecmp(parameter[0], "blendfunc"))
1773 if (numparameters == 2)
1775 if (!strcasecmp(parameter[1], "add"))
1777 layer->blendfunc[0] = GL_ONE;
1778 layer->blendfunc[1] = GL_ONE;
1780 else if (!strcasecmp(parameter[1], "filter"))
1782 layer->blendfunc[0] = GL_DST_COLOR;
1783 layer->blendfunc[1] = GL_ZERO;
1785 else if (!strcasecmp(parameter[1], "blend"))
1787 layer->blendfunc[0] = GL_SRC_ALPHA;
1788 layer->blendfunc[1] = GL_ONE_MINUS_SRC_ALPHA;
1791 else if (numparameters == 3)
1794 for (k = 0;k < 2;k++)
1796 if (!strcasecmp(parameter[k+1], "GL_ONE"))
1797 layer->blendfunc[k] = GL_ONE;
1798 else if (!strcasecmp(parameter[k+1], "GL_ZERO"))
1799 layer->blendfunc[k] = GL_ZERO;
1800 else if (!strcasecmp(parameter[k+1], "GL_SRC_COLOR"))
1801 layer->blendfunc[k] = GL_SRC_COLOR;
1802 else if (!strcasecmp(parameter[k+1], "GL_SRC_ALPHA"))
1803 layer->blendfunc[k] = GL_SRC_ALPHA;
1804 else if (!strcasecmp(parameter[k+1], "GL_DST_COLOR"))
1805 layer->blendfunc[k] = GL_DST_COLOR;
1806 else if (!strcasecmp(parameter[k+1], "GL_DST_ALPHA"))
1807 layer->blendfunc[k] = GL_ONE_MINUS_DST_ALPHA;
1808 else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_COLOR"))
1809 layer->blendfunc[k] = GL_ONE_MINUS_SRC_COLOR;
1810 else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_ALPHA"))
1811 layer->blendfunc[k] = GL_ONE_MINUS_SRC_ALPHA;
1812 else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_COLOR"))
1813 layer->blendfunc[k] = GL_ONE_MINUS_DST_COLOR;
1814 else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_ALPHA"))
1815 layer->blendfunc[k] = GL_ONE_MINUS_DST_ALPHA;
1817 layer->blendfunc[k] = GL_ONE; // default in case of parsing error
1821 if (numparameters >= 2 && !strcasecmp(parameter[0], "alphafunc"))
1822 layer->alphatest = true;
1823 if (numparameters >= 2 && (!strcasecmp(parameter[0], "map") || !strcasecmp(parameter[0], "clampmap")))
1825 if (!strcasecmp(parameter[0], "clampmap"))
1826 layer->clampmap = true;
1827 layer->numframes = 1;
1828 layer->framerate = 1;
1829 layer->texturename = (char**)Mem_ExpandableArray_AllocRecord (
1830 &q3shader_data->char_ptrs);
1831 layer->texturename[0] = Mem_strdup (q3shaders_mem, parameter[1]);
1832 if (!strcasecmp(parameter[1], "$lightmap"))
1833 shader.lighting = true;
1835 else if (numparameters >= 3 && (!strcasecmp(parameter[0], "animmap") || !strcasecmp(parameter[0], "animclampmap")))
1838 layer->numframes = min(numparameters - 2, TEXTURE_MAXFRAMES);
1839 layer->framerate = atof(parameter[1]);
1840 layer->texturename = (char **) Mem_Alloc (q3shaders_mem, sizeof (char*) * layer->numframes);
1841 for (i = 0;i < layer->numframes;i++)
1842 layer->texturename[i] = Mem_strdup (q3shaders_mem, parameter[i + 2]);
1844 else if (numparameters >= 2 && !strcasecmp(parameter[0], "rgbgen"))
1847 for (i = 0;i < numparameters - 2 && i < Q3RGBGEN_MAXPARMS;i++)
1848 layer->rgbgen.parms[i] = atof(parameter[i+2]);
1849 if (!strcasecmp(parameter[1], "identity")) layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1850 else if (!strcasecmp(parameter[1], "const")) layer->rgbgen.rgbgen = Q3RGBGEN_CONST;
1851 else if (!strcasecmp(parameter[1], "entity")) layer->rgbgen.rgbgen = Q3RGBGEN_ENTITY;
1852 else if (!strcasecmp(parameter[1], "exactvertex")) layer->rgbgen.rgbgen = Q3RGBGEN_EXACTVERTEX;
1853 else if (!strcasecmp(parameter[1], "identitylighting")) layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITYLIGHTING;
1854 else if (!strcasecmp(parameter[1], "lightingdiffuse")) layer->rgbgen.rgbgen = Q3RGBGEN_LIGHTINGDIFFUSE;
1855 else if (!strcasecmp(parameter[1], "oneminusentity")) layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSENTITY;
1856 else if (!strcasecmp(parameter[1], "oneminusvertex")) layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSVERTEX;
1857 else if (!strcasecmp(parameter[1], "vertex")) layer->rgbgen.rgbgen = Q3RGBGEN_VERTEX;
1858 else if (!strcasecmp(parameter[1], "wave"))
1860 layer->rgbgen.rgbgen = Q3RGBGEN_WAVE;
1861 layer->rgbgen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1862 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1863 layer->rgbgen.waveparms[i] = atof(parameter[i+3]);
1865 else Con_DPrintf("%s parsing warning: unknown rgbgen %s\n", search->filenames[fileindex], parameter[1]);
1867 else if (numparameters >= 2 && !strcasecmp(parameter[0], "alphagen"))
1870 for (i = 0;i < numparameters - 2 && i < Q3ALPHAGEN_MAXPARMS;i++)
1871 layer->alphagen.parms[i] = atof(parameter[i+2]);
1872 if (!strcasecmp(parameter[1], "identity")) layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1873 else if (!strcasecmp(parameter[1], "const")) layer->alphagen.alphagen = Q3ALPHAGEN_CONST;
1874 else if (!strcasecmp(parameter[1], "entity")) layer->alphagen.alphagen = Q3ALPHAGEN_ENTITY;
1875 else if (!strcasecmp(parameter[1], "lightingspecular")) layer->alphagen.alphagen = Q3ALPHAGEN_LIGHTINGSPECULAR;
1876 else if (!strcasecmp(parameter[1], "oneminusentity")) layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSENTITY;
1877 else if (!strcasecmp(parameter[1], "oneminusvertex")) layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSVERTEX;
1878 else if (!strcasecmp(parameter[1], "portal")) layer->alphagen.alphagen = Q3ALPHAGEN_PORTAL;
1879 else if (!strcasecmp(parameter[1], "vertex")) layer->alphagen.alphagen = Q3ALPHAGEN_VERTEX;
1880 else if (!strcasecmp(parameter[1], "wave"))
1882 layer->alphagen.alphagen = Q3ALPHAGEN_WAVE;
1883 layer->alphagen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1884 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1885 layer->alphagen.waveparms[i] = atof(parameter[i+3]);
1887 else Con_DPrintf("%s parsing warning: unknown alphagen %s\n", search->filenames[fileindex], parameter[1]);
1889 else if (numparameters >= 2 && (!strcasecmp(parameter[0], "texgen") || !strcasecmp(parameter[0], "tcgen")))
1892 // observed values: tcgen environment
1893 // no other values have been observed in real shaders
1894 for (i = 0;i < numparameters - 2 && i < Q3TCGEN_MAXPARMS;i++)
1895 layer->tcgen.parms[i] = atof(parameter[i+2]);
1896 if (!strcasecmp(parameter[1], "base")) layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1897 else if (!strcasecmp(parameter[1], "texture")) layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1898 else if (!strcasecmp(parameter[1], "environment")) layer->tcgen.tcgen = Q3TCGEN_ENVIRONMENT;
1899 else if (!strcasecmp(parameter[1], "lightmap")) layer->tcgen.tcgen = Q3TCGEN_LIGHTMAP;
1900 else if (!strcasecmp(parameter[1], "vector")) layer->tcgen.tcgen = Q3TCGEN_VECTOR;
1901 else Con_DPrintf("%s parsing warning: unknown tcgen mode %s\n", search->filenames[fileindex], parameter[1]);
1903 else if (numparameters >= 2 && !strcasecmp(parameter[0], "tcmod"))
1910 // tcmod stretch sin # # # #
1911 // tcmod stretch triangle # # # #
1912 // tcmod transform # # # # # #
1913 // tcmod turb # # # #
1914 // tcmod turb sin # # # # (this is bogus)
1915 // no other values have been observed in real shaders
1916 for (tcmodindex = 0;tcmodindex < Q3MAXTCMODS;tcmodindex++)
1917 if (!layer->tcmods[tcmodindex].tcmod)
1919 if (tcmodindex < Q3MAXTCMODS)
1921 for (i = 0;i < numparameters - 2 && i < Q3TCMOD_MAXPARMS;i++)
1922 layer->tcmods[tcmodindex].parms[i] = atof(parameter[i+2]);
1923 if (!strcasecmp(parameter[1], "entitytranslate")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ENTITYTRANSLATE;
1924 else if (!strcasecmp(parameter[1], "rotate")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ROTATE;
1925 else if (!strcasecmp(parameter[1], "scale")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCALE;
1926 else if (!strcasecmp(parameter[1], "scroll")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCROLL;
1927 else if (!strcasecmp(parameter[1], "page")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_PAGE;
1928 else if (!strcasecmp(parameter[1], "stretch"))
1930 layer->tcmods[tcmodindex].tcmod = Q3TCMOD_STRETCH;
1931 layer->tcmods[tcmodindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1932 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1933 layer->tcmods[tcmodindex].waveparms[i] = atof(parameter[i+3]);
1935 else if (!strcasecmp(parameter[1], "transform")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TRANSFORM;
1936 else if (!strcasecmp(parameter[1], "turb")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TURBULENT;
1937 else Con_DPrintf("%s parsing warning: unknown tcmod mode %s\n", search->filenames[fileindex], parameter[1]);
1940 Con_DPrintf("%s parsing warning: too many tcmods on one layer\n", search->filenames[fileindex]);
1942 // break out a level if it was a closing brace (not using the character here to not confuse vim)
1943 if (!strcasecmp(com_token, "}"))
1946 if (layer->rgbgen.rgbgen == Q3RGBGEN_LIGHTINGDIFFUSE || layer->rgbgen.rgbgen == Q3RGBGEN_VERTEX)
1947 shader.lighting = true;
1948 if (layer->alphagen.alphagen == Q3ALPHAGEN_VERTEX)
1950 if (layer == shader.layers + 0)
1952 // vertex controlled transparency
1953 shader.vertexalpha = true;
1957 // multilayer terrain shader or similar
1958 shader.textureblendalpha = true;
1961 layer->texflags = TEXF_ALPHA;
1962 if (!(shader.surfaceparms & Q3SURFACEPARM_NOMIPMAPS))
1963 layer->texflags |= TEXF_MIPMAP;
1964 if (!(shader.textureflags & Q3TEXTUREFLAG_NOPICMIP))
1965 layer->texflags |= TEXF_PICMIP | TEXF_COMPRESS;
1966 if (layer->clampmap)
1967 layer->texflags |= TEXF_CLAMP;
1971 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1973 if (j < TEXTURE_MAXFRAMES + 4)
1975 // remap dp_water to dpwater, dp_reflect to dpreflect, etc.
1976 if(j == 0 && !strncasecmp(com_token, "dp_", 3))
1977 dpsnprintf(parameter[j], sizeof(parameter[j]), "dp%s", &com_token[3]);
1979 strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1980 numparameters = j + 1;
1982 if (!COM_ParseToken_QuakeC(&text, true))
1985 //for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1986 // parameter[j][0] = 0;
1987 if (fileindex == 0 && !strcasecmp(com_token, "}"))
1989 if (developer_insane.integer)
1991 Con_DPrintf("%s: ", shader.name);
1992 for (j = 0;j < numparameters;j++)
1993 Con_DPrintf(" %s", parameter[j]);
1996 if (numparameters < 1)
1998 if (!strcasecmp(parameter[0], "surfaceparm") && numparameters >= 2)
2000 if (!strcasecmp(parameter[1], "alphashadow"))
2001 shader.surfaceparms |= Q3SURFACEPARM_ALPHASHADOW;
2002 else if (!strcasecmp(parameter[1], "areaportal"))
2003 shader.surfaceparms |= Q3SURFACEPARM_AREAPORTAL;
2004 else if (!strcasecmp(parameter[1], "botclip"))
2005 shader.surfaceparms |= Q3SURFACEPARM_BOTCLIP;
2006 else if (!strcasecmp(parameter[1], "clusterportal"))
2007 shader.surfaceparms |= Q3SURFACEPARM_CLUSTERPORTAL;
2008 else if (!strcasecmp(parameter[1], "detail"))
2009 shader.surfaceparms |= Q3SURFACEPARM_DETAIL;
2010 else if (!strcasecmp(parameter[1], "donotenter"))
2011 shader.surfaceparms |= Q3SURFACEPARM_DONOTENTER;
2012 else if (!strcasecmp(parameter[1], "dust"))
2013 shader.surfaceparms |= Q3SURFACEPARM_DUST;
2014 else if (!strcasecmp(parameter[1], "hint"))
2015 shader.surfaceparms |= Q3SURFACEPARM_HINT;
2016 else if (!strcasecmp(parameter[1], "fog"))
2017 shader.surfaceparms |= Q3SURFACEPARM_FOG;
2018 else if (!strcasecmp(parameter[1], "lava"))
2019 shader.surfaceparms |= Q3SURFACEPARM_LAVA;
2020 else if (!strcasecmp(parameter[1], "lightfilter"))
2021 shader.surfaceparms |= Q3SURFACEPARM_LIGHTFILTER;
2022 else if (!strcasecmp(parameter[1], "lightgrid"))
2023 shader.surfaceparms |= Q3SURFACEPARM_LIGHTGRID;
2024 else if (!strcasecmp(parameter[1], "metalsteps"))
2025 shader.surfaceparms |= Q3SURFACEPARM_METALSTEPS;
2026 else if (!strcasecmp(parameter[1], "nodamage"))
2027 shader.surfaceparms |= Q3SURFACEPARM_NODAMAGE;
2028 else if (!strcasecmp(parameter[1], "nodlight"))
2029 shader.surfaceparms |= Q3SURFACEPARM_NODLIGHT;
2030 else if (!strcasecmp(parameter[1], "nodraw"))
2031 shader.surfaceparms |= Q3SURFACEPARM_NODRAW;
2032 else if (!strcasecmp(parameter[1], "nodrop"))
2033 shader.surfaceparms |= Q3SURFACEPARM_NODROP;
2034 else if (!strcasecmp(parameter[1], "noimpact"))
2035 shader.surfaceparms |= Q3SURFACEPARM_NOIMPACT;
2036 else if (!strcasecmp(parameter[1], "nolightmap"))
2037 shader.surfaceparms |= Q3SURFACEPARM_NOLIGHTMAP;
2038 else if (!strcasecmp(parameter[1], "nomarks"))
2039 shader.surfaceparms |= Q3SURFACEPARM_NOMARKS;
2040 else if (!strcasecmp(parameter[1], "nomipmaps"))
2041 shader.surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
2042 else if (!strcasecmp(parameter[1], "nonsolid"))
2043 shader.surfaceparms |= Q3SURFACEPARM_NONSOLID;
2044 else if (!strcasecmp(parameter[1], "origin"))
2045 shader.surfaceparms |= Q3SURFACEPARM_ORIGIN;
2046 else if (!strcasecmp(parameter[1], "playerclip"))
2047 shader.surfaceparms |= Q3SURFACEPARM_PLAYERCLIP;
2048 else if (!strcasecmp(parameter[1], "sky"))
2049 shader.surfaceparms |= Q3SURFACEPARM_SKY;
2050 else if (!strcasecmp(parameter[1], "slick"))
2051 shader.surfaceparms |= Q3SURFACEPARM_SLICK;
2052 else if (!strcasecmp(parameter[1], "slime"))
2053 shader.surfaceparms |= Q3SURFACEPARM_SLIME;
2054 else if (!strcasecmp(parameter[1], "structural"))
2055 shader.surfaceparms |= Q3SURFACEPARM_STRUCTURAL;
2056 else if (!strcasecmp(parameter[1], "trans"))
2057 shader.surfaceparms |= Q3SURFACEPARM_TRANS;
2058 else if (!strcasecmp(parameter[1], "water"))
2059 shader.surfaceparms |= Q3SURFACEPARM_WATER;
2060 else if (!strcasecmp(parameter[1], "pointlight"))
2061 shader.surfaceparms |= Q3SURFACEPARM_POINTLIGHT;
2062 else if (!strcasecmp(parameter[1], "antiportal"))
2063 shader.surfaceparms |= Q3SURFACEPARM_ANTIPORTAL;
2066 // try custom surfaceparms
2067 for (j = 0; j < numcustsurfaceparms; j++)
2069 if (!strcasecmp(custsurfaceparmnames[j], parameter[1]))
2071 shader.surfaceparms |= custsurfaceparms[j];
2076 if (j == numcustsurfaceparms)
2077 Con_DPrintf("%s parsing warning: unknown surfaceparm \"%s\"\n", search->filenames[fileindex], parameter[1]);
2080 else if (!strcasecmp(parameter[0], "dpshadow"))
2081 shader.dpshadow = true;
2082 else if (!strcasecmp(parameter[0], "dpnoshadow"))
2083 shader.dpnoshadow = true;
2084 else if (!strcasecmp(parameter[0], "dpreflectcube"))
2085 strlcpy(shader.dpreflectcube, parameter[1], sizeof(shader.dpreflectcube));
2086 else if (!strcasecmp(parameter[0], "dpmeshcollisions"))
2087 shader.dpmeshcollisions = true;
2088 else if (!strcasecmp(parameter[0], "sky") && numparameters >= 2)
2090 // some q3 skies don't have the sky parm set
2091 shader.surfaceparms |= Q3SURFACEPARM_SKY;
2092 strlcpy(shader.skyboxname, parameter[1], sizeof(shader.skyboxname));
2094 else if (!strcasecmp(parameter[0], "skyparms") && numparameters >= 2)
2096 // some q3 skies don't have the sky parm set
2097 shader.surfaceparms |= Q3SURFACEPARM_SKY;
2098 if (!atoi(parameter[1]) && strcasecmp(parameter[1], "-"))
2099 strlcpy(shader.skyboxname, parameter[1], sizeof(shader.skyboxname));
2101 else if (!strcasecmp(parameter[0], "cull") && numparameters >= 2)
2103 if (!strcasecmp(parameter[1], "disable") || !strcasecmp(parameter[1], "none") || !strcasecmp(parameter[1], "twosided"))
2104 shader.textureflags |= Q3TEXTUREFLAG_TWOSIDED;
2106 else if (!strcasecmp(parameter[0], "nomipmaps"))
2107 shader.surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
2108 else if (!strcasecmp(parameter[0], "nopicmip"))
2109 shader.textureflags |= Q3TEXTUREFLAG_NOPICMIP;
2110 else if (!strcasecmp(parameter[0], "polygonoffset"))
2111 shader.textureflags |= Q3TEXTUREFLAG_POLYGONOFFSET;
2112 else if (!strcasecmp(parameter[0], "dppolygonoffset"))
2114 shader.textureflags |= Q3TEXTUREFLAG_POLYGONOFFSET;
2115 if(numparameters >= 2)
2117 shader.biaspolygonfactor = atof(parameter[1]);
2118 if(numparameters >= 3)
2119 shader.biaspolygonoffset = atof(parameter[2]);
2121 shader.biaspolygonoffset = 0;
2124 else if (!strcasecmp(parameter[0], "dprefract") && numparameters >= 5)
2126 shader.textureflags |= Q3TEXTUREFLAG_REFRACTION;
2127 shader.refractfactor = atof(parameter[1]);
2128 Vector4Set(shader.refractcolor4f, atof(parameter[2]), atof(parameter[3]), atof(parameter[4]), 1);
2130 else if (!strcasecmp(parameter[0], "dpreflect") && numparameters >= 6)
2132 shader.textureflags |= Q3TEXTUREFLAG_REFLECTION;
2133 shader.reflectfactor = atof(parameter[1]);
2134 Vector4Set(shader.reflectcolor4f, atof(parameter[2]), atof(parameter[3]), atof(parameter[4]), atof(parameter[5]));
2136 else if (!strcasecmp(parameter[0], "dpcamera"))
2138 shader.textureflags |= Q3TEXTUREFLAG_CAMERA;
2140 else if (!strcasecmp(parameter[0], "dpwater") && numparameters >= 12)
2142 shader.textureflags |= Q3TEXTUREFLAG_WATERSHADER;
2143 shader.reflectmin = atof(parameter[1]);
2144 shader.reflectmax = atof(parameter[2]);
2145 shader.refractfactor = atof(parameter[3]);
2146 shader.reflectfactor = atof(parameter[4]);
2147 Vector4Set(shader.refractcolor4f, atof(parameter[5]), atof(parameter[6]), atof(parameter[7]), 1);
2148 Vector4Set(shader.reflectcolor4f, atof(parameter[8]), atof(parameter[9]), atof(parameter[10]), 1);
2149 shader.r_water_wateralpha = atof(parameter[11]);
2151 else if (!strcasecmp(parameter[0], "dpwaterscroll") && numparameters >= 3)
2153 shader.r_water_waterscroll[0] = 1/atof(parameter[1]);
2154 shader.r_water_waterscroll[1] = 1/atof(parameter[2]);
2156 else if (!strcasecmp(parameter[0], "dpglossintensitymod") && numparameters >= 2)
2158 shader.specularscalemod = atof(parameter[1]);
2160 else if (!strcasecmp(parameter[0], "dpglossexponentmod") && numparameters >= 2)
2162 shader.specularpowermod = atof(parameter[1]);
2164 else if (!strcasecmp(parameter[0], "dpoffsetmapping") && numparameters >= 3)
2166 if (!strcasecmp(parameter[1], "disable") || !strcasecmp(parameter[1], "none") || !strcasecmp(parameter[1], "off"))
2167 shader.offsetmapping = OFFSETMAPPING_OFF;
2168 else if (!strcasecmp(parameter[1], "default"))
2169 shader.offsetmapping = OFFSETMAPPING_DEFAULT;
2170 else if (!strcasecmp(parameter[1], "linear"))
2171 shader.offsetmapping = OFFSETMAPPING_LINEAR;
2172 else if (!strcasecmp(parameter[1], "relief"))
2173 shader.offsetmapping = OFFSETMAPPING_RELIEF;
2174 shader.offsetscale = atof(parameter[2]);
2176 else if (!strcasecmp(parameter[0], "deformvertexes") && numparameters >= 2)
2179 for (deformindex = 0;deformindex < Q3MAXDEFORMS;deformindex++)
2180 if (!shader.deforms[deformindex].deform)
2182 if (deformindex < Q3MAXDEFORMS)
2184 for (i = 0;i < numparameters - 2 && i < Q3DEFORM_MAXPARMS;i++)
2185 shader.deforms[deformindex].parms[i] = atof(parameter[i+2]);
2186 if (!strcasecmp(parameter[1], "projectionshadow")) shader.deforms[deformindex].deform = Q3DEFORM_PROJECTIONSHADOW;
2187 else if (!strcasecmp(parameter[1], "autosprite" )) shader.deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE;
2188 else if (!strcasecmp(parameter[1], "autosprite2" )) shader.deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE2;
2189 else if (!strcasecmp(parameter[1], "text0" )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT0;
2190 else if (!strcasecmp(parameter[1], "text1" )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT1;
2191 else if (!strcasecmp(parameter[1], "text2" )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT2;
2192 else if (!strcasecmp(parameter[1], "text3" )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT3;
2193 else if (!strcasecmp(parameter[1], "text4" )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT4;
2194 else if (!strcasecmp(parameter[1], "text5" )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT5;
2195 else if (!strcasecmp(parameter[1], "text6" )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT6;
2196 else if (!strcasecmp(parameter[1], "text7" )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT7;
2197 else if (!strcasecmp(parameter[1], "bulge" )) shader.deforms[deformindex].deform = Q3DEFORM_BULGE;
2198 else if (!strcasecmp(parameter[1], "normal" )) shader.deforms[deformindex].deform = Q3DEFORM_NORMAL;
2199 else if (!strcasecmp(parameter[1], "wave" ))
2201 shader.deforms[deformindex].deform = Q3DEFORM_WAVE;
2202 shader.deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[3]);
2203 for (i = 0;i < numparameters - 4 && i < Q3WAVEPARMS;i++)
2204 shader.deforms[deformindex].waveparms[i] = atof(parameter[i+4]);
2206 else if (!strcasecmp(parameter[1], "move" ))
2208 shader.deforms[deformindex].deform = Q3DEFORM_MOVE;
2209 shader.deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[5]);
2210 for (i = 0;i < numparameters - 6 && i < Q3WAVEPARMS;i++)
2211 shader.deforms[deformindex].waveparms[i] = atof(parameter[i+6]);
2216 // pick the primary layer to render with
2217 if (shader.numlayers)
2219 shader.backgroundlayer = -1;
2220 shader.primarylayer = 0;
2221 // if lightmap comes first this is definitely an ordinary texture
2222 // if the first two layers have the correct blendfuncs and use vertex alpha, it is a blended terrain shader
2223 if ((shader.layers[shader.primarylayer].texturename != NULL)
2224 && !strcasecmp(shader.layers[shader.primarylayer].texturename[0], "$lightmap"))
2226 shader.backgroundlayer = -1;
2227 shader.primarylayer = 1;
2229 else if (shader.numlayers >= 2
2230 && shader.layers[1].alphagen.alphagen == Q3ALPHAGEN_VERTEX
2231 && (shader.layers[0].blendfunc[0] == GL_ONE && shader.layers[0].blendfunc[1] == GL_ZERO && !shader.layers[0].alphatest)
2232 && ((shader.layers[1].blendfunc[0] == GL_SRC_ALPHA && shader.layers[1].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA)
2233 || (shader.layers[1].blendfunc[0] == GL_ONE && shader.layers[1].blendfunc[1] == GL_ZERO && shader.layers[1].alphatest)))
2235 // terrain blending or other effects
2236 shader.backgroundlayer = 0;
2237 shader.primarylayer = 1;
2240 // fix up multiple reflection types
2241 if(shader.textureflags & Q3TEXTUREFLAG_WATERSHADER)
2242 shader.textureflags &= ~(Q3TEXTUREFLAG_REFRACTION | Q3TEXTUREFLAG_REFLECTION | Q3TEXTUREFLAG_CAMERA);
2244 Q3Shader_AddToHash (&shader);
2248 FS_FreeSearch(search);
2249 // free custinfoparm values
2250 for (j = 0; j < numcustsurfaceparms; j++)
2251 Mem_Free(custsurfaceparmnames[j]);
2254 q3shaderinfo_t *Mod_LookupQ3Shader(const char *name)
2256 unsigned short hash;
2257 q3shader_hash_entry_t* entry;
2259 Mod_LoadQ3Shaders();
2260 hash = CRC_Block_CaseInsensitive ((const unsigned char *)name, strlen (name));
2261 entry = q3shader_data->hash + (hash % Q3SHADER_HASH_SIZE);
2262 while (entry != NULL)
2264 if (strcasecmp (entry->shader.name, name) == 0)
2265 return &entry->shader;
2266 entry = entry->chain;
2271 qboolean Mod_LoadTextureFromQ3Shader(texture_t *texture, const char *name, qboolean warnmissing, qboolean fallback, int defaulttexflags)
2274 int texflagsmask, texflagsor;
2275 qboolean success = true;
2276 q3shaderinfo_t *shader;
2279 strlcpy(texture->name, name, sizeof(texture->name));
2280 shader = name[0] ? Mod_LookupQ3Shader(name) : NULL;
2283 if(!(defaulttexflags & TEXF_PICMIP))
2284 texflagsmask &= ~TEXF_PICMIP;
2285 if(!(defaulttexflags & TEXF_COMPRESS))
2286 texflagsmask &= ~TEXF_COMPRESS;
2288 if(defaulttexflags & TEXF_ISWORLD)
2289 texflagsor |= TEXF_ISWORLD;
2290 if(defaulttexflags & TEXF_ISSPRITE)
2291 texflagsor |= TEXF_ISSPRITE;
2292 // unless later loaded from the shader
2293 texture->offsetmapping = (mod_q3shader_default_offsetmapping.value) ? OFFSETMAPPING_DEFAULT : OFFSETMAPPING_OFF;
2294 texture->offsetscale = 1;
2295 texture->specularscalemod = 1;
2296 texture->specularpowermod = 1;
2297 // WHEN ADDING DEFAULTS HERE, REMEMBER TO SYNC TO SHADER LOADING ABOVE
2298 // HERE, AND Q1BSP LOADING
2299 // JUST GREP FOR "specularscalemod = 1".
2303 if (developer_loading.integer)
2304 Con_Printf("%s: loaded shader for %s\n", loadmodel->name, name);
2305 texture->surfaceparms = shader->surfaceparms;
2307 // allow disabling of picmip or compression by defaulttexflags
2308 texture->textureflags = (shader->textureflags & texflagsmask) | texflagsor;
2310 if (shader->surfaceparms & Q3SURFACEPARM_SKY)
2312 texture->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
2313 if (shader->skyboxname[0])
2315 // quake3 seems to append a _ to the skybox name, so this must do so as well
2316 dpsnprintf(loadmodel->brush.skybox, sizeof(loadmodel->brush.skybox), "%s_", shader->skyboxname);
2319 else if ((texture->surfaceflags & Q3SURFACEFLAG_NODRAW) || shader->numlayers == 0)
2320 texture->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2322 texture->basematerialflags = MATERIALFLAG_WALL;
2324 if (shader->layers[0].alphatest)
2325 texture->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
2326 if (shader->textureflags & Q3TEXTUREFLAG_TWOSIDED)
2327 texture->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
2328 if (shader->textureflags & Q3TEXTUREFLAG_POLYGONOFFSET)
2330 texture->biaspolygonoffset += shader->biaspolygonoffset;
2331 texture->biaspolygonfactor += shader->biaspolygonfactor;
2333 if (shader->textureflags & Q3TEXTUREFLAG_REFRACTION)
2334 texture->basematerialflags |= MATERIALFLAG_REFRACTION;
2335 if (shader->textureflags & Q3TEXTUREFLAG_REFLECTION)
2336 texture->basematerialflags |= MATERIALFLAG_REFLECTION;
2337 if (shader->textureflags & Q3TEXTUREFLAG_WATERSHADER)
2338 texture->basematerialflags |= MATERIALFLAG_WATERSHADER;
2339 if (shader->textureflags & Q3TEXTUREFLAG_CAMERA)
2340 texture->basematerialflags |= MATERIALFLAG_CAMERA;
2341 texture->customblendfunc[0] = GL_ONE;
2342 texture->customblendfunc[1] = GL_ZERO;
2343 if (shader->numlayers > 0)
2345 texture->customblendfunc[0] = shader->layers[0].blendfunc[0];
2346 texture->customblendfunc[1] = shader->layers[0].blendfunc[1];
2348 Q3 shader blendfuncs actually used in the game (* = supported by DP)
2349 * additive GL_ONE GL_ONE
2350 additive weird GL_ONE GL_SRC_ALPHA
2351 additive weird 2 GL_ONE GL_ONE_MINUS_SRC_ALPHA
2352 * alpha GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA
2353 alpha inverse GL_ONE_MINUS_SRC_ALPHA GL_SRC_ALPHA
2354 brighten GL_DST_COLOR GL_ONE
2355 brighten GL_ONE GL_SRC_COLOR
2356 brighten weird GL_DST_COLOR GL_ONE_MINUS_DST_ALPHA
2357 brighten weird 2 GL_DST_COLOR GL_SRC_ALPHA
2358 * modulate GL_DST_COLOR GL_ZERO
2359 * modulate GL_ZERO GL_SRC_COLOR
2360 modulate inverse GL_ZERO GL_ONE_MINUS_SRC_COLOR
2361 modulate inverse alpha GL_ZERO GL_SRC_ALPHA
2362 modulate weird inverse GL_ONE_MINUS_DST_COLOR GL_ZERO
2363 * modulate x2 GL_DST_COLOR GL_SRC_COLOR
2364 * no blend GL_ONE GL_ZERO
2365 nothing GL_ZERO GL_ONE
2367 // if not opaque, figure out what blendfunc to use
2368 if (shader->layers[0].blendfunc[0] != GL_ONE || shader->layers[0].blendfunc[1] != GL_ZERO)
2370 if (shader->layers[0].blendfunc[0] == GL_ONE && shader->layers[0].blendfunc[1] == GL_ONE)
2371 texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2372 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE)
2373 texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2374 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA)
2375 texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2377 texture->basematerialflags |= MATERIALFLAG_CUSTOMBLEND | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2380 if (!shader->lighting)
2381 texture->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
2382 if (shader->primarylayer >= 0)
2384 q3shaderinfo_layer_t* primarylayer = shader->layers + shader->primarylayer;
2385 // copy over many primarylayer parameters
2386 texture->rgbgen = primarylayer->rgbgen;
2387 texture->alphagen = primarylayer->alphagen;
2388 texture->tcgen = primarylayer->tcgen;
2389 memcpy(texture->tcmods, primarylayer->tcmods, sizeof(texture->tcmods));
2390 // load the textures
2391 texture->numskinframes = primarylayer->numframes;
2392 texture->skinframerate = primarylayer->framerate;
2393 for (j = 0;j < primarylayer->numframes;j++)
2395 if(cls.state == ca_dedicated)
2397 texture->skinframes[j] = NULL;
2399 else if (!(texture->skinframes[j] = R_SkinFrame_LoadExternal(primarylayer->texturename[j], (primarylayer->texflags & texflagsmask) | texflagsor, false)))
2401 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);
2402 texture->skinframes[j] = R_SkinFrame_LoadMissing();
2406 if (shader->backgroundlayer >= 0)
2408 q3shaderinfo_layer_t* backgroundlayer = shader->layers + shader->backgroundlayer;
2409 // copy over one secondarylayer parameter
2410 memcpy(texture->backgroundtcmods, backgroundlayer->tcmods, sizeof(texture->backgroundtcmods));
2411 // load the textures
2412 texture->backgroundnumskinframes = backgroundlayer->numframes;
2413 texture->backgroundskinframerate = backgroundlayer->framerate;
2414 for (j = 0;j < backgroundlayer->numframes;j++)
2416 if(cls.state == ca_dedicated)
2418 texture->skinframes[j] = NULL;
2420 else if (!(texture->backgroundskinframes[j] = R_SkinFrame_LoadExternal(backgroundlayer->texturename[j], (backgroundlayer->texflags & texflagsmask) | texflagsor, false)))
2422 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);
2423 texture->backgroundskinframes[j] = R_SkinFrame_LoadMissing();
2427 if (shader->dpshadow)
2428 texture->basematerialflags &= ~MATERIALFLAG_NOSHADOW;
2429 if (shader->dpnoshadow)
2430 texture->basematerialflags |= MATERIALFLAG_NOSHADOW;
2431 memcpy(texture->deforms, shader->deforms, sizeof(texture->deforms));
2432 texture->reflectmin = shader->reflectmin;
2433 texture->reflectmax = shader->reflectmax;
2434 texture->refractfactor = shader->refractfactor;
2435 Vector4Copy(shader->refractcolor4f, texture->refractcolor4f);
2436 texture->reflectfactor = shader->reflectfactor;
2437 Vector4Copy(shader->reflectcolor4f, texture->reflectcolor4f);
2438 texture->r_water_wateralpha = shader->r_water_wateralpha;
2439 Vector2Copy(shader->r_water_waterscroll, texture->r_water_waterscroll);
2440 texture->offsetmapping = shader->offsetmapping;
2441 texture->offsetscale = shader->offsetscale;
2442 texture->specularscalemod = shader->specularscalemod;
2443 texture->specularpowermod = shader->specularpowermod;
2444 if (shader->dpreflectcube[0])
2445 texture->reflectcubetexture = R_GetCubemap(shader->dpreflectcube);
2447 // set up default supercontents (on q3bsp this is overridden by the q3bsp loader)
2448 texture->supercontents = SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
2449 if (shader->surfaceparms & Q3SURFACEPARM_LAVA ) texture->supercontents = SUPERCONTENTS_LAVA ;
2450 if (shader->surfaceparms & Q3SURFACEPARM_SLIME ) texture->supercontents = SUPERCONTENTS_SLIME ;
2451 if (shader->surfaceparms & Q3SURFACEPARM_WATER ) texture->supercontents = SUPERCONTENTS_WATER ;
2452 if (shader->surfaceparms & Q3SURFACEPARM_NONSOLID ) texture->supercontents = 0 ;
2453 if (shader->surfaceparms & Q3SURFACEPARM_PLAYERCLIP ) texture->supercontents = SUPERCONTENTS_PLAYERCLIP ;
2454 if (shader->surfaceparms & Q3SURFACEPARM_BOTCLIP ) texture->supercontents = SUPERCONTENTS_MONSTERCLIP ;
2455 if (shader->surfaceparms & Q3SURFACEPARM_SKY ) texture->supercontents = SUPERCONTENTS_SKY ;
2457 // if (shader->surfaceparms & Q3SURFACEPARM_ALPHASHADOW ) texture->supercontents |= SUPERCONTENTS_ALPHASHADOW ;
2458 // if (shader->surfaceparms & Q3SURFACEPARM_AREAPORTAL ) texture->supercontents |= SUPERCONTENTS_AREAPORTAL ;
2459 // if (shader->surfaceparms & Q3SURFACEPARM_CLUSTERPORTAL) texture->supercontents |= SUPERCONTENTS_CLUSTERPORTAL;
2460 // if (shader->surfaceparms & Q3SURFACEPARM_DETAIL ) texture->supercontents |= SUPERCONTENTS_DETAIL ;
2461 if (shader->surfaceparms & Q3SURFACEPARM_DONOTENTER ) texture->supercontents |= SUPERCONTENTS_DONOTENTER ;
2462 // if (shader->surfaceparms & Q3SURFACEPARM_FOG ) texture->supercontents |= SUPERCONTENTS_FOG ;
2463 if (shader->surfaceparms & Q3SURFACEPARM_LAVA ) texture->supercontents |= SUPERCONTENTS_LAVA ;
2464 // if (shader->surfaceparms & Q3SURFACEPARM_LIGHTFILTER ) texture->supercontents |= SUPERCONTENTS_LIGHTFILTER ;
2465 // if (shader->surfaceparms & Q3SURFACEPARM_METALSTEPS ) texture->supercontents |= SUPERCONTENTS_METALSTEPS ;
2466 // if (shader->surfaceparms & Q3SURFACEPARM_NODAMAGE ) texture->supercontents |= SUPERCONTENTS_NODAMAGE ;
2467 // if (shader->surfaceparms & Q3SURFACEPARM_NODLIGHT ) texture->supercontents |= SUPERCONTENTS_NODLIGHT ;
2468 // if (shader->surfaceparms & Q3SURFACEPARM_NODRAW ) texture->supercontents |= SUPERCONTENTS_NODRAW ;
2469 if (shader->surfaceparms & Q3SURFACEPARM_NODROP ) texture->supercontents |= SUPERCONTENTS_NODROP ;
2470 // if (shader->surfaceparms & Q3SURFACEPARM_NOIMPACT ) texture->supercontents |= SUPERCONTENTS_NOIMPACT ;
2471 // if (shader->surfaceparms & Q3SURFACEPARM_NOLIGHTMAP ) texture->supercontents |= SUPERCONTENTS_NOLIGHTMAP ;
2472 // if (shader->surfaceparms & Q3SURFACEPARM_NOMARKS ) texture->supercontents |= SUPERCONTENTS_NOMARKS ;
2473 // if (shader->surfaceparms & Q3SURFACEPARM_NOMIPMAPS ) texture->supercontents |= SUPERCONTENTS_NOMIPMAPS ;
2474 if (shader->surfaceparms & Q3SURFACEPARM_NONSOLID ) texture->supercontents &=~SUPERCONTENTS_SOLID ;
2475 // if (shader->surfaceparms & Q3SURFACEPARM_ORIGIN ) texture->supercontents |= SUPERCONTENTS_ORIGIN ;
2476 if (shader->surfaceparms & Q3SURFACEPARM_PLAYERCLIP ) texture->supercontents |= SUPERCONTENTS_PLAYERCLIP ;
2477 if (shader->surfaceparms & Q3SURFACEPARM_SKY ) texture->supercontents |= SUPERCONTENTS_SKY ;
2478 // if (shader->surfaceparms & Q3SURFACEPARM_SLICK ) texture->supercontents |= SUPERCONTENTS_SLICK ;
2479 if (shader->surfaceparms & Q3SURFACEPARM_SLIME ) texture->supercontents |= SUPERCONTENTS_SLIME ;
2480 // if (shader->surfaceparms & Q3SURFACEPARM_STRUCTURAL ) texture->supercontents |= SUPERCONTENTS_STRUCTURAL ;
2481 // if (shader->surfaceparms & Q3SURFACEPARM_TRANS ) texture->supercontents |= SUPERCONTENTS_TRANS ;
2482 if (shader->surfaceparms & Q3SURFACEPARM_WATER ) texture->supercontents |= SUPERCONTENTS_WATER ;
2483 // if (shader->surfaceparms & Q3SURFACEPARM_POINTLIGHT ) texture->supercontents |= SUPERCONTENTS_POINTLIGHT ;
2484 // if (shader->surfaceparms & Q3SURFACEPARM_HINT ) texture->supercontents |= SUPERCONTENTS_HINT ;
2485 // if (shader->surfaceparms & Q3SURFACEPARM_DUST ) texture->supercontents |= SUPERCONTENTS_DUST ;
2486 if (shader->surfaceparms & Q3SURFACEPARM_BOTCLIP ) texture->supercontents |= SUPERCONTENTS_BOTCLIP | SUPERCONTENTS_MONSTERCLIP;
2487 // if (shader->surfaceparms & Q3SURFACEPARM_LIGHTGRID ) texture->supercontents |= SUPERCONTENTS_LIGHTGRID ;
2488 // if (shader->surfaceparms & Q3SURFACEPARM_ANTIPORTAL ) texture->supercontents |= SUPERCONTENTS_ANTIPORTAL ;
2490 if (shader->dpmeshcollisions)
2491 texture->basematerialflags |= MATERIALFLAG_MESHCOLLISIONS;
2493 else if (!strcmp(texture->name, "noshader") || !texture->name[0])
2495 if (developer_extra.integer)
2496 Con_DPrintf("^1%s:^7 using fallback noshader material for ^3\"%s\"\n", loadmodel->name, name);
2497 texture->surfaceparms = 0;
2498 texture->supercontents = SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
2500 else if (!strcmp(texture->name, "common/nodraw") || !strcmp(texture->name, "textures/common/nodraw"))
2502 if (developer_extra.integer)
2503 Con_DPrintf("^1%s:^7 using fallback nodraw material for ^3\"%s\"\n", loadmodel->name, name);
2504 texture->surfaceparms = 0;
2505 texture->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2506 texture->supercontents = SUPERCONTENTS_SOLID;
2510 if (developer_extra.integer)
2511 Con_DPrintf("^1%s:^7 No shader found for texture ^3\"%s\"\n", loadmodel->name, texture->name);
2512 texture->surfaceparms = 0;
2513 if (texture->surfaceflags & Q3SURFACEFLAG_NODRAW)
2515 texture->basematerialflags |= MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2516 texture->supercontents = SUPERCONTENTS_SOLID;
2518 else if (texture->surfaceflags & Q3SURFACEFLAG_SKY)
2520 texture->basematerialflags |= MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
2521 texture->supercontents = SUPERCONTENTS_SKY;
2525 texture->basematerialflags |= MATERIALFLAG_WALL;
2526 texture->supercontents = SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
2528 texture->numskinframes = 1;
2529 if(cls.state == ca_dedicated)
2531 texture->skinframes[0] = NULL;
2537 if ((texture->skinframes[0] = R_SkinFrame_LoadExternal(texture->name, defaulttexflags, false)))
2539 if(texture->skinframes[0]->hasalpha)
2540 texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2547 if (!success && warnmissing)
2548 Con_Printf("^1%s:^7 could not load texture ^3\"%s\"\n", loadmodel->name, texture->name);
2551 // init the animation variables
2552 texture->currentframe = texture;
2553 if (texture->numskinframes < 1)
2554 texture->numskinframes = 1;
2555 if (!texture->skinframes[0])
2556 texture->skinframes[0] = R_SkinFrame_LoadMissing();
2557 texture->currentskinframe = texture->skinframes[0];
2558 texture->backgroundcurrentskinframe = texture->backgroundskinframes[0];
2562 skinfile_t *Mod_LoadSkinFiles(void)
2564 int i, words, line, wordsoverflow;
2567 skinfile_t *skinfile = NULL, *first = NULL;
2568 skinfileitem_t *skinfileitem;
2569 char word[10][MAX_QPATH];
2573 U_bodyBox,models/players/Legoman/BikerA2.tga
2574 U_RArm,models/players/Legoman/BikerA1.tga
2575 U_LArm,models/players/Legoman/BikerA1.tga
2576 U_armor,common/nodraw
2577 U_sword,common/nodraw
2578 U_shield,common/nodraw
2579 U_homb,common/nodraw
2580 U_backpack,common/nodraw
2581 U_colcha,common/nodraw
2586 memset(word, 0, sizeof(word));
2587 for (i = 0;i < 256 && (data = text = (char *)FS_LoadFile(va("%s_%i.skin", loadmodel->name, i), tempmempool, true, NULL));i++)
2589 // If it's the first file we parse
2590 if (skinfile == NULL)
2592 skinfile = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
2597 skinfile->next = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
2598 skinfile = skinfile->next;
2600 skinfile->next = NULL;
2602 for(line = 0;;line++)
2605 if (!COM_ParseToken_QuakeC(&data, true))
2607 if (!strcmp(com_token, "\n"))
2610 wordsoverflow = false;
2614 strlcpy(word[words++], com_token, sizeof (word[0]));
2616 wordsoverflow = true;
2618 while (COM_ParseToken_QuakeC(&data, true) && strcmp(com_token, "\n"));
2621 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);
2624 // words is always >= 1
2625 if (!strcmp(word[0], "replace"))
2629 if (developer_loading.integer)
2630 Con_Printf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[1], word[2]);
2631 skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
2632 skinfileitem->next = skinfile->items;
2633 skinfile->items = skinfileitem;
2634 strlcpy (skinfileitem->name, word[1], sizeof (skinfileitem->name));
2635 strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
2638 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]);
2640 else if (words >= 2 && !strncmp(word[0], "tag_", 4))
2642 // tag name, like "tag_weapon,"
2643 // not used for anything (not even in Quake3)
2645 else if (words >= 2 && !strcmp(word[1], ","))
2647 // mesh shader name, like "U_RArm,models/players/Legoman/BikerA1.tga"
2648 if (developer_loading.integer)
2649 Con_Printf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[0], word[2]);
2650 skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
2651 skinfileitem->next = skinfile->items;
2652 skinfile->items = skinfileitem;
2653 strlcpy (skinfileitem->name, word[0], sizeof (skinfileitem->name));
2654 strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
2657 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);
2662 loadmodel->numskins = i;
2666 void Mod_FreeSkinFiles(skinfile_t *skinfile)
2669 skinfileitem_t *skinfileitem, *nextitem;
2670 for (;skinfile;skinfile = next)
2672 next = skinfile->next;
2673 for (skinfileitem = skinfile->items;skinfileitem;skinfileitem = nextitem)
2675 nextitem = skinfileitem->next;
2676 Mem_Free(skinfileitem);
2682 int Mod_CountSkinFiles(skinfile_t *skinfile)
2685 for (i = 0;skinfile;skinfile = skinfile->next, i++);
2689 void Mod_SnapVertices(int numcomponents, int numvertices, float *vertices, float snap)
2692 double isnap = 1.0 / snap;
2693 for (i = 0;i < numvertices*numcomponents;i++)
2694 vertices[i] = floor(vertices[i]*isnap)*snap;
2697 int Mod_RemoveDegenerateTriangles(int numtriangles, const int *inelement3i, int *outelement3i, const float *vertex3f)
2699 int i, outtriangles;
2700 float edgedir1[3], edgedir2[3], temp[3];
2701 // a degenerate triangle is one with no width (thickness, surface area)
2702 // these are characterized by having all 3 points colinear (along a line)
2703 // or having two points identical
2704 // the simplest check is to calculate the triangle's area
2705 for (i = 0, outtriangles = 0;i < numtriangles;i++, inelement3i += 3)
2707 // calculate first edge
2708 VectorSubtract(vertex3f + inelement3i[1] * 3, vertex3f + inelement3i[0] * 3, edgedir1);
2709 VectorSubtract(vertex3f + inelement3i[2] * 3, vertex3f + inelement3i[0] * 3, edgedir2);
2710 CrossProduct(edgedir1, edgedir2, temp);
2711 if (VectorLength2(temp) < 0.001f)
2712 continue; // degenerate triangle (no area)
2713 // valid triangle (has area)
2714 VectorCopy(inelement3i, outelement3i);
2718 return outtriangles;
2721 void Mod_VertexRangeFromElements(int numelements, const int *elements, int *firstvertexpointer, int *lastvertexpointer)
2724 int firstvertex, lastvertex;
2725 if (numelements > 0 && elements)
2727 firstvertex = lastvertex = elements[0];
2728 for (i = 1;i < numelements;i++)
2731 firstvertex = min(firstvertex, e);
2732 lastvertex = max(lastvertex, e);
2736 firstvertex = lastvertex = 0;
2737 if (firstvertexpointer)
2738 *firstvertexpointer = firstvertex;
2739 if (lastvertexpointer)
2740 *lastvertexpointer = lastvertex;
2743 void Mod_MakeSortedSurfaces(dp_model_t *mod)
2745 // make an optimal set of texture-sorted batches to draw...
2747 int *firstsurfacefortexture;
2748 int *numsurfacesfortexture;
2749 if (!mod->sortedmodelsurfaces)
2750 mod->sortedmodelsurfaces = (int *) Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
2751 firstsurfacefortexture = (int *) Mem_Alloc(tempmempool, mod->num_textures * sizeof(*firstsurfacefortexture));
2752 numsurfacesfortexture = (int *) Mem_Alloc(tempmempool, mod->num_textures * sizeof(*numsurfacesfortexture));
2753 memset(numsurfacesfortexture, 0, mod->num_textures * sizeof(*numsurfacesfortexture));
2754 for (j = 0;j < mod->nummodelsurfaces;j++)
2756 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
2757 int t = (int)(surface->texture - mod->data_textures);
2758 numsurfacesfortexture[t]++;
2761 for (t = 0;t < mod->num_textures;t++)
2763 firstsurfacefortexture[t] = j;
2764 j += numsurfacesfortexture[t];
2766 for (j = 0;j < mod->nummodelsurfaces;j++)
2768 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
2769 int t = (int)(surface->texture - mod->data_textures);
2770 mod->sortedmodelsurfaces[firstsurfacefortexture[t]++] = j + mod->firstmodelsurface;
2772 Mem_Free(firstsurfacefortexture);
2773 Mem_Free(numsurfacesfortexture);
2776 void Mod_BuildVBOs(void)
2778 if (!loadmodel->surfmesh.num_vertices)
2781 if (gl_paranoid.integer && loadmodel->surfmesh.data_element3s && loadmodel->surfmesh.data_element3i)
2784 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2786 if (loadmodel->surfmesh.data_element3s[i] != loadmodel->surfmesh.data_element3i[i])
2788 Con_Printf("Mod_BuildVBOs: element %u is incorrect (%u should be %u)\n", i, loadmodel->surfmesh.data_element3s[i], loadmodel->surfmesh.data_element3i[i]);
2789 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2794 // build r_vertexmesh_t array
2795 // (compressed interleaved array for faster rendering)
2796 if (!loadmodel->surfmesh.vertexmesh)
2799 int numvertices = loadmodel->surfmesh.num_vertices;
2800 r_vertexmesh_t *vertexmesh;
2801 loadmodel->surfmesh.vertexmesh = vertexmesh = (r_vertexmesh_t*)Mem_Alloc(loadmodel->mempool, numvertices * sizeof(*loadmodel->surfmesh.vertexmesh));
2802 for (vertexindex = 0;vertexindex < numvertices;vertexindex++, vertexmesh++)
2804 VectorCopy(loadmodel->surfmesh.data_vertex3f + 3*vertexindex, vertexmesh->vertex3f);
2805 VectorScale(loadmodel->surfmesh.data_svector3f + 3*vertexindex, 1.0f, vertexmesh->svector3f);
2806 VectorScale(loadmodel->surfmesh.data_tvector3f + 3*vertexindex, 1.0f, vertexmesh->tvector3f);
2807 VectorScale(loadmodel->surfmesh.data_normal3f + 3*vertexindex, 1.0f, vertexmesh->normal3f);
2808 if (loadmodel->surfmesh.data_lightmapcolor4f)
2809 Vector4Scale(loadmodel->surfmesh.data_lightmapcolor4f + 4*vertexindex, 255.0f, vertexmesh->color4ub);
2810 Vector2Copy(loadmodel->surfmesh.data_texcoordtexture2f + 2*vertexindex, vertexmesh->texcoordtexture2f);
2811 if (loadmodel->surfmesh.data_texcoordlightmap2f)
2812 Vector2Scale(loadmodel->surfmesh.data_texcoordlightmap2f + 2*vertexindex, 1.0f, vertexmesh->texcoordlightmap2f);
2816 // build r_vertexposition_t array
2817 if (!loadmodel->surfmesh.vertexposition)
2820 int numvertices = loadmodel->surfmesh.num_vertices;
2821 r_vertexposition_t *vertexposition;
2822 loadmodel->surfmesh.vertexposition = vertexposition = (r_vertexposition_t*)Mem_Alloc(loadmodel->mempool, numvertices * sizeof(*loadmodel->surfmesh.vertexposition));
2823 for (vertexindex = 0;vertexindex < numvertices;vertexindex++, vertexposition++)
2824 VectorCopy(loadmodel->surfmesh.data_vertex3f + 3*vertexindex, vertexposition->vertex3f);
2827 // upload r_vertexmesh_t array as a buffer
2828 if (loadmodel->surfmesh.vertexmesh && !loadmodel->surfmesh.vertexmeshbuffer)
2829 loadmodel->surfmesh.vertexmeshbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.vertexmesh, loadmodel->surfmesh.num_vertices * sizeof(*loadmodel->surfmesh.vertexmesh), loadmodel->name, false, false, false);
2831 // upload r_vertexposition_t array as a buffer
2832 if (loadmodel->surfmesh.vertexposition && !loadmodel->surfmesh.vertexpositionbuffer)
2833 loadmodel->surfmesh.vertexpositionbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.vertexposition, loadmodel->surfmesh.num_vertices * sizeof(*loadmodel->surfmesh.vertexposition), loadmodel->name, false, false, false);
2835 // upload short indices as a buffer
2836 if (loadmodel->surfmesh.data_element3s && !loadmodel->surfmesh.data_element3s_indexbuffer)
2837 loadmodel->surfmesh.data_element3s_indexbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.data_element3s, loadmodel->surfmesh.num_triangles * sizeof(short[3]), loadmodel->name, true, false, true);
2839 // upload int indices as a buffer
2840 if (loadmodel->surfmesh.data_element3i && !loadmodel->surfmesh.data_element3i_indexbuffer && !loadmodel->surfmesh.data_element3s)
2841 loadmodel->surfmesh.data_element3i_indexbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles * sizeof(int[3]), loadmodel->name, true, false, false);
2843 // only build a vbo if one has not already been created (this is important for brush models which load specially)
2844 // vertex buffer is several arrays and we put them in the same buffer
2846 // is this wise? the texcoordtexture2f array is used with dynamic
2847 // vertex/svector/tvector/normal when rendering animated models, on the
2848 // other hand animated models don't use a lot of vertices anyway...
2849 if (!loadmodel->surfmesh.vbo_vertexbuffer)
2854 loadmodel->surfmesh.vbooffset_vertex3f = size;if (loadmodel->surfmesh.data_vertex3f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2855 loadmodel->surfmesh.vbooffset_svector3f = size;if (loadmodel->surfmesh.data_svector3f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2856 loadmodel->surfmesh.vbooffset_tvector3f = size;if (loadmodel->surfmesh.data_tvector3f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2857 loadmodel->surfmesh.vbooffset_normal3f = size;if (loadmodel->surfmesh.data_normal3f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2858 loadmodel->surfmesh.vbooffset_texcoordtexture2f = size;if (loadmodel->surfmesh.data_texcoordtexture2f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
2859 loadmodel->surfmesh.vbooffset_texcoordlightmap2f = size;if (loadmodel->surfmesh.data_texcoordlightmap2f) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
2860 loadmodel->surfmesh.vbooffset_lightmapcolor4f = size;if (loadmodel->surfmesh.data_lightmapcolor4f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[4]);
2861 mem = (unsigned char *)Mem_Alloc(tempmempool, size);
2862 if (loadmodel->surfmesh.data_vertex3f ) memcpy(mem + loadmodel->surfmesh.vbooffset_vertex3f , loadmodel->surfmesh.data_vertex3f , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2863 if (loadmodel->surfmesh.data_svector3f ) memcpy(mem + loadmodel->surfmesh.vbooffset_svector3f , loadmodel->surfmesh.data_svector3f , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2864 if (loadmodel->surfmesh.data_tvector3f ) memcpy(mem + loadmodel->surfmesh.vbooffset_tvector3f , loadmodel->surfmesh.data_tvector3f , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2865 if (loadmodel->surfmesh.data_normal3f ) memcpy(mem + loadmodel->surfmesh.vbooffset_normal3f , loadmodel->surfmesh.data_normal3f , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2866 if (loadmodel->surfmesh.data_texcoordtexture2f ) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordtexture2f , loadmodel->surfmesh.data_texcoordtexture2f , loadmodel->surfmesh.num_vertices * sizeof(float[2]));
2867 if (loadmodel->surfmesh.data_texcoordlightmap2f) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordlightmap2f, loadmodel->surfmesh.data_texcoordlightmap2f, loadmodel->surfmesh.num_vertices * sizeof(float[2]));
2868 if (loadmodel->surfmesh.data_lightmapcolor4f ) memcpy(mem + loadmodel->surfmesh.vbooffset_lightmapcolor4f , loadmodel->surfmesh.data_lightmapcolor4f , loadmodel->surfmesh.num_vertices * sizeof(float[4]));
2869 loadmodel->surfmesh.vbo_vertexbuffer = R_Mesh_CreateMeshBuffer(mem, size, loadmodel->name, false, false, false);
2874 static void Mod_Decompile_OBJ(dp_model_t *model, const char *filename, const char *mtlfilename, const char *originalfilename)
2876 int submodelindex, vertexindex, surfaceindex, triangleindex, textureindex, countvertices = 0, countsurfaces = 0, countfaces = 0, counttextures = 0;
2878 const char *texname;
2880 const float *v, *vn, *vt;
2882 size_t outbufferpos = 0;
2883 size_t outbuffermax = 0x100000;
2884 char *outbuffer = (char *) Z_Malloc(outbuffermax), *oldbuffer;
2885 const msurface_t *surface;
2886 const int maxtextures = 256;
2887 char *texturenames = (char *) Z_Malloc(maxtextures * MAX_QPATH);
2888 dp_model_t *submodel;
2890 // construct the mtllib file
2891 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "# mtllib for %s exported by darkplaces engine\n", originalfilename);
2894 for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->num_surfaces;surfaceindex++, surface++)
2897 countvertices += surface->num_vertices;
2898 countfaces += surface->num_triangles;
2899 texname = (surface->texture && surface->texture->name[0]) ? surface->texture->name : "default";
2900 for (textureindex = 0;textureindex < counttextures;textureindex++)
2901 if (!strcmp(texturenames + textureindex * MAX_QPATH, texname))
2903 if (textureindex < counttextures)
2904 continue; // already wrote this material entry
2905 if (textureindex >= maxtextures)
2906 continue; // just a precaution
2907 textureindex = counttextures++;
2908 strlcpy(texturenames + textureindex * MAX_QPATH, texname, MAX_QPATH);
2909 if (outbufferpos >= outbuffermax >> 1)
2912 oldbuffer = outbuffer;
2913 outbuffer = (char *) Z_Malloc(outbuffermax);
2914 memcpy(outbuffer, oldbuffer, outbufferpos);
2917 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");
2922 // write the mtllib file
2923 FS_WriteFile(mtlfilename, outbuffer, outbufferpos);
2925 // construct the obj file
2927 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);
2931 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)
2933 if (outbufferpos >= outbuffermax >> 1)
2936 oldbuffer = outbuffer;
2937 outbuffer = (char *) Z_Malloc(outbuffermax);
2938 memcpy(outbuffer, oldbuffer, outbufferpos);
2941 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]);
2946 for (submodelindex = 0;submodelindex < max(1, model->brush.numsubmodels);submodelindex++)
2948 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "o %i\n", submodelindex);
2951 submodel = model->brush.numsubmodels ? model->brush.submodels[submodelindex] : model;
2952 for (surfaceindex = 0;surfaceindex < submodel->nummodelsurfaces;surfaceindex++)
2954 surface = model->data_surfaces + submodel->sortedmodelsurfaces[surfaceindex];
2955 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "usemtl %s\n", (surface->texture && surface->texture->name[0]) ? surface->texture->name : "default");
2958 for (triangleindex = 0, e = model->surfmesh.data_element3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
2960 if (outbufferpos >= outbuffermax >> 1)
2963 oldbuffer = outbuffer;
2964 outbuffer = (char *) Z_Malloc(outbuffermax);
2965 memcpy(outbuffer, oldbuffer, outbufferpos);
2971 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);
2978 // write the obj file
2979 FS_WriteFile(filename, outbuffer, outbufferpos);
2983 Z_Free(texturenames);
2986 Con_Printf("Wrote %s (%i bytes, %i vertices, %i faces, %i surfaces with %i distinct textures)\n", filename, (int)outbufferpos, countvertices, countfaces, countsurfaces, counttextures);
2989 static void Mod_Decompile_SMD(dp_model_t *model, const char *filename, int firstpose, int numposes, qboolean writetriangles)
2991 int countnodes = 0, counttriangles = 0, countframes = 0;
2999 size_t outbufferpos = 0;
3000 size_t outbuffermax = 0x100000;
3001 char *outbuffer = (char *) Z_Malloc(outbuffermax), *oldbuffer;
3002 const msurface_t *surface;
3003 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "version 1\nnodes\n");
3006 for (transformindex = 0;transformindex < model->num_bones;transformindex++)
3008 if (outbufferpos >= outbuffermax >> 1)
3011 oldbuffer = outbuffer;
3012 outbuffer = (char *) Z_Malloc(outbuffermax);
3013 memcpy(outbuffer, oldbuffer, outbufferpos);
3017 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i \"%s\" %3i\n", transformindex, model->data_bones[transformindex].name, model->data_bones[transformindex].parent);
3021 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\nskeleton\n");
3024 for (poseindex = 0;poseindex < numposes;poseindex++)
3027 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "time %i\n", poseindex);
3030 for (transformindex = 0;transformindex < model->num_bones;transformindex++)
3034 matrix4x4_t posematrix;
3035 if (outbufferpos >= outbuffermax >> 1)
3038 oldbuffer = outbuffer;
3039 outbuffer = (char *) Z_Malloc(outbuffermax);
3040 memcpy(outbuffer, oldbuffer, outbufferpos);
3044 // strangely the smd angles are for a transposed matrix, so we
3045 // have to generate a transposed matrix, then convert that...
3046 Matrix4x4_FromBonePose6s(&posematrix, model->num_posescale, model->data_poses6s + 6*(model->num_bones * poseindex + transformindex));
3047 Matrix4x4_ToArray12FloatGL(&posematrix, mtest[0]);
3048 AnglesFromVectors(angles, mtest[0], mtest[2], false);
3049 if (angles[0] >= 180) angles[0] -= 360;
3050 if (angles[1] >= 180) angles[1] -= 360;
3051 if (angles[2] >= 180) angles[2] -= 360;
3055 float a = DEG2RAD(angles[ROLL]);
3056 float b = DEG2RAD(angles[PITCH]);
3057 float c = DEG2RAD(angles[YAW]);
3058 float cy, sy, cp, sp, cr, sr;
3060 // smd matrix construction, for comparing
3071 test[1][0] = sr*sp*cy+cr*-sy;
3072 test[1][1] = sr*sp*sy+cr*cy;
3074 test[2][0] = (cr*sp*cy+-sr*-sy);
3075 test[2][1] = (cr*sp*sy+-sr*cy);
3077 test[3][0] = pose[9];
3078 test[3][1] = pose[10];
3079 test[3][2] = pose[11];
3082 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]));
3087 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\n");
3092 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "triangles\n");
3095 for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->num_surfaces;surfaceindex++, surface++)
3097 for (triangleindex = 0, e = model->surfmesh.data_element3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
3100 if (outbufferpos >= outbuffermax >> 1)
3103 oldbuffer = outbuffer;
3104 outbuffer = (char *) Z_Malloc(outbuffermax);
3105 memcpy(outbuffer, oldbuffer, outbufferpos);
3108 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%s\n", surface->texture && surface->texture->name[0] ? surface->texture->name : "default.bmp");
3111 for (cornerindex = 0;cornerindex < 3;cornerindex++)
3113 const int index = e[2-cornerindex];
3114 const float *v = model->surfmesh.data_vertex3f + index * 3;
3115 const float *vn = model->surfmesh.data_normal3f + index * 3;
3116 const float *vt = model->surfmesh.data_texcoordtexture2f + index * 2;
3117 const int b = model->surfmesh.blends[index];
3118 if (b < model->num_bones)
3119 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]);
3122 const blendweights_t *w = model->surfmesh.data_blendweights + b - model->num_bones;
3123 const unsigned char *wi = w->index;
3124 const unsigned char *wf = w->influence;
3125 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);
3126 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);
3127 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);
3128 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]);
3135 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\n");
3140 FS_WriteFile(filename, outbuffer, outbufferpos);
3143 Con_Printf("Wrote %s (%i bytes, %i nodes, %i frames, %i triangles)\n", filename, (int)outbufferpos, countnodes, countframes, counttriangles);
3150 decompiles a model to editable files
3153 static void Mod_Decompile_f(void)
3155 int i, j, k, l, first, count;
3157 char inname[MAX_QPATH];
3158 char outname[MAX_QPATH];
3159 char mtlname[MAX_QPATH];
3160 char basename[MAX_QPATH];
3161 char animname[MAX_QPATH];
3162 char animname2[MAX_QPATH];
3163 char zymtextbuffer[16384];
3164 char dpmtextbuffer[16384];
3165 char framegroupstextbuffer[16384];
3166 int zymtextsize = 0;
3167 int dpmtextsize = 0;
3168 int framegroupstextsize = 0;
3170 if (Cmd_Argc() != 2)
3172 Con_Print("usage: modeldecompile <filename>\n");
3176 strlcpy(inname, Cmd_Argv(1), sizeof(inname));
3177 FS_StripExtension(inname, basename, sizeof(basename));
3179 mod = Mod_ForName(inname, false, true, inname[0] == '*' ? cl.model_name[1] : NULL);
3180 if (mod->brush.submodel)
3182 // if we're decompiling a submodel, be sure to give it a proper name based on its parent
3183 FS_StripExtension(cl.model_name[1], outname, sizeof(outname));
3184 dpsnprintf(basename, sizeof(basename), "%s/%s", outname, mod->name);
3189 Con_Print("No such model\n");
3192 if (!mod->surfmesh.num_triangles)
3194 Con_Print("Empty model (or sprite)\n");
3198 // export OBJ if possible (not on sprites)
3199 if (mod->surfmesh.num_triangles)
3201 dpsnprintf(outname, sizeof(outname), "%s_decompiled.obj", basename);
3202 dpsnprintf(mtlname, sizeof(mtlname), "%s_decompiled.mtl", basename);
3203 Mod_Decompile_OBJ(mod, outname, mtlname, inname);
3206 // export SMD if possible (only for skeletal models)
3207 if (mod->surfmesh.num_triangles && mod->num_bones)
3209 dpsnprintf(outname, sizeof(outname), "%s_decompiled/ref1.smd", basename);
3210 Mod_Decompile_SMD(mod, outname, 0, 1, true);
3211 l = dpsnprintf(zymtextbuffer + zymtextsize, sizeof(zymtextbuffer) - zymtextsize, "output out.zym\nscale 1\norigin 0 0 0\nmesh ref1.smd\n");
3212 if (l > 0) zymtextsize += l;
3213 l = dpsnprintf(dpmtextbuffer + dpmtextsize, sizeof(dpmtextbuffer) - dpmtextsize, "outputdir .\nmodel out\nscale 1\norigin 0 0 0\nscene ref1.smd\n");
3214 if (l > 0) dpmtextsize += l;
3215 for (i = 0;i < mod->numframes;i = j)
3217 strlcpy(animname, mod->animscenes[i].name, sizeof(animname));
3218 first = mod->animscenes[i].firstframe;
3219 if (mod->animscenes[i].framecount > 1)
3222 count = mod->animscenes[i].framecount;
3228 // check for additional frames with same name
3229 for (l = 0, k = strlen(animname);animname[l];l++)
3230 if(animname[l] < '0' || animname[l] > '9')
3232 if(k > 0 && animname[k-1] == '_')
3235 count = mod->num_poses - first;
3236 for (j = i + 1;j < mod->numframes;j++)
3238 strlcpy(animname2, mod->animscenes[j].name, sizeof(animname2));
3239 for (l = 0, k = strlen(animname2);animname2[l];l++)
3240 if(animname2[l] < '0' || animname2[l] > '9')
3242 if(k > 0 && animname[k-1] == '_')
3245 if (strcmp(animname2, animname) || mod->animscenes[j].framecount > 1)
3247 count = mod->animscenes[j].firstframe - first;
3251 // if it's only one frame, use the original frame name
3253 strlcpy(animname, mod->animscenes[i].name, sizeof(animname));
3256 dpsnprintf(outname, sizeof(outname), "%s_decompiled/%s.smd", basename, animname);
3257 Mod_Decompile_SMD(mod, outname, first, count, false);
3258 if (zymtextsize < (int)sizeof(zymtextbuffer) - 100)
3260 l = dpsnprintf(zymtextbuffer + zymtextsize, sizeof(zymtextbuffer) - zymtextsize, "scene %s.smd fps %g %s\n", animname, mod->animscenes[i].framerate, mod->animscenes[i].loop ? "" : " noloop");
3261 if (l > 0) zymtextsize += l;
3263 if (dpmtextsize < (int)sizeof(dpmtextbuffer) - 100)
3265 l = dpsnprintf(dpmtextbuffer + dpmtextsize, sizeof(dpmtextbuffer) - dpmtextsize, "scene %s.smd fps %g %s\n", animname, mod->animscenes[i].framerate, mod->animscenes[i].loop ? "" : " noloop");
3266 if (l > 0) dpmtextsize += l;
3268 if (framegroupstextsize < (int)sizeof(framegroupstextbuffer) - 100)
3270 l = dpsnprintf(framegroupstextbuffer + framegroupstextsize, sizeof(framegroupstextbuffer) - framegroupstextsize, "%d %d %f %d // %s\n", first, count, mod->animscenes[i].framerate, mod->animscenes[i].loop, animname);
3271 if (l > 0) framegroupstextsize += l;
3275 FS_WriteFile(va("%s_decompiled/out_zym.txt", basename), zymtextbuffer, (fs_offset_t)zymtextsize);
3277 FS_WriteFile(va("%s_decompiled/out_dpm.txt", basename), dpmtextbuffer, (fs_offset_t)dpmtextsize);
3278 if (framegroupstextsize)
3279 FS_WriteFile(va("%s_decompiled.framegroups", basename), framegroupstextbuffer, (fs_offset_t)framegroupstextsize);
3283 void Mod_AllocLightmap_Init(mod_alloclightmap_state_t *state, int width, int height)
3286 memset(state, 0, sizeof(*state));
3287 state->width = width;
3288 state->height = height;
3289 state->currentY = 0;
3290 state->rows = (mod_alloclightmap_row_t *)Mem_Alloc(loadmodel->mempool, state->height * sizeof(*state->rows));
3291 for (y = 0;y < state->height;y++)
3293 state->rows[y].currentX = 0;
3294 state->rows[y].rowY = -1;
3298 void Mod_AllocLightmap_Reset(mod_alloclightmap_state_t *state)
3301 state->currentY = 0;
3302 for (y = 0;y < state->height;y++)
3304 state->rows[y].currentX = 0;
3305 state->rows[y].rowY = -1;
3309 void Mod_AllocLightmap_Free(mod_alloclightmap_state_t *state)
3312 Mem_Free(state->rows);
3313 memset(state, 0, sizeof(*state));
3316 qboolean Mod_AllocLightmap_Block(mod_alloclightmap_state_t *state, int blockwidth, int blockheight, int *outx, int *outy)
3318 mod_alloclightmap_row_t *row;
3321 row = state->rows + blockheight;
3322 if ((row->rowY < 0) || (row->currentX + blockwidth > state->width))
3324 if (state->currentY + blockheight <= state->height)
3326 // use the current allocation position
3327 row->rowY = state->currentY;
3329 state->currentY += blockheight;
3333 // find another position
3334 for (y = blockheight;y < state->height;y++)
3336 if ((state->rows[y].rowY >= 0) && (state->rows[y].currentX + blockwidth <= state->width))
3338 row = state->rows + y;
3342 if (y == state->height)
3347 *outx = row->currentX;
3348 row->currentX += blockwidth;
3353 typedef struct lightmapsample_s
3357 float *vertex_color;
3358 unsigned char *lm_bgr;
3359 unsigned char *lm_dir;
3363 typedef struct lightmapvertex_s
3368 float texcoordbase[2];
3369 float texcoordlightmap[2];
3370 float lightcolor[4];
3374 typedef struct lightmaptriangle_s
3382 // 2D modelspace coordinates of min corner
3383 // snapped to lightmap grid but not in grid coordinates
3385 // 2D modelspace to lightmap coordinate scale
3393 typedef struct lightmaplight_s
3404 lightmaptriangle_t *mod_generatelightmaps_lightmaptriangles;
3406 #define MAX_LIGHTMAPSAMPLES 64
3407 static int mod_generatelightmaps_numoffsets[3];
3408 static float mod_generatelightmaps_offsets[3][MAX_LIGHTMAPSAMPLES][3];
3410 static int mod_generatelightmaps_numlights;
3411 static lightmaplight_t *mod_generatelightmaps_lightinfo;
3413 extern int R_Shadow_GetRTLightInfo(unsigned int lightindex, float *origin, float *radius, float *color);
3414 extern cvar_t r_shadow_lightattenuationdividebias;
3415 extern cvar_t r_shadow_lightattenuationlinearscale;
3417 static void Mod_GenerateLightmaps_LightPoint(dp_model_t *model, const vec3_t pos, vec3_t ambient, vec3_t diffuse, vec3_t lightdir)
3422 float relativepoint[3];
3429 float lightorigin[3];
3433 float lightcolor[3];
3435 for (i = 0;i < 5*3;i++)
3437 for (index = 0;;index++)
3439 result = R_Shadow_GetRTLightInfo(index, lightorigin, &lightradius, lightcolor);
3444 lightradius2 = lightradius * lightradius;
3445 VectorSubtract(lightorigin, pos, relativepoint);
3446 dist2 = VectorLength2(relativepoint);
3447 if (dist2 >= lightradius2)
3449 lightiradius = 1.0f / lightradius;
3450 dist = sqrt(dist2) * lightiradius;
3451 intensity = dist < 1 ? ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) : 0;
3454 if (model && model->TraceLine)
3456 model->TraceLine(model, NULL, NULL, &trace, pos, lightorigin, SUPERCONTENTS_VISBLOCKERMASK);
3457 if (trace.fraction < 1)
3460 // scale down intensity to add to both ambient and diffuse
3461 //intensity *= 0.5f;
3462 VectorNormalize(relativepoint);
3463 VectorScale(lightcolor, intensity, color);
3464 VectorMA(sample , 0.5f , color, sample );
3465 VectorMA(sample + 3, relativepoint[0], color, sample + 3);
3466 VectorMA(sample + 6, relativepoint[1], color, sample + 6);
3467 VectorMA(sample + 9, relativepoint[2], color, sample + 9);
3468 // calculate a weighted average light direction as well
3469 intensity *= VectorLength(color);
3470 VectorMA(sample + 12, intensity, relativepoint, sample + 12);
3472 // calculate the direction we'll use to reduce the sample to a directional light source
3473 VectorCopy(sample + 12, dir);
3474 //VectorSet(dir, sample[3] + sample[4] + sample[5], sample[6] + sample[7] + sample[8], sample[9] + sample[10] + sample[11]);
3475 VectorNormalize(dir);
3476 // extract the diffuse color along the chosen direction and scale it
3477 diffuse[0] = (dir[0]*sample[3] + dir[1]*sample[6] + dir[2]*sample[ 9] + sample[ 0]);
3478 diffuse[1] = (dir[0]*sample[4] + dir[1]*sample[7] + dir[2]*sample[10] + sample[ 1]);
3479 diffuse[2] = (dir[0]*sample[5] + dir[1]*sample[8] + dir[2]*sample[11] + sample[ 2]);
3480 // subtract some of diffuse from ambient
3481 VectorMA(sample, -0.333f, diffuse, ambient);
3482 // store the normalized lightdir
3483 VectorCopy(dir, lightdir);
3486 static void Mod_GenerateLightmaps_CreateLights_ComputeSVBSP_InsertSurfaces(const dp_model_t *model, svbsp_t *svbsp, const float *mins, const float *maxs)
3490 const msurface_t *surface;
3491 const float *vertex3f = model->surfmesh.data_vertex3f;
3492 const int *element3i = model->surfmesh.data_element3i;
3495 for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->nummodelsurfaces;surfaceindex++, surface++)
3497 if (!BoxesOverlap(surface->mins, surface->maxs, mins, maxs))
3499 if (surface->texture->basematerialflags & MATERIALFLAG_NOSHADOW)
3501 for (triangleindex = 0, e = element3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
3503 VectorCopy(vertex3f + 3*e[0], v2[0]);
3504 VectorCopy(vertex3f + 3*e[1], v2[1]);
3505 VectorCopy(vertex3f + 3*e[2], v2[2]);
3506 SVBSP_AddPolygon(svbsp, 3, v2[0], true, NULL, NULL, 0);
3511 static void Mod_GenerateLightmaps_CreateLights_ComputeSVBSP(dp_model_t *model, lightmaplight_t *lightinfo)
3513 int maxnodes = 1<<14;
3514 svbsp_node_t *nodes;
3519 VectorSet(mins, lightinfo->origin[0] - lightinfo->radius, lightinfo->origin[1] - lightinfo->radius, lightinfo->origin[2] - lightinfo->radius);
3520 VectorSet(maxs, lightinfo->origin[0] + lightinfo->radius, lightinfo->origin[1] + lightinfo->radius, lightinfo->origin[2] + lightinfo->radius);
3521 VectorCopy(lightinfo->origin, origin);
3522 nodes = (svbsp_node_t *)Mem_Alloc(tempmempool, maxnodes * sizeof(*nodes));
3525 SVBSP_Init(&svbsp, origin, maxnodes, nodes);
3526 Mod_GenerateLightmaps_CreateLights_ComputeSVBSP_InsertSurfaces(model, &svbsp, mins, maxs);
3527 if (svbsp.ranoutofnodes)
3530 if (maxnodes > 1<<22)
3536 nodes = (svbsp_node_t *)Mem_Alloc(tempmempool, maxnodes * sizeof(*nodes));
3541 if (svbsp.numnodes > 0)
3543 svbsp.nodes = (svbsp_node_t *)Mem_Alloc(tempmempool, svbsp.numnodes * sizeof(*nodes));
3544 memcpy(svbsp.nodes, nodes, svbsp.numnodes * sizeof(*nodes));
3545 lightinfo->svbsp = svbsp;
3550 static void Mod_GenerateLightmaps_CreateLights(dp_model_t *model)
3554 lightmaplight_t *lightinfo;
3558 mod_generatelightmaps_numlights = 0;
3559 for (index = 0;;index++)
3561 result = R_Shadow_GetRTLightInfo(index, origin, &radius, color);
3565 mod_generatelightmaps_numlights++;
3567 if (mod_generatelightmaps_numlights > 0)
3569 mod_generatelightmaps_lightinfo = (lightmaplight_t *)Mem_Alloc(tempmempool, mod_generatelightmaps_numlights * sizeof(*mod_generatelightmaps_lightinfo));
3570 lightinfo = mod_generatelightmaps_lightinfo;
3571 for (index = 0;;index++)
3573 result = R_Shadow_GetRTLightInfo(index, lightinfo->origin, &lightinfo->radius, lightinfo->color);
3580 for (index = 0, lightinfo = mod_generatelightmaps_lightinfo;index < mod_generatelightmaps_numlights;index++, lightinfo++)
3582 lightinfo->iradius = 1.0f / lightinfo->radius;
3583 lightinfo->radius2 = lightinfo->radius * lightinfo->radius;
3584 // TODO: compute svbsp
3585 Mod_GenerateLightmaps_CreateLights_ComputeSVBSP(model, lightinfo);
3589 static void Mod_GenerateLightmaps_DestroyLights(dp_model_t *model)
3592 if (mod_generatelightmaps_lightinfo)
3594 for (i = 0;i < mod_generatelightmaps_numlights;i++)
3595 if (mod_generatelightmaps_lightinfo[i].svbsp.nodes)
3596 Mem_Free(mod_generatelightmaps_lightinfo[i].svbsp.nodes);
3597 Mem_Free(mod_generatelightmaps_lightinfo);
3599 mod_generatelightmaps_lightinfo = NULL;
3600 mod_generatelightmaps_numlights = 0;
3603 static qboolean Mod_GenerateLightmaps_SamplePoint_SVBSP(const svbsp_t *svbsp, const float *pos)
3605 const svbsp_node_t *node;
3606 const svbsp_node_t *nodes = svbsp->nodes;
3611 num = node->children[DotProduct(node->plane, pos) < node->plane[3]];
3613 return num == -1; // true if empty, false if solid (shadowed)
3616 static void Mod_GenerateLightmaps_SamplePoint(const float *pos, const float *normal, float *sample, int numoffsets, const float *offsets)
3619 float relativepoint[3];
3628 const lightmaplight_t *lightinfo;
3630 for (i = 0;i < 5*3;i++)
3632 for (i = 0, lightinfo = mod_generatelightmaps_lightinfo;i < mod_generatelightmaps_numlights;i++, lightinfo++)
3634 //R_SampleRTLights(pos, sample, numoffsets, offsets);
3635 VectorSubtract(lightinfo->origin, pos, relativepoint);
3636 // don't accept light from behind a surface, it causes bad shading
3637 if (normal && DotProduct(relativepoint, normal) <= 0)
3639 dist2 = VectorLength2(relativepoint);
3640 if (dist2 >= lightinfo->radius2)
3642 dist = sqrt(dist2) * lightinfo->iradius;
3643 intensity = dist < 1 ? ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) : 0;
3646 if (cl.worldmodel && cl.worldmodel->TraceLine && numoffsets > 0)
3650 if (Mod_GenerateLightmaps_SamplePoint_SVBSP(&lightinfo->svbsp, pos))
3652 for (offsetindex = 1;offsetindex < numoffsets;offsetindex++)
3654 VectorAdd(pos, offsets + 3*offsetindex, offsetpos);
3657 // for light grid we'd better check visibility of the offset point
3658 cl.worldmodel->TraceLine(cl.worldmodel, NULL, NULL, &trace, pos, offsetpos, SUPERCONTENTS_VISBLOCKERMASK);
3659 if (trace.fraction < 1)
3660 VectorLerp(pos, trace.fraction, offsetpos, offsetpos);
3663 if (Mod_GenerateLightmaps_SamplePoint_SVBSP(&lightinfo->svbsp, offsetpos))
3668 // scale intensity according to how many rays succeeded
3669 // we know one test is valid, half of the rest will fail...
3670 //if (normal && tests > 1)
3671 // intensity *= (tests - 1.0f) / tests;
3672 intensity *= (float)hits / tests;
3674 // scale down intensity to add to both ambient and diffuse
3675 //intensity *= 0.5f;
3676 VectorNormalize(relativepoint);
3677 VectorScale(lightinfo->color, intensity, color);
3678 VectorMA(sample , 0.5f , color, sample );
3679 VectorMA(sample + 3, relativepoint[0], color, sample + 3);
3680 VectorMA(sample + 6, relativepoint[1], color, sample + 6);
3681 VectorMA(sample + 9, relativepoint[2], color, sample + 9);
3682 // calculate a weighted average light direction as well
3683 intensity *= VectorLength(color);
3684 VectorMA(sample + 12, intensity, relativepoint, sample + 12);
3688 static void Mod_GenerateLightmaps_LightmapSample(const float *pos, const float *normal, unsigned char *lm_bgr, unsigned char *lm_dir)
3694 Mod_GenerateLightmaps_SamplePoint(pos, normal, sample, mod_generatelightmaps_numoffsets[0], mod_generatelightmaps_offsets[0][0]);
3695 //VectorSet(dir, sample[3] + sample[4] + sample[5], sample[6] + sample[7] + sample[8], sample[9] + sample[10] + sample[11]);
3696 VectorCopy(sample + 12, dir);
3697 VectorNormalize(dir);
3698 //VectorAdd(dir, normal, dir);
3699 //VectorNormalize(dir);
3700 f = DotProduct(dir, normal);
3701 f = max(0, f) * 255.0f;
3702 VectorScale(sample, f, color);
3703 //VectorCopy(normal, dir);
3704 VectorSet(dir, (dir[0]+1.0f)*127.5f, (dir[1]+1.0f)*127.5f, (dir[2]+1.0f)*127.5f);
3705 lm_bgr[0] = (unsigned char)bound(0.0f, color[2], 255.0f);
3706 lm_bgr[1] = (unsigned char)bound(0.0f, color[1], 255.0f);
3707 lm_bgr[2] = (unsigned char)bound(0.0f, color[0], 255.0f);
3709 lm_dir[0] = (unsigned char)dir[2];
3710 lm_dir[1] = (unsigned char)dir[1];
3711 lm_dir[2] = (unsigned char)dir[0];
3715 static void Mod_GenerateLightmaps_VertexSample(const float *pos, const float *normal, float *vertex_color)
3718 Mod_GenerateLightmaps_SamplePoint(pos, normal, sample, mod_generatelightmaps_numoffsets[1], mod_generatelightmaps_offsets[1][0]);
3719 VectorCopy(sample, vertex_color);
3722 static void Mod_GenerateLightmaps_GridSample(const float *pos, q3dlightgrid_t *s)
3728 Mod_GenerateLightmaps_SamplePoint(pos, NULL, sample, mod_generatelightmaps_numoffsets[2], mod_generatelightmaps_offsets[2][0]);
3729 // calculate the direction we'll use to reduce the sample to a directional light source
3730 VectorCopy(sample + 12, dir);
3731 //VectorSet(dir, sample[3] + sample[4] + sample[5], sample[6] + sample[7] + sample[8], sample[9] + sample[10] + sample[11]);
3732 VectorNormalize(dir);
3733 // extract the diffuse color along the chosen direction and scale it
3734 diffuse[0] = (dir[0]*sample[3] + dir[1]*sample[6] + dir[2]*sample[ 9] + sample[ 0]) * 127.5f;
3735 diffuse[1] = (dir[0]*sample[4] + dir[1]*sample[7] + dir[2]*sample[10] + sample[ 1]) * 127.5f;
3736 diffuse[2] = (dir[0]*sample[5] + dir[1]*sample[8] + dir[2]*sample[11] + sample[ 2]) * 127.5f;
3737 // scale the ambient from 0-2 to 0-255 and subtract some of diffuse
3738 VectorScale(sample, 127.5f, ambient);
3739 VectorMA(ambient, -0.333f, diffuse, ambient);
3740 // encode to the grid format
3741 s->ambientrgb[0] = (unsigned char)bound(0.0f, ambient[0], 255.0f);
3742 s->ambientrgb[1] = (unsigned char)bound(0.0f, ambient[1], 255.0f);
3743 s->ambientrgb[2] = (unsigned char)bound(0.0f, ambient[2], 255.0f);
3744 s->diffusergb[0] = (unsigned char)bound(0.0f, diffuse[0], 255.0f);
3745 s->diffusergb[1] = (unsigned char)bound(0.0f, diffuse[1], 255.0f);
3746 s->diffusergb[2] = (unsigned char)bound(0.0f, diffuse[2], 255.0f);
3747 if (dir[2] >= 0.99f) {s->diffusepitch = 0;s->diffuseyaw = 0;}
3748 else if (dir[2] <= -0.99f) {s->diffusepitch = 128;s->diffuseyaw = 0;}
3749 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));}
3752 static void Mod_GenerateLightmaps_InitSampleOffsets(dp_model_t *model)
3757 memset(mod_generatelightmaps_offsets, 0, sizeof(mod_generatelightmaps_offsets));
3758 mod_generatelightmaps_numoffsets[0] = min(MAX_LIGHTMAPSAMPLES, mod_generatelightmaps_lightmapsamples.integer);
3759 mod_generatelightmaps_numoffsets[1] = min(MAX_LIGHTMAPSAMPLES, mod_generatelightmaps_vertexsamples.integer);
3760 mod_generatelightmaps_numoffsets[2] = min(MAX_LIGHTMAPSAMPLES, mod_generatelightmaps_gridsamples.integer);
3761 radius[0] = mod_generatelightmaps_lightmapradius.value;
3762 radius[1] = mod_generatelightmaps_vertexradius.value;
3763 radius[2] = mod_generatelightmaps_gridradius.value;
3764 for (i = 0;i < 3;i++)
3766 for (j = 1;j < mod_generatelightmaps_numoffsets[i];j++)
3769 VectorScale(temp, radius[i], mod_generatelightmaps_offsets[i][j]);
3774 static void Mod_GenerateLightmaps_DestroyLightmaps(dp_model_t *model)
3776 msurface_t *surface;
3779 for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3781 surface = model->data_surfaces + surfaceindex;
3782 surface->lightmaptexture = NULL;
3783 surface->deluxemaptexture = NULL;
3785 if (model->brushq3.data_lightmaps)
3787 for (i = 0;i < model->brushq3.num_mergedlightmaps;i++)
3788 if (model->brushq3.data_lightmaps[i])
3789 R_FreeTexture(model->brushq3.data_lightmaps[i]);
3790 Mem_Free(model->brushq3.data_lightmaps);
3791 model->brushq3.data_lightmaps = NULL;
3793 if (model->brushq3.data_deluxemaps)
3795 for (i = 0;i < model->brushq3.num_mergedlightmaps;i++)
3796 if (model->brushq3.data_deluxemaps[i])
3797 R_FreeTexture(model->brushq3.data_deluxemaps[i]);
3798 Mem_Free(model->brushq3.data_deluxemaps);
3799 model->brushq3.data_deluxemaps = NULL;
3803 static void Mod_GenerateLightmaps_UnweldTriangles(dp_model_t *model)
3805 msurface_t *surface;
3811 surfmesh_t oldsurfmesh;
3813 unsigned char *data;
3814 oldsurfmesh = model->surfmesh;
3815 model->surfmesh.num_triangles = oldsurfmesh.num_triangles;
3816 model->surfmesh.num_vertices = oldsurfmesh.num_triangles * 3;
3818 size += model->surfmesh.num_vertices * sizeof(float[3]);
3819 size += model->surfmesh.num_vertices * sizeof(float[3]);
3820 size += model->surfmesh.num_vertices * sizeof(float[3]);
3821 size += model->surfmesh.num_vertices * sizeof(float[3]);
3822 size += model->surfmesh.num_vertices * sizeof(float[2]);
3823 size += model->surfmesh.num_vertices * sizeof(float[2]);
3824 size += model->surfmesh.num_vertices * sizeof(float[4]);
3825 data = (unsigned char *)Mem_Alloc(model->mempool, size);
3826 model->surfmesh.data_vertex3f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[3]);
3827 model->surfmesh.data_normal3f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[3]);
3828 model->surfmesh.data_svector3f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[3]);
3829 model->surfmesh.data_tvector3f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[3]);
3830 model->surfmesh.data_texcoordtexture2f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[2]);
3831 model->surfmesh.data_texcoordlightmap2f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[2]);
3832 model->surfmesh.data_lightmapcolor4f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[4]);
3833 if (model->surfmesh.num_vertices > 65536)
3834 model->surfmesh.data_element3s = NULL;
3836 if (model->surfmesh.vertexposition)
3837 Mem_Free(model->surfmesh.vertexposition);
3838 model->surfmesh.vertexposition = NULL;
3839 if (model->surfmesh.vertexmesh)
3840 Mem_Free(model->surfmesh.vertexmesh);
3841 model->surfmesh.vertexmesh = NULL;
3842 if (model->surfmesh.vertexpositionbuffer)
3843 R_Mesh_DestroyMeshBuffer(model->surfmesh.vertexpositionbuffer);
3844 model->surfmesh.vertexpositionbuffer = NULL;
3845 if (model->surfmesh.vertexmeshbuffer)
3846 R_Mesh_DestroyMeshBuffer(model->surfmesh.vertexmeshbuffer);
3847 model->surfmesh.vertexmeshbuffer = NULL;
3848 if (model->surfmesh.data_element3i_indexbuffer)
3849 R_Mesh_DestroyMeshBuffer(model->surfmesh.data_element3i_indexbuffer);
3850 model->surfmesh.data_element3i_indexbuffer = NULL;
3851 if (model->surfmesh.data_element3s_indexbuffer)
3852 R_Mesh_DestroyMeshBuffer(model->surfmesh.data_element3s_indexbuffer);
3853 model->surfmesh.data_element3s_indexbuffer = NULL;
3854 if (model->surfmesh.vbo_vertexbuffer)
3855 R_Mesh_DestroyMeshBuffer(model->surfmesh.vbo_vertexbuffer);
3856 model->surfmesh.vbo_vertexbuffer = 0;
3858 // convert all triangles to unique vertex data
3860 for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3862 surface = model->data_surfaces + surfaceindex;
3863 surface->num_firstvertex = outvertexindex;
3864 surface->num_vertices = surface->num_triangles*3;
3865 e = oldsurfmesh.data_element3i + surface->num_firsttriangle*3;
3866 for (i = 0;i < surface->num_triangles*3;i++)
3869 model->surfmesh.data_vertex3f[outvertexindex*3+0] = oldsurfmesh.data_vertex3f[vertexindex*3+0];
3870 model->surfmesh.data_vertex3f[outvertexindex*3+1] = oldsurfmesh.data_vertex3f[vertexindex*3+1];
3871 model->surfmesh.data_vertex3f[outvertexindex*3+2] = oldsurfmesh.data_vertex3f[vertexindex*3+2];
3872 model->surfmesh.data_normal3f[outvertexindex*3+0] = oldsurfmesh.data_normal3f[vertexindex*3+0];
3873 model->surfmesh.data_normal3f[outvertexindex*3+1] = oldsurfmesh.data_normal3f[vertexindex*3+1];
3874 model->surfmesh.data_normal3f[outvertexindex*3+2] = oldsurfmesh.data_normal3f[vertexindex*3+2];
3875 model->surfmesh.data_svector3f[outvertexindex*3+0] = oldsurfmesh.data_svector3f[vertexindex*3+0];
3876 model->surfmesh.data_svector3f[outvertexindex*3+1] = oldsurfmesh.data_svector3f[vertexindex*3+1];
3877 model->surfmesh.data_svector3f[outvertexindex*3+2] = oldsurfmesh.data_svector3f[vertexindex*3+2];
3878 model->surfmesh.data_tvector3f[outvertexindex*3+0] = oldsurfmesh.data_tvector3f[vertexindex*3+0];
3879 model->surfmesh.data_tvector3f[outvertexindex*3+1] = oldsurfmesh.data_tvector3f[vertexindex*3+1];
3880 model->surfmesh.data_tvector3f[outvertexindex*3+2] = oldsurfmesh.data_tvector3f[vertexindex*3+2];
3881 model->surfmesh.data_texcoordtexture2f[outvertexindex*2+0] = oldsurfmesh.data_texcoordtexture2f[vertexindex*2+0];
3882 model->surfmesh.data_texcoordtexture2f[outvertexindex*2+1] = oldsurfmesh.data_texcoordtexture2f[vertexindex*2+1];
3883 if (oldsurfmesh.data_texcoordlightmap2f)
3885 model->surfmesh.data_texcoordlightmap2f[outvertexindex*2+0] = oldsurfmesh.data_texcoordlightmap2f[vertexindex*2+0];
3886 model->surfmesh.data_texcoordlightmap2f[outvertexindex*2+1] = oldsurfmesh.data_texcoordlightmap2f[vertexindex*2+1];
3888 if (oldsurfmesh.data_lightmapcolor4f)
3890 model->surfmesh.data_lightmapcolor4f[outvertexindex*4+0] = oldsurfmesh.data_lightmapcolor4f[vertexindex*4+0];
3891 model->surfmesh.data_lightmapcolor4f[outvertexindex*4+1] = oldsurfmesh.data_lightmapcolor4f[vertexindex*4+1];
3892 model->surfmesh.data_lightmapcolor4f[outvertexindex*4+2] = oldsurfmesh.data_lightmapcolor4f[vertexindex*4+2];
3893 model->surfmesh.data_lightmapcolor4f[outvertexindex*4+3] = oldsurfmesh.data_lightmapcolor4f[vertexindex*4+3];
3896 Vector4Set(model->surfmesh.data_lightmapcolor4f + 4*outvertexindex, 1, 1, 1, 1);
3897 model->surfmesh.data_element3i[surface->num_firsttriangle*3+i] = outvertexindex;
3901 if (model->surfmesh.data_element3s)
3902 for (i = 0;i < model->surfmesh.num_triangles*3;i++)
3903 model->surfmesh.data_element3s[i] = model->surfmesh.data_element3i[i];
3905 // find and update all submodels to use this new surfmesh data
3906 for (i = 0;i < model->brush.numsubmodels;i++)
3907 model->brush.submodels[i]->surfmesh = model->surfmesh;
3910 static void Mod_GenerateLightmaps_CreateTriangleInformation(dp_model_t *model)
3912 msurface_t *surface;
3918 lightmaptriangle_t *triangle;
3919 // generate lightmap triangle structs
3920 mod_generatelightmaps_lightmaptriangles = (lightmaptriangle_t *)Mem_Alloc(model->mempool, model->surfmesh.num_triangles * sizeof(lightmaptriangle_t));
3921 for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3923 surface = model->data_surfaces + surfaceindex;
3924 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
3925 for (i = 0;i < surface->num_triangles;i++)
3927 triangle = &mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle+i];
3928 triangle->triangleindex = surface->num_firsttriangle+i;
3929 triangle->surfaceindex = surfaceindex;
3930 VectorCopy(model->surfmesh.data_vertex3f + 3*e[i*3+0], triangle->vertex[0]);
3931 VectorCopy(model->surfmesh.data_vertex3f + 3*e[i*3+1], triangle->vertex[1]);
3932 VectorCopy(model->surfmesh.data_vertex3f + 3*e[i*3+2], triangle->vertex[2]);
3933 // calculate bounds of triangle
3934 triangle->mins[0] = min(triangle->vertex[0][0], min(triangle->vertex[1][0], triangle->vertex[2][0]));
3935 triangle->mins[1] = min(triangle->vertex[0][1], min(triangle->vertex[1][1], triangle->vertex[2][1]));
3936 triangle->mins[2] = min(triangle->vertex[0][2], min(triangle->vertex[1][2], triangle->vertex[2][2]));
3937 triangle->maxs[0] = max(triangle->vertex[0][0], max(triangle->vertex[1][0], triangle->vertex[2][0]));
3938 triangle->maxs[1] = max(triangle->vertex[0][1], max(triangle->vertex[1][1], triangle->vertex[2][1]));
3939 triangle->maxs[2] = max(triangle->vertex[0][2], max(triangle->vertex[1][2], triangle->vertex[2][2]));
3940 // pick an axial projection based on the triangle normal
3941 TriangleNormal(triangle->vertex[0], triangle->vertex[1], triangle->vertex[2], normal);
3943 if (fabs(normal[1]) > fabs(normal[axis]))
3945 if (fabs(normal[2]) > fabs(normal[axis]))
3947 triangle->axis = axis;
3952 static void Mod_GenerateLightmaps_DestroyTriangleInformation(dp_model_t *model)
3954 if (mod_generatelightmaps_lightmaptriangles)
3955 Mem_Free(mod_generatelightmaps_lightmaptriangles);
3956 mod_generatelightmaps_lightmaptriangles = NULL;
3959 float lmaxis[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
3961 static void Mod_GenerateLightmaps_CreateLightmaps(dp_model_t *model)
3963 msurface_t *surface;
3977 float trianglenormal[3];
3978 float samplecenter[3];
3979 float samplenormal[3];
3985 float lmscalepixels;
3988 float lm_basescalepixels;
3989 int lm_borderpixels;
3993 lightmaptriangle_t *triangle;
3994 unsigned char *lightmappixels;
3995 unsigned char *deluxemappixels;
3996 mod_alloclightmap_state_t lmstate;
3998 // generate lightmap projection information for all triangles
3999 if (model->texturepool == NULL)
4000 model->texturepool = R_AllocTexturePool();
4001 lm_basescalepixels = 1.0f / max(0.0001f, mod_generatelightmaps_unitspersample.value);
4002 lm_borderpixels = mod_generatelightmaps_borderpixels.integer;
4003 lm_texturesize = bound(lm_borderpixels*2+1, 64, (int)vid.maxtexturesize_2d);
4004 //lm_maxpixels = lm_texturesize-(lm_borderpixels*2+1);
4005 Mod_AllocLightmap_Init(&lmstate, lm_texturesize, lm_texturesize);
4007 for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
4009 surface = model->data_surfaces + surfaceindex;
4010 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
4011 lmscalepixels = lm_basescalepixels;
4012 for (retry = 0;retry < 30;retry++)
4014 // after a couple failed attempts, degrade quality to make it fit
4016 lmscalepixels *= 0.5f;
4017 for (i = 0;i < surface->num_triangles;i++)
4019 triangle = &mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle+i];
4020 triangle->lightmapindex = lightmapnumber;
4021 // calculate lightmap bounds in 3D pixel coordinates, limit size,
4022 // pick two planar axes for projection
4023 // lightmap coordinates here are in pixels
4024 // lightmap projections are snapped to pixel grid explicitly, such
4025 // that two neighboring triangles sharing an edge and projection
4026 // axis will have identical sampl espacing along their shared edge
4028 for (j = 0;j < 3;j++)
4030 if (j == triangle->axis)
4032 lmmins = floor(triangle->mins[j]*lmscalepixels)-lm_borderpixels;
4033 lmmaxs = floor(triangle->maxs[j]*lmscalepixels)+lm_borderpixels;
4034 triangle->lmsize[k] = (int)(lmmaxs-lmmins);
4035 triangle->lmbase[k] = lmmins/lmscalepixels;
4036 triangle->lmscale[k] = lmscalepixels;
4039 if (!Mod_AllocLightmap_Block(&lmstate, triangle->lmsize[0], triangle->lmsize[1], &triangle->lmoffset[0], &triangle->lmoffset[1]))
4042 // if all fit in this texture, we're done with this surface
4043 if (i == surface->num_triangles)
4045 // if we haven't maxed out the lightmap size yet, we retry the
4046 // entire surface batch...
4047 if (lm_texturesize * 2 <= min(mod_generatelightmaps_texturesize.integer, (int)vid.maxtexturesize_2d))
4049 lm_texturesize *= 2;
4052 Mod_AllocLightmap_Free(&lmstate);
4053 Mod_AllocLightmap_Init(&lmstate, lm_texturesize, lm_texturesize);
4056 // if we have maxed out the lightmap size, and this triangle does
4057 // not fit in the same texture as the rest of the surface, we have
4058 // to retry the entire surface in a new texture (can only use one)
4059 // with multiple retries, the lightmap quality degrades until it
4060 // fits (or gives up)
4061 if (surfaceindex > 0)
4063 Mod_AllocLightmap_Reset(&lmstate);
4067 Mod_AllocLightmap_Free(&lmstate);
4069 // now put triangles together into lightmap textures, and do not allow
4070 // triangles of a surface to go into different textures (as that would
4071 // require rewriting the surface list)
4072 model->brushq3.deluxemapping_modelspace = true;
4073 model->brushq3.deluxemapping = true;
4074 model->brushq3.num_mergedlightmaps = lightmapnumber;
4075 model->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(model->mempool, model->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4076 model->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(model->mempool, model->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4077 lightmappixels = (unsigned char *)Mem_Alloc(tempmempool, model->brushq3.num_mergedlightmaps * lm_texturesize * lm_texturesize * 4);
4078 deluxemappixels = (unsigned char *)Mem_Alloc(tempmempool, model->brushq3.num_mergedlightmaps * lm_texturesize * lm_texturesize * 4);
4079 for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
4081 surface = model->data_surfaces + surfaceindex;
4082 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
4083 for (i = 0;i < surface->num_triangles;i++)
4085 triangle = &mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle+i];
4086 TriangleNormal(triangle->vertex[0], triangle->vertex[1], triangle->vertex[2], trianglenormal);
4087 VectorNormalize(trianglenormal);
4088 VectorCopy(trianglenormal, samplenormal); // FIXME: this is supposed to be interpolated per pixel from vertices
4089 axis = triangle->axis;
4090 axis1 = axis == 0 ? 1 : 0;
4091 axis2 = axis == 2 ? 1 : 2;
4092 lmiscale[0] = 1.0f / triangle->lmscale[0];
4093 lmiscale[1] = 1.0f / triangle->lmscale[1];
4094 if (trianglenormal[axis] < 0)
4095 VectorNegate(trianglenormal, trianglenormal);
4096 CrossProduct(lmaxis[axis2], trianglenormal, temp);slopex = temp[axis] / temp[axis1];
4097 CrossProduct(lmaxis[axis1], trianglenormal, temp);slopey = temp[axis] / temp[axis2];
4098 slopebase = triangle->vertex[0][axis] - triangle->vertex[0][axis1]*slopex - triangle->vertex[0][axis2]*slopey;
4099 for (j = 0;j < 3;j++)
4101 float *t2f = model->surfmesh.data_texcoordlightmap2f + e[i*3+j]*2;
4102 t2f[0] = ((triangle->vertex[j][axis1] - triangle->lmbase[0]) * triangle->lmscale[0] + triangle->lmoffset[0]) / lm_texturesize;
4103 t2f[1] = ((triangle->vertex[j][axis2] - triangle->lmbase[1]) * triangle->lmscale[1] + triangle->lmoffset[1]) / lm_texturesize;
4105 samplecenter[axis1] = (t2f[0]*lm_texturesize-triangle->lmoffset[0])*lmiscale[0] + triangle->lmbase[0];
4106 samplecenter[axis2] = (t2f[1]*lm_texturesize-triangle->lmoffset[1])*lmiscale[1] + triangle->lmbase[1];
4107 samplecenter[axis] = samplecenter[axis1]*slopex + samplecenter[axis2]*slopey + slopebase;
4108 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]);
4118 forward[1] = 1.0f / triangle->lmscale[0];
4122 left[2] = 1.0f / triangle->lmscale[1];
4127 origin[1] = triangle->lmbase[0];
4128 origin[2] = triangle->lmbase[1];
4131 forward[0] = 1.0f / triangle->lmscale[0];
4136 left[2] = 1.0f / triangle->lmscale[1];
4140 origin[0] = triangle->lmbase[0];
4142 origin[2] = triangle->lmbase[1];
4145 forward[0] = 1.0f / triangle->lmscale[0];
4149 left[1] = 1.0f / triangle->lmscale[1];
4154 origin[0] = triangle->lmbase[0];
4155 origin[1] = triangle->lmbase[1];
4159 Matrix4x4_FromVectors(&backmatrix, forward, left, up, origin);
4161 #define LM_DIST_EPSILON (1.0f / 32.0f)
4162 for (y = 0;y < triangle->lmsize[1];y++)
4164 pixeloffset = ((triangle->lightmapindex * lm_texturesize + y + triangle->lmoffset[1]) * lm_texturesize + triangle->lmoffset[0]) * 4;
4165 for (x = 0;x < triangle->lmsize[0];x++, pixeloffset += 4)
4167 samplecenter[axis1] = (x+0.5f)*lmiscale[0] + triangle->lmbase[0];
4168 samplecenter[axis2] = (y+0.5f)*lmiscale[1] + triangle->lmbase[1];
4169 samplecenter[axis] = samplecenter[axis1]*slopex + samplecenter[axis2]*slopey + slopebase;
4170 VectorMA(samplecenter, 0.125f, samplenormal, samplecenter);
4171 Mod_GenerateLightmaps_LightmapSample(samplecenter, samplenormal, lightmappixels + pixeloffset, deluxemappixels + pixeloffset);
4177 for (lightmapindex = 0;lightmapindex < model->brushq3.num_mergedlightmaps;lightmapindex++)
4179 model->brushq3.data_lightmaps[lightmapindex] = R_LoadTexture2D(model->texturepool, va("lightmap%i", lightmapindex), lm_texturesize, lm_texturesize, lightmappixels + lightmapindex * lm_texturesize * lm_texturesize * 4, TEXTYPE_BGRA, TEXF_FORCELINEAR, -1, NULL);
4180 model->brushq3.data_deluxemaps[lightmapindex] = R_LoadTexture2D(model->texturepool, va("deluxemap%i", lightmapindex), lm_texturesize, lm_texturesize, deluxemappixels + lightmapindex * lm_texturesize * lm_texturesize * 4, TEXTYPE_BGRA, TEXF_FORCELINEAR, -1, NULL);
4184 Mem_Free(lightmappixels);
4185 if (deluxemappixels)
4186 Mem_Free(deluxemappixels);
4188 for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
4190 surface = model->data_surfaces + surfaceindex;
4191 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
4192 if (!surface->num_triangles)
4194 lightmapindex = mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle].lightmapindex;
4195 surface->lightmaptexture = model->brushq3.data_lightmaps[lightmapindex];
4196 surface->deluxemaptexture = model->brushq3.data_deluxemaps[lightmapindex];
4197 surface->lightmapinfo = NULL;
4200 model->brush.LightPoint = Mod_GenerateLightmaps_LightPoint;
4201 model->brushq1.lightdata = NULL;
4202 model->brushq1.lightmapupdateflags = NULL;
4203 model->brushq1.firstrender = false;
4204 model->brushq1.num_lightstyles = 0;
4205 model->brushq1.data_lightstyleinfo = NULL;
4206 for (i = 0;i < model->brush.numsubmodels;i++)
4208 model->brush.submodels[i]->brushq1.lightmapupdateflags = NULL;
4209 model->brush.submodels[i]->brushq1.firstrender = false;
4210 model->brush.submodels[i]->brushq1.num_lightstyles = 0;
4211 model->brush.submodels[i]->brushq1.data_lightstyleinfo = NULL;
4215 static void Mod_GenerateLightmaps_UpdateVertexColors(dp_model_t *model)
4218 for (i = 0;i < model->surfmesh.num_vertices;i++)
4219 Mod_GenerateLightmaps_VertexSample(model->surfmesh.data_vertex3f + 3*i, model->surfmesh.data_normal3f + 3*i, model->surfmesh.data_lightmapcolor4f + 4*i);
4222 static void Mod_GenerateLightmaps_UpdateLightGrid(dp_model_t *model)
4229 for (z = 0;z < model->brushq3.num_lightgrid_isize[2];z++)
4231 pos[2] = (model->brushq3.num_lightgrid_imins[2] + z + 0.5f) * model->brushq3.num_lightgrid_cellsize[2];
4232 for (y = 0;y < model->brushq3.num_lightgrid_isize[1];y++)
4234 pos[1] = (model->brushq3.num_lightgrid_imins[1] + y + 0.5f) * model->brushq3.num_lightgrid_cellsize[1];
4235 for (x = 0;x < model->brushq3.num_lightgrid_isize[0];x++, index++)
4237 pos[0] = (model->brushq3.num_lightgrid_imins[0] + x + 0.5f) * model->brushq3.num_lightgrid_cellsize[0];
4238 Mod_GenerateLightmaps_GridSample(pos, model->brushq3.data_lightgrid + index);
4244 extern cvar_t mod_q3bsp_nolightmaps;
4245 static void Mod_GenerateLightmaps(dp_model_t *model)
4247 //lightmaptriangle_t *lightmaptriangles = Mem_Alloc(model->mempool, model->surfmesh.num_triangles * sizeof(lightmaptriangle_t));
4248 dp_model_t *oldloadmodel = loadmodel;
4251 Mod_GenerateLightmaps_InitSampleOffsets(model);
4252 Mod_GenerateLightmaps_DestroyLightmaps(model);
4253 Mod_GenerateLightmaps_UnweldTriangles(model);
4254 Mod_GenerateLightmaps_CreateTriangleInformation(model);
4255 Mod_GenerateLightmaps_CreateLights(model);
4256 if(!mod_q3bsp_nolightmaps.integer)
4257 Mod_GenerateLightmaps_CreateLightmaps(model);
4258 Mod_GenerateLightmaps_UpdateVertexColors(model);
4259 Mod_GenerateLightmaps_UpdateLightGrid(model);
4260 Mod_GenerateLightmaps_DestroyLights(model);
4261 Mod_GenerateLightmaps_DestroyTriangleInformation(model);
4263 loadmodel = oldloadmodel;
4266 static void Mod_GenerateLightmaps_f(void)
4268 if (Cmd_Argc() != 1)
4270 Con_Printf("usage: mod_generatelightmaps\n");
4275 Con_Printf("no worldmodel loaded\n");
4278 Mod_GenerateLightmaps(cl.worldmodel);