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 mod_generatelightmaps_unitspersample = {CVAR_SAVE, "mod_generatelightmaps_unitspersample", "8", "lightmap resolution"};
32 cvar_t mod_generatelightmaps_borderpixels = {CVAR_SAVE, "mod_generatelightmaps_borderpixels", "2", "extra space around polygons to prevent sampling artifacts"};
33 cvar_t mod_generatelightmaps_texturesize = {CVAR_SAVE, "mod_generatelightmaps_texturesize", "1024", "size of lightmap textures"};
34 cvar_t mod_generatelightmaps_lightmapsamples = {CVAR_SAVE, "mod_generatelightmaps_lightmapsamples", "16", "number of shadow tests done per lightmap pixel"};
35 cvar_t mod_generatelightmaps_vertexsamples = {CVAR_SAVE, "mod_generatelightmaps_vertexsamples", "16", "number of shadow tests done per vertex"};
36 cvar_t mod_generatelightmaps_gridsamples = {CVAR_SAVE, "mod_generatelightmaps_gridsamples", "64", "number of shadow tests done per lightgrid cell"};
37 cvar_t mod_generatelightmaps_lightmapradius = {CVAR_SAVE, "mod_generatelightmaps_lightmapradius", "16", "sampling area around each lightmap pixel"};
38 cvar_t mod_generatelightmaps_vertexradius = {CVAR_SAVE, "mod_generatelightmaps_vertexradius", "16", "sampling area around each vertex"};
39 cvar_t mod_generatelightmaps_gridradius = {CVAR_SAVE, "mod_generatelightmaps_gridradius", "64", "sampling area around each lightgrid cell center"};
41 dp_model_t *loadmodel;
43 static mempool_t *mod_mempool;
44 static memexpandablearray_t models;
46 static mempool_t* q3shaders_mem;
47 typedef struct q3shader_hash_entry_s
49 q3shaderinfo_t shader;
50 struct q3shader_hash_entry_s* chain;
51 } q3shader_hash_entry_t;
52 #define Q3SHADER_HASH_SIZE 1021
53 typedef struct q3shader_data_s
55 memexpandablearray_t hash_entries;
56 q3shader_hash_entry_t hash[Q3SHADER_HASH_SIZE];
57 memexpandablearray_t char_ptrs;
59 static q3shader_data_t* q3shader_data;
61 static void mod_start(void)
64 int nummodels = Mem_ExpandableArray_IndexRange(&models);
67 SCR_PushLoadingScreen(false, "Loading models", 1.0);
69 for (i = 0;i < nummodels;i++)
70 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
73 for (i = 0;i < nummodels;i++)
74 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
77 SCR_PushLoadingScreen(true, mod->name, 1.0 / count);
78 Mod_LoadModel(mod, true, false);
79 SCR_PopLoadingScreen(false);
81 SCR_PopLoadingScreen(false);
84 static void mod_shutdown(void)
87 int nummodels = Mem_ExpandableArray_IndexRange(&models);
90 for (i = 0;i < nummodels;i++)
91 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && (mod->loaded || mod->mempool))
97 static void mod_newmap(void)
100 int i, j, k, surfacenum, ssize, tsize;
101 int nummodels = Mem_ExpandableArray_IndexRange(&models);
104 for (i = 0;i < nummodels;i++)
106 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->mempool)
108 for (j = 0;j < mod->num_textures && mod->data_textures;j++)
110 for (k = 0;k < mod->data_textures[j].numskinframes;k++)
111 R_SkinFrame_MarkUsed(mod->data_textures[j].skinframes[k]);
112 for (k = 0;k < mod->data_textures[j].backgroundnumskinframes;k++)
113 R_SkinFrame_MarkUsed(mod->data_textures[j].backgroundskinframes[k]);
115 if (mod->brush.solidskyskinframe)
116 R_SkinFrame_MarkUsed(mod->brush.solidskyskinframe);
117 if (mod->brush.alphaskyskinframe)
118 R_SkinFrame_MarkUsed(mod->brush.alphaskyskinframe);
122 if (!cl_stainmaps_clearonload.integer)
125 for (i = 0;i < nummodels;i++)
127 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->mempool && mod->data_surfaces)
129 for (surfacenum = 0, surface = mod->data_surfaces;surfacenum < mod->num_surfaces;surfacenum++, surface++)
131 if (surface->lightmapinfo && surface->lightmapinfo->stainsamples)
133 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
134 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
135 memset(surface->lightmapinfo->stainsamples, 255, ssize * tsize * 3);
136 mod->brushq1.lightmapupdateflags[surfacenum] = true;
148 static void Mod_Print(void);
149 static void Mod_Precache (void);
150 static void Mod_Decompile_f(void);
151 static void Mod_BuildVBOs(void);
152 static void Mod_GenerateLightmaps_f(void);
155 mod_mempool = Mem_AllocPool("modelinfo", 0, NULL);
156 Mem_ExpandableArray_NewArray(&models, mod_mempool, sizeof(dp_model_t), 16);
162 Cvar_RegisterVariable(&r_mipskins);
163 Cvar_RegisterVariable(&mod_generatelightmaps_unitspersample);
164 Cvar_RegisterVariable(&mod_generatelightmaps_borderpixels);
165 Cvar_RegisterVariable(&mod_generatelightmaps_texturesize);
167 Cvar_RegisterVariable(&mod_generatelightmaps_lightmapsamples);
168 Cvar_RegisterVariable(&mod_generatelightmaps_vertexsamples);
169 Cvar_RegisterVariable(&mod_generatelightmaps_gridsamples);
170 Cvar_RegisterVariable(&mod_generatelightmaps_lightmapradius);
171 Cvar_RegisterVariable(&mod_generatelightmaps_vertexradius);
172 Cvar_RegisterVariable(&mod_generatelightmaps_gridradius);
174 Cmd_AddCommand ("modellist", Mod_Print, "prints a list of loaded models");
175 Cmd_AddCommand ("modelprecache", Mod_Precache, "load a model");
176 Cmd_AddCommand ("modeldecompile", Mod_Decompile_f, "exports a model in several formats for editing purposes");
177 Cmd_AddCommand ("mod_generatelightmaps", Mod_GenerateLightmaps_f, "rebuilds lighting on current worldmodel");
180 void Mod_RenderInit(void)
182 R_RegisterModule("Models", mod_start, mod_shutdown, mod_newmap);
185 void Mod_UnloadModel (dp_model_t *mod)
187 char name[MAX_QPATH];
189 dp_model_t *parentmodel;
191 if (developer_loading.integer)
192 Con_Printf("unloading model %s\n", mod->name);
194 strlcpy(name, mod->name, sizeof(name));
195 parentmodel = mod->brush.parentmodel;
197 if (mod->surfmesh.ebo3i)
198 R_Mesh_DestroyBufferObject(mod->surfmesh.ebo3i);
199 if (mod->surfmesh.ebo3s)
200 R_Mesh_DestroyBufferObject(mod->surfmesh.ebo3s);
201 if (mod->surfmesh.vbo)
202 R_Mesh_DestroyBufferObject(mod->surfmesh.vbo);
203 // free textures/memory attached to the model
204 R_FreeTexturePool(&mod->texturepool);
205 Mem_FreePool(&mod->mempool);
206 // clear the struct to make it available
207 memset(mod, 0, sizeof(dp_model_t));
208 // restore the fields we want to preserve
209 strlcpy(mod->name, name, sizeof(mod->name));
210 mod->brush.parentmodel = parentmodel;
215 void R_Model_Null_Draw(entity_render_t *ent)
221 typedef void (*mod_framegroupify_parsegroups_t) (unsigned int i, int start, int len, float fps, qboolean loop, void *pass);
223 int Mod_FrameGroupify_ParseGroups(const char *buf, mod_framegroupify_parsegroups_t cb, void *pass)
236 if (!COM_ParseToken_Simple(&bufptr, true, false))
238 if (!strcmp(com_token, "\n"))
239 continue; // empty line
240 start = atoi(com_token);
241 if (!COM_ParseToken_Simple(&bufptr, true, false))
243 if (!strcmp(com_token, "\n"))
245 Con_Printf("framegroups file: missing number of frames\n");
248 len = atoi(com_token);
249 if (!COM_ParseToken_Simple(&bufptr, true, false))
251 // we default to looping as it's usually wanted, so to NOT loop you append a 0
252 if (strcmp(com_token, "\n"))
254 fps = atof(com_token);
255 if (!COM_ParseToken_Simple(&bufptr, true, false))
257 if (strcmp(com_token, "\n"))
258 loop = atoi(com_token) != 0;
269 cb(i, start, len, fps, loop, pass);
276 void Mod_FrameGroupify_ParseGroups_Count (unsigned int i, int start, int len, float fps, qboolean loop, void *pass)
278 unsigned int *cnt = (unsigned int *) pass;
282 void Mod_FrameGroupify_ParseGroups_Store (unsigned int i, int start, int len, float fps, qboolean loop, void *pass)
284 dp_model_t *mod = (dp_model_t *) pass;
285 animscene_t *anim = &mod->animscenes[i];
286 dpsnprintf(anim->name, sizeof(anim[i].name), "groupified_%d", i);
287 anim->firstframe = bound(0, start, mod->num_poses - 1);
288 anim->framecount = bound(1, len, mod->num_poses - anim->firstframe);
289 anim->framerate = max(1, fps);
291 //Con_Printf("frame group %d is %d %d %f %d\n", i, start, len, fps, loop);
294 void Mod_FrameGroupify(dp_model_t *mod, const char *buf)
299 cnt = Mod_FrameGroupify_ParseGroups(buf, NULL, NULL);
302 Con_Printf("no scene found in framegroups file, aborting\n");
305 mod->numframes = cnt;
308 // (we do not free the previous animscenes, but model unloading will free the pool owning them, so it's okay)
309 mod->animscenes = (animscene_t *) Mem_Alloc(mod->mempool, sizeof(animscene_t) * mod->numframes);
312 Mod_FrameGroupify_ParseGroups(buf, Mod_FrameGroupify_ParseGroups_Store, mod);
322 dp_model_t *Mod_LoadModel(dp_model_t *mod, qboolean crash, qboolean checkdisk)
327 fs_offset_t filesize;
331 if (mod->name[0] == '*') // submodel
334 if (!strcmp(mod->name, "null"))
339 if (mod->loaded || mod->mempool)
340 Mod_UnloadModel(mod);
342 if (developer_loading.integer)
343 Con_Printf("loading model %s\n", mod->name);
346 mod->crc = (unsigned int)-1;
349 VectorClear(mod->normalmins);
350 VectorClear(mod->normalmaxs);
351 VectorClear(mod->yawmins);
352 VectorClear(mod->yawmaxs);
353 VectorClear(mod->rotatedmins);
354 VectorClear(mod->rotatedmaxs);
356 mod->modeldatatypestring = "null";
357 mod->type = mod_null;
358 mod->Draw = R_Model_Null_Draw;
362 // no fatal errors occurred, so this model is ready to use.
371 // even if the model is loaded it still may need reloading...
373 // if it is not loaded or checkdisk is true we need to calculate the crc
374 if (!mod->loaded || checkdisk)
376 if (checkdisk && mod->loaded)
377 Con_DPrintf("checking model %s\n", mod->name);
378 buf = FS_LoadFile (mod->name, tempmempool, false, &filesize);
381 crc = CRC_Block((unsigned char *)buf, filesize);
382 // we need to reload the model if the crc does not match
388 // if the model is already loaded and checks passed, just return
396 if (developer_loading.integer)
397 Con_Printf("loading model %s\n", mod->name);
399 SCR_PushLoadingScreen(true, mod->name, 1);
401 // LordHavoc: unload the existing model in this slot (if there is one)
402 if (mod->loaded || mod->mempool)
403 Mod_UnloadModel(mod);
408 // errors can prevent the corresponding mod->loaded = true;
411 // default model radius and bounding box (mainly for missing models)
413 VectorSet(mod->normalmins, -mod->radius, -mod->radius, -mod->radius);
414 VectorSet(mod->normalmaxs, mod->radius, mod->radius, mod->radius);
415 VectorSet(mod->yawmins, -mod->radius, -mod->radius, -mod->radius);
416 VectorSet(mod->yawmaxs, mod->radius, mod->radius, mod->radius);
417 VectorSet(mod->rotatedmins, -mod->radius, -mod->radius, -mod->radius);
418 VectorSet(mod->rotatedmaxs, mod->radius, mod->radius, mod->radius);
422 // load q3 shaders for the first time, or after a level change
428 char *bufend = (char *)buf + filesize;
430 // all models use memory, so allocate a memory pool
431 mod->mempool = Mem_AllocPool(mod->name, 0, NULL);
433 num = LittleLong(*((int *)buf));
434 // call the apropriate loader
436 if (!strcasecmp(FS_FileExtension(mod->name), "obj")) Mod_OBJ_Load(mod, buf, bufend);
437 else if (!memcmp(buf, "IDPO", 4)) Mod_IDP0_Load(mod, buf, bufend);
438 else if (!memcmp(buf, "IDP2", 4)) Mod_IDP2_Load(mod, buf, bufend);
439 else if (!memcmp(buf, "IDP3", 4)) Mod_IDP3_Load(mod, buf, bufend);
440 else if (!memcmp(buf, "IDSP", 4)) Mod_IDSP_Load(mod, buf, bufend);
441 else if (!memcmp(buf, "IDS2", 4)) Mod_IDS2_Load(mod, buf, bufend);
442 else if (!memcmp(buf, "IBSP", 4)) Mod_IBSP_Load(mod, buf, bufend);
443 else if (!memcmp(buf, "ZYMOTICMODEL", 12)) Mod_ZYMOTICMODEL_Load(mod, buf, bufend);
444 else if (!memcmp(buf, "DARKPLACESMODEL", 16)) Mod_DARKPLACESMODEL_Load(mod, buf, bufend);
445 else if (!memcmp(buf, "ACTRHEAD", 8)) Mod_PSKMODEL_Load(mod, buf, bufend);
446 else if (strlen(mod->name) >= 4 && !strcmp(mod->name + strlen(mod->name) - 4, ".map")) Mod_MAP_Load(mod, buf, bufend);
447 else if (num == BSPVERSION || num == 30) Mod_Q1BSP_Load(mod, buf, bufend);
448 else Con_Printf("Mod_LoadModel: model \"%s\" is of unknown/unsupported type\n", mod->name);
451 buf = FS_LoadFile (va("%s.framegroups", mod->name), tempmempool, false, &filesize);
454 Mod_FrameGroupify(mod, (const char *)buf);
462 // LordHavoc: Sys_Error was *ANNOYING*
463 Con_Printf ("Mod_LoadModel: %s not found\n", mod->name);
466 // no fatal errors occurred, so this model is ready to use.
469 SCR_PopLoadingScreen(false);
474 void Mod_ClearUsed(void)
477 int nummodels = Mem_ExpandableArray_IndexRange(&models);
479 for (i = 0;i < nummodels;i++)
480 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0])
484 void Mod_PurgeUnused(void)
487 int nummodels = Mem_ExpandableArray_IndexRange(&models);
489 for (i = 0;i < nummodels;i++)
491 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && !mod->used)
493 Mod_UnloadModel(mod);
494 Mem_ExpandableArray_FreeRecord(&models, mod);
505 dp_model_t *Mod_FindName(const char *name, const char *parentname)
514 // if we're not dedicatd, the renderer calls will crash without video
517 nummodels = Mem_ExpandableArray_IndexRange(&models);
520 Host_Error ("Mod_ForName: NULL name");
522 // search the currently loaded models
523 for (i = 0;i < nummodels;i++)
525 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))))
532 // no match found, create a new one
533 mod = (dp_model_t *) Mem_ExpandableArray_AllocRecord(&models);
534 strlcpy(mod->name, name, sizeof(mod->name));
536 mod->brush.parentmodel = Mod_FindName(parentname, NULL);
538 mod->brush.parentmodel = NULL;
548 Loads in a model for the given name
551 dp_model_t *Mod_ForName(const char *name, qboolean crash, qboolean checkdisk, const char *parentname)
554 model = Mod_FindName(name, parentname);
555 if (!model->loaded || checkdisk)
556 Mod_LoadModel(model, crash, checkdisk);
564 Reloads all models if they have changed
567 void Mod_Reload(void)
570 int nummodels = Mem_ExpandableArray_IndexRange(&models);
573 SCR_PushLoadingScreen(false, "Reloading models", 1.0);
575 for (i = 0;i < nummodels;i++)
576 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*' && mod->used)
578 for (i = 0;i < nummodels;i++)
579 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*' && mod->used)
581 SCR_PushLoadingScreen(true, mod->name, 1.0 / count);
582 Mod_LoadModel(mod, true, true);
583 SCR_PopLoadingScreen(false);
585 SCR_PopLoadingScreen(false);
588 unsigned char *mod_base;
591 //=============================================================================
598 static void Mod_Print(void)
601 int nummodels = Mem_ExpandableArray_IndexRange(&models);
604 Con_Print("Loaded models:\n");
605 for (i = 0;i < nummodels;i++)
607 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
609 if (mod->brush.numsubmodels)
610 Con_Printf("%4iK %s (%i submodels)\n", mod->mempool ? (int)((mod->mempool->totalsize + 1023) / 1024) : 0, mod->name, mod->brush.numsubmodels);
612 Con_Printf("%4iK %s\n", mod->mempool ? (int)((mod->mempool->totalsize + 1023) / 1024) : 0, mod->name);
622 static void Mod_Precache(void)
625 Mod_ForName(Cmd_Argv(1), false, true, Cmd_Argv(1)[0] == '*' ? cl.model_name[1] : NULL);
627 Con_Print("usage: modelprecache <filename>\n");
630 int Mod_BuildVertexRemapTableFromElements(int numelements, const int *elements, int numvertices, int *remapvertices)
634 used = (unsigned char *)Mem_Alloc(tempmempool, numvertices);
635 memset(used, 0, numvertices);
636 for (i = 0;i < numelements;i++)
637 used[elements[i]] = 1;
638 for (i = 0, count = 0;i < numvertices;i++)
639 remapvertices[i] = used[i] ? count++ : -1;
645 // fast way, using an edge hash
646 #define TRIANGLEEDGEHASH 8192
647 void Mod_BuildTriangleNeighbors(int *neighbors, const int *elements, int numtriangles)
649 int i, j, p, e1, e2, *n, hashindex, count, match;
651 typedef struct edgehashentry_s
653 struct edgehashentry_s *next;
658 edgehashentry_t *edgehash[TRIANGLEEDGEHASH], *edgehashentries, edgehashentriesbuffer[TRIANGLEEDGEHASH*3], *hash;
659 memset(edgehash, 0, sizeof(edgehash));
660 edgehashentries = edgehashentriesbuffer;
661 // if there are too many triangles for the stack array, allocate larger buffer
662 if (numtriangles > TRIANGLEEDGEHASH)
663 edgehashentries = (edgehashentry_t *)Mem_Alloc(tempmempool, numtriangles * 3 * sizeof(edgehashentry_t));
664 // find neighboring triangles
665 for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
667 for (j = 0, p = 2;j < 3;p = j, j++)
671 // this hash index works for both forward and backward edges
672 hashindex = (unsigned int)(e1 + e2) % TRIANGLEEDGEHASH;
673 hash = edgehashentries + i * 3 + j;
674 hash->next = edgehash[hashindex];
675 edgehash[hashindex] = hash;
677 hash->element[0] = e1;
678 hash->element[1] = e2;
681 for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
683 for (j = 0, p = 2;j < 3;p = j, j++)
687 // this hash index works for both forward and backward edges
688 hashindex = (unsigned int)(e1 + e2) % TRIANGLEEDGEHASH;
691 for (hash = edgehash[hashindex];hash;hash = hash->next)
693 if (hash->element[0] == e2 && hash->element[1] == e1)
695 if (hash->triangle != i)
696 match = hash->triangle;
699 else if ((hash->element[0] == e1 && hash->element[1] == e2))
702 // detect edges shared by three triangles and make them seams
708 // also send a keepalive here (this can take a while too!)
709 CL_KeepaliveMessage(false);
711 // free the allocated buffer
712 if (edgehashentries != edgehashentriesbuffer)
713 Mem_Free(edgehashentries);
716 // very slow but simple way
717 static int Mod_FindTriangleWithEdge(const int *elements, int numtriangles, int start, int end, int ignore)
722 for (i = 0;i < numtriangles;i++, elements += 3)
724 if ((elements[0] == start && elements[1] == end)
725 || (elements[1] == start && elements[2] == end)
726 || (elements[2] == start && elements[0] == end))
732 else if ((elements[1] == start && elements[0] == end)
733 || (elements[2] == start && elements[1] == end)
734 || (elements[0] == start && elements[2] == end))
737 // detect edges shared by three triangles and make them seams
743 void Mod_BuildTriangleNeighbors(int *neighbors, const int *elements, int numtriangles)
747 for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
749 n[0] = Mod_FindTriangleWithEdge(elements, numtriangles, e[1], e[0], i);
750 n[1] = Mod_FindTriangleWithEdge(elements, numtriangles, e[2], e[1], i);
751 n[2] = Mod_FindTriangleWithEdge(elements, numtriangles, e[0], e[2], i);
756 void Mod_ValidateElements(int *elements, int numtriangles, int firstvertex, int numverts, const char *filename, int fileline)
758 int i, warned = false, endvertex = firstvertex + numverts;
759 for (i = 0;i < numtriangles * 3;i++)
761 if (elements[i] < firstvertex || elements[i] >= endvertex)
766 Con_Printf("Mod_ValidateElements: out of bounds elements detected at %s:%d\n", filename, fileline);
768 elements[i] = firstvertex;
773 // warning: this is an expensive function!
774 void Mod_BuildNormals(int firstvertex, int numvertices, int numtriangles, const float *vertex3f, const int *elements, float *normal3f, qboolean areaweighting)
781 memset(normal3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
782 // process each vertex of each triangle and accumulate the results
783 // use area-averaging, to make triangles with a big area have a bigger
784 // weighting on the vertex normal than triangles with a small area
785 // to do so, just add the 'normals' together (the bigger the area
786 // the greater the length of the normal is
788 for (i = 0; i < numtriangles; i++, element += 3)
791 vertex3f + element[0] * 3,
792 vertex3f + element[1] * 3,
793 vertex3f + element[2] * 3,
798 VectorNormalize(areaNormal);
800 for (j = 0;j < 3;j++)
802 vectorNormal = normal3f + element[j] * 3;
803 vectorNormal[0] += areaNormal[0];
804 vectorNormal[1] += areaNormal[1];
805 vectorNormal[2] += areaNormal[2];
808 // and just normalize the accumulated vertex normal in the end
809 vectorNormal = normal3f + 3 * firstvertex;
810 for (i = 0; i < numvertices; i++, vectorNormal += 3)
811 VectorNormalize(vectorNormal);
814 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)
816 float f, tangentcross[3], v10[3], v20[3], tc10[2], tc20[2];
817 // 79 add/sub/negate/multiply (1 cycle), 1 compare (3 cycle?), total cycles not counting load/store/exchange roughly 82 cycles
818 // 6 add, 28 subtract, 39 multiply, 1 compare, 50% chance of 6 negates
820 // 6 multiply, 9 subtract
821 VectorSubtract(v1, v0, v10);
822 VectorSubtract(v2, v0, v20);
823 normal3f[0] = v20[1] * v10[2] - v20[2] * v10[1];
824 normal3f[1] = v20[2] * v10[0] - v20[0] * v10[2];
825 normal3f[2] = v20[0] * v10[1] - v20[1] * v10[0];
826 // 12 multiply, 10 subtract
827 tc10[1] = tc1[1] - tc0[1];
828 tc20[1] = tc2[1] - tc0[1];
829 svector3f[0] = tc10[1] * v20[0] - tc20[1] * v10[0];
830 svector3f[1] = tc10[1] * v20[1] - tc20[1] * v10[1];
831 svector3f[2] = tc10[1] * v20[2] - tc20[1] * v10[2];
832 tc10[0] = tc1[0] - tc0[0];
833 tc20[0] = tc2[0] - tc0[0];
834 tvector3f[0] = tc10[0] * v20[0] - tc20[0] * v10[0];
835 tvector3f[1] = tc10[0] * v20[1] - tc20[0] * v10[1];
836 tvector3f[2] = tc10[0] * v20[2] - tc20[0] * v10[2];
837 // 12 multiply, 4 add, 6 subtract
838 f = DotProduct(svector3f, normal3f);
839 svector3f[0] -= f * normal3f[0];
840 svector3f[1] -= f * normal3f[1];
841 svector3f[2] -= f * normal3f[2];
842 f = DotProduct(tvector3f, normal3f);
843 tvector3f[0] -= f * normal3f[0];
844 tvector3f[1] -= f * normal3f[1];
845 tvector3f[2] -= f * normal3f[2];
846 // if texture is mapped the wrong way (counterclockwise), the tangents
847 // have to be flipped, this is detected by calculating a normal from the
848 // two tangents, and seeing if it is opposite the surface normal
849 // 9 multiply, 2 add, 3 subtract, 1 compare, 50% chance of: 6 negates
850 CrossProduct(tvector3f, svector3f, tangentcross);
851 if (DotProduct(tangentcross, normal3f) < 0)
853 VectorNegate(svector3f, svector3f);
854 VectorNegate(tvector3f, tvector3f);
858 // warning: this is a very expensive function!
859 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)
862 float sdir[3], tdir[3], normal[3], *sv, *tv;
863 const float *v0, *v1, *v2, *tc0, *tc1, *tc2, *n;
864 float f, tangentcross[3], v10[3], v20[3], tc10[2], tc20[2];
867 memset(svector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
868 memset(tvector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
869 // process each vertex of each triangle and accumulate the results
870 for (tnum = 0, e = elements;tnum < numtriangles;tnum++, e += 3)
872 v0 = vertex3f + e[0] * 3;
873 v1 = vertex3f + e[1] * 3;
874 v2 = vertex3f + e[2] * 3;
875 tc0 = texcoord2f + e[0] * 2;
876 tc1 = texcoord2f + e[1] * 2;
877 tc2 = texcoord2f + e[2] * 2;
879 // 79 add/sub/negate/multiply (1 cycle), 1 compare (3 cycle?), total cycles not counting load/store/exchange roughly 82 cycles
880 // 6 add, 28 subtract, 39 multiply, 1 compare, 50% chance of 6 negates
882 // calculate the edge directions and surface normal
883 // 6 multiply, 9 subtract
884 VectorSubtract(v1, v0, v10);
885 VectorSubtract(v2, v0, v20);
886 normal[0] = v20[1] * v10[2] - v20[2] * v10[1];
887 normal[1] = v20[2] * v10[0] - v20[0] * v10[2];
888 normal[2] = v20[0] * v10[1] - v20[1] * v10[0];
890 // calculate the tangents
891 // 12 multiply, 10 subtract
892 tc10[1] = tc1[1] - tc0[1];
893 tc20[1] = tc2[1] - tc0[1];
894 sdir[0] = tc10[1] * v20[0] - tc20[1] * v10[0];
895 sdir[1] = tc10[1] * v20[1] - tc20[1] * v10[1];
896 sdir[2] = tc10[1] * v20[2] - tc20[1] * v10[2];
897 tc10[0] = tc1[0] - tc0[0];
898 tc20[0] = tc2[0] - tc0[0];
899 tdir[0] = tc10[0] * v20[0] - tc20[0] * v10[0];
900 tdir[1] = tc10[0] * v20[1] - tc20[0] * v10[1];
901 tdir[2] = tc10[0] * v20[2] - tc20[0] * v10[2];
903 // if texture is mapped the wrong way (counterclockwise), the tangents
904 // have to be flipped, this is detected by calculating a normal from the
905 // two tangents, and seeing if it is opposite the surface normal
906 // 9 multiply, 2 add, 3 subtract, 1 compare, 50% chance of: 6 negates
907 CrossProduct(tdir, sdir, tangentcross);
908 if (DotProduct(tangentcross, normal) < 0)
910 VectorNegate(sdir, sdir);
911 VectorNegate(tdir, tdir);
916 VectorNormalize(sdir);
917 VectorNormalize(tdir);
919 for (i = 0;i < 3;i++)
921 VectorAdd(svector3f + e[i]*3, sdir, svector3f + e[i]*3);
922 VectorAdd(tvector3f + e[i]*3, tdir, tvector3f + e[i]*3);
925 // make the tangents completely perpendicular to the surface normal, and
926 // then normalize them
927 // 16 assignments, 2 divide, 2 sqrt, 2 negates, 14 adds, 24 multiplies
928 for (i = 0, sv = svector3f + 3 * firstvertex, tv = tvector3f + 3 * firstvertex, n = normal3f + 3 * firstvertex;i < numvertices;i++, sv += 3, tv += 3, n += 3)
930 f = -DotProduct(sv, n);
931 VectorMA(sv, f, n, sv);
933 f = -DotProduct(tv, n);
934 VectorMA(tv, f, n, tv);
939 void Mod_AllocSurfMesh(mempool_t *mempool, int numvertices, int numtriangles, qboolean lightmapoffsets, qboolean vertexcolors, qboolean neighbors)
942 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));
943 loadmodel->surfmesh.num_vertices = numvertices;
944 loadmodel->surfmesh.num_triangles = numtriangles;
945 if (loadmodel->surfmesh.num_vertices)
947 loadmodel->surfmesh.data_vertex3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
948 loadmodel->surfmesh.data_svector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
949 loadmodel->surfmesh.data_tvector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
950 loadmodel->surfmesh.data_normal3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
951 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
952 loadmodel->surfmesh.data_texcoordlightmap2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
954 loadmodel->surfmesh.data_lightmapcolor4f = (float *)data, data += sizeof(float[4]) * loadmodel->surfmesh.num_vertices;
956 loadmodel->surfmesh.data_lightmapoffsets = (int *)data, data += sizeof(int) * loadmodel->surfmesh.num_vertices;
958 if (loadmodel->surfmesh.num_triangles)
960 loadmodel->surfmesh.data_element3i = (int *)data, data += sizeof(int[3]) * loadmodel->surfmesh.num_triangles;
962 loadmodel->surfmesh.data_neighbor3i = (int *)data, data += sizeof(int[3]) * loadmodel->surfmesh.num_triangles;
963 if (loadmodel->surfmesh.num_vertices <= 65536)
964 loadmodel->surfmesh.data_element3s = (unsigned short *)data, data += sizeof(unsigned short[3]) * loadmodel->surfmesh.num_triangles;
968 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)
970 shadowmesh_t *newmesh;
973 size = sizeof(shadowmesh_t);
974 size += maxverts * sizeof(float[3]);
976 size += maxverts * sizeof(float[11]);
977 size += maxtriangles * sizeof(int[3]);
978 if (maxverts <= 65536)
979 size += maxtriangles * sizeof(unsigned short[3]);
981 size += maxtriangles * sizeof(int[3]);
983 size += SHADOWMESHVERTEXHASH * sizeof(shadowmeshvertexhash_t *) + maxverts * sizeof(shadowmeshvertexhash_t);
984 data = (unsigned char *)Mem_Alloc(mempool, size);
985 newmesh = (shadowmesh_t *)data;data += sizeof(*newmesh);
986 newmesh->map_diffuse = map_diffuse;
987 newmesh->map_specular = map_specular;
988 newmesh->map_normal = map_normal;
989 newmesh->maxverts = maxverts;
990 newmesh->maxtriangles = maxtriangles;
991 newmesh->numverts = 0;
992 newmesh->numtriangles = 0;
993 memset(newmesh->sideoffsets, 0, sizeof(newmesh->sideoffsets));
994 memset(newmesh->sidetotals, 0, sizeof(newmesh->sidetotals));
996 newmesh->vertex3f = (float *)data;data += maxverts * sizeof(float[3]);
999 newmesh->svector3f = (float *)data;data += maxverts * sizeof(float[3]);
1000 newmesh->tvector3f = (float *)data;data += maxverts * sizeof(float[3]);
1001 newmesh->normal3f = (float *)data;data += maxverts * sizeof(float[3]);
1002 newmesh->texcoord2f = (float *)data;data += maxverts * sizeof(float[2]);
1004 newmesh->element3i = (int *)data;data += maxtriangles * sizeof(int[3]);
1007 newmesh->neighbor3i = (int *)data;data += maxtriangles * sizeof(int[3]);
1011 newmesh->vertexhashtable = (shadowmeshvertexhash_t **)data;data += SHADOWMESHVERTEXHASH * sizeof(shadowmeshvertexhash_t *);
1012 newmesh->vertexhashentries = (shadowmeshvertexhash_t *)data;data += maxverts * sizeof(shadowmeshvertexhash_t);
1014 if (maxverts <= 65536)
1015 newmesh->element3s = (unsigned short *)data;data += maxtriangles * sizeof(unsigned short[3]);
1019 shadowmesh_t *Mod_ShadowMesh_ReAlloc(mempool_t *mempool, shadowmesh_t *oldmesh, int light, int neighbors)
1021 shadowmesh_t *newmesh;
1022 newmesh = Mod_ShadowMesh_Alloc(mempool, oldmesh->numverts, oldmesh->numtriangles, oldmesh->map_diffuse, oldmesh->map_specular, oldmesh->map_normal, light, neighbors, false);
1023 newmesh->numverts = oldmesh->numverts;
1024 newmesh->numtriangles = oldmesh->numtriangles;
1025 memcpy(newmesh->sideoffsets, oldmesh->sideoffsets, sizeof(oldmesh->sideoffsets));
1026 memcpy(newmesh->sidetotals, oldmesh->sidetotals, sizeof(oldmesh->sidetotals));
1028 memcpy(newmesh->vertex3f, oldmesh->vertex3f, oldmesh->numverts * sizeof(float[3]));
1029 if (newmesh->svector3f && oldmesh->svector3f)
1031 memcpy(newmesh->svector3f, oldmesh->svector3f, oldmesh->numverts * sizeof(float[3]));
1032 memcpy(newmesh->tvector3f, oldmesh->tvector3f, oldmesh->numverts * sizeof(float[3]));
1033 memcpy(newmesh->normal3f, oldmesh->normal3f, oldmesh->numverts * sizeof(float[3]));
1034 memcpy(newmesh->texcoord2f, oldmesh->texcoord2f, oldmesh->numverts * sizeof(float[2]));
1036 memcpy(newmesh->element3i, oldmesh->element3i, oldmesh->numtriangles * sizeof(int[3]));
1037 if (newmesh->neighbor3i && oldmesh->neighbor3i)
1038 memcpy(newmesh->neighbor3i, oldmesh->neighbor3i, oldmesh->numtriangles * sizeof(int[3]));
1042 int Mod_ShadowMesh_AddVertex(shadowmesh_t *mesh, float *vertex14f)
1044 int hashindex, vnum;
1045 shadowmeshvertexhash_t *hash;
1046 // this uses prime numbers intentionally
1047 hashindex = (unsigned int) (vertex14f[0] * 2003 + vertex14f[1] * 4001 + vertex14f[2] * 7919) % SHADOWMESHVERTEXHASH;
1048 for (hash = mesh->vertexhashtable[hashindex];hash;hash = hash->next)
1050 vnum = (hash - mesh->vertexhashentries);
1051 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]))
1052 && (mesh->svector3f == NULL || (mesh->svector3f[vnum * 3 + 0] == vertex14f[3] && mesh->svector3f[vnum * 3 + 1] == vertex14f[4] && mesh->svector3f[vnum * 3 + 2] == vertex14f[5]))
1053 && (mesh->tvector3f == NULL || (mesh->tvector3f[vnum * 3 + 0] == vertex14f[6] && mesh->tvector3f[vnum * 3 + 1] == vertex14f[7] && mesh->tvector3f[vnum * 3 + 2] == vertex14f[8]))
1054 && (mesh->normal3f == NULL || (mesh->normal3f[vnum * 3 + 0] == vertex14f[9] && mesh->normal3f[vnum * 3 + 1] == vertex14f[10] && mesh->normal3f[vnum * 3 + 2] == vertex14f[11]))
1055 && (mesh->texcoord2f == NULL || (mesh->texcoord2f[vnum * 2 + 0] == vertex14f[12] && mesh->texcoord2f[vnum * 2 + 1] == vertex14f[13])))
1056 return hash - mesh->vertexhashentries;
1058 vnum = mesh->numverts++;
1059 hash = mesh->vertexhashentries + vnum;
1060 hash->next = mesh->vertexhashtable[hashindex];
1061 mesh->vertexhashtable[hashindex] = hash;
1062 if (mesh->vertex3f) {mesh->vertex3f[vnum * 3 + 0] = vertex14f[0];mesh->vertex3f[vnum * 3 + 1] = vertex14f[1];mesh->vertex3f[vnum * 3 + 2] = vertex14f[2];}
1063 if (mesh->svector3f) {mesh->svector3f[vnum * 3 + 0] = vertex14f[3];mesh->svector3f[vnum * 3 + 1] = vertex14f[4];mesh->svector3f[vnum * 3 + 2] = vertex14f[5];}
1064 if (mesh->tvector3f) {mesh->tvector3f[vnum * 3 + 0] = vertex14f[6];mesh->tvector3f[vnum * 3 + 1] = vertex14f[7];mesh->tvector3f[vnum * 3 + 2] = vertex14f[8];}
1065 if (mesh->normal3f) {mesh->normal3f[vnum * 3 + 0] = vertex14f[9];mesh->normal3f[vnum * 3 + 1] = vertex14f[10];mesh->normal3f[vnum * 3 + 2] = vertex14f[11];}
1066 if (mesh->texcoord2f) {mesh->texcoord2f[vnum * 2 + 0] = vertex14f[12];mesh->texcoord2f[vnum * 2 + 1] = vertex14f[13];}
1070 void Mod_ShadowMesh_AddTriangle(mempool_t *mempool, shadowmesh_t *mesh, rtexture_t *map_diffuse, rtexture_t *map_specular, rtexture_t *map_normal, float *vertex14f)
1072 if (mesh->numtriangles == 0)
1074 // set the properties on this empty mesh to be more favorable...
1075 // (note: this case only occurs for the first triangle added to a new mesh chain)
1076 mesh->map_diffuse = map_diffuse;
1077 mesh->map_specular = map_specular;
1078 mesh->map_normal = map_normal;
1080 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)
1082 if (mesh->next == NULL)
1083 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);
1086 mesh->element3i[mesh->numtriangles * 3 + 0] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 0);
1087 mesh->element3i[mesh->numtriangles * 3 + 1] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 1);
1088 mesh->element3i[mesh->numtriangles * 3 + 2] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 2);
1089 mesh->numtriangles++;
1092 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)
1095 float vbuf[3*14], *v;
1096 memset(vbuf, 0, sizeof(vbuf));
1097 for (i = 0;i < numtris;i++)
1099 for (j = 0, v = vbuf;j < 3;j++, v += 14)
1104 v[0] = vertex3f[e * 3 + 0];
1105 v[1] = vertex3f[e * 3 + 1];
1106 v[2] = vertex3f[e * 3 + 2];
1110 v[3] = svector3f[e * 3 + 0];
1111 v[4] = svector3f[e * 3 + 1];
1112 v[5] = svector3f[e * 3 + 2];
1116 v[6] = tvector3f[e * 3 + 0];
1117 v[7] = tvector3f[e * 3 + 1];
1118 v[8] = tvector3f[e * 3 + 2];
1122 v[9] = normal3f[e * 3 + 0];
1123 v[10] = normal3f[e * 3 + 1];
1124 v[11] = normal3f[e * 3 + 2];
1128 v[12] = texcoord2f[e * 2 + 0];
1129 v[13] = texcoord2f[e * 2 + 1];
1132 Mod_ShadowMesh_AddTriangle(mempool, mesh, map_diffuse, map_specular, map_normal, vbuf);
1135 // the triangle calculation can take a while, so let's do a keepalive here
1136 CL_KeepaliveMessage(false);
1139 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)
1141 // the preparation before shadow mesh initialization can take a while, so let's do a keepalive here
1142 CL_KeepaliveMessage(false);
1144 return Mod_ShadowMesh_Alloc(mempool, maxverts, maxtriangles, map_diffuse, map_specular, map_normal, light, neighbors, expandable);
1147 static void Mod_ShadowMesh_CreateVBOs(shadowmesh_t *mesh)
1149 if (!gl_support_arb_vertex_buffer_object)
1152 // element buffer is easy because it's just one array
1153 if (mesh->numtriangles)
1155 if (mesh->element3s)
1156 mesh->ebo3s = R_Mesh_CreateStaticBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB, mesh->element3s, mesh->numtriangles * sizeof(unsigned short[3]), "shadowmesh");
1158 mesh->ebo3i = R_Mesh_CreateStaticBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB, mesh->element3i, mesh->numtriangles * sizeof(unsigned int[3]), "shadowmesh");
1161 // vertex buffer is several arrays and we put them in the same buffer
1163 // is this wise? the texcoordtexture2f array is used with dynamic
1164 // vertex/svector/tvector/normal when rendering animated models, on the
1165 // other hand animated models don't use a lot of vertices anyway...
1171 mesh->vbooffset_vertex3f = size;if (mesh->vertex3f ) size += mesh->numverts * sizeof(float[3]);
1172 mesh->vbooffset_svector3f = size;if (mesh->svector3f ) size += mesh->numverts * sizeof(float[3]);
1173 mesh->vbooffset_tvector3f = size;if (mesh->tvector3f ) size += mesh->numverts * sizeof(float[3]);
1174 mesh->vbooffset_normal3f = size;if (mesh->normal3f ) size += mesh->numverts * sizeof(float[3]);
1175 mesh->vbooffset_texcoord2f = size;if (mesh->texcoord2f ) size += mesh->numverts * sizeof(float[2]);
1176 mem = (unsigned char *)Mem_Alloc(tempmempool, size);
1177 if (mesh->vertex3f ) memcpy(mem + mesh->vbooffset_vertex3f , mesh->vertex3f , mesh->numverts * sizeof(float[3]));
1178 if (mesh->svector3f ) memcpy(mem + mesh->vbooffset_svector3f , mesh->svector3f , mesh->numverts * sizeof(float[3]));
1179 if (mesh->tvector3f ) memcpy(mem + mesh->vbooffset_tvector3f , mesh->tvector3f , mesh->numverts * sizeof(float[3]));
1180 if (mesh->normal3f ) memcpy(mem + mesh->vbooffset_normal3f , mesh->normal3f , mesh->numverts * sizeof(float[3]));
1181 if (mesh->texcoord2f ) memcpy(mem + mesh->vbooffset_texcoord2f , mesh->texcoord2f , mesh->numverts * sizeof(float[2]));
1182 mesh->vbo = R_Mesh_CreateStaticBufferObject(GL_ARRAY_BUFFER_ARB, mem, size, "shadowmesh");
1187 shadowmesh_t *Mod_ShadowMesh_Finish(mempool_t *mempool, shadowmesh_t *firstmesh, qboolean light, qboolean neighbors, qboolean createvbo)
1189 shadowmesh_t *mesh, *newmesh, *nextmesh;
1190 // reallocate meshs to conserve space
1191 for (mesh = firstmesh, firstmesh = NULL;mesh;mesh = nextmesh)
1193 nextmesh = mesh->next;
1194 if (mesh->numverts >= 3 && mesh->numtriangles >= 1)
1196 newmesh = Mod_ShadowMesh_ReAlloc(mempool, mesh, light, neighbors);
1197 newmesh->next = firstmesh;
1198 firstmesh = newmesh;
1199 if (newmesh->element3s)
1202 for (i = 0;i < newmesh->numtriangles*3;i++)
1203 newmesh->element3s[i] = newmesh->element3i[i];
1206 Mod_ShadowMesh_CreateVBOs(newmesh);
1211 // this can take a while, so let's do a keepalive here
1212 CL_KeepaliveMessage(false);
1217 void Mod_ShadowMesh_CalcBBox(shadowmesh_t *firstmesh, vec3_t mins, vec3_t maxs, vec3_t center, float *radius)
1221 vec3_t nmins, nmaxs, ncenter, temp;
1222 float nradius2, dist2, *v;
1226 for (mesh = firstmesh;mesh;mesh = mesh->next)
1228 if (mesh == firstmesh)
1230 VectorCopy(mesh->vertex3f, nmins);
1231 VectorCopy(mesh->vertex3f, nmaxs);
1233 for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
1235 if (nmins[0] > v[0]) nmins[0] = v[0];if (nmaxs[0] < v[0]) nmaxs[0] = v[0];
1236 if (nmins[1] > v[1]) nmins[1] = v[1];if (nmaxs[1] < v[1]) nmaxs[1] = v[1];
1237 if (nmins[2] > v[2]) nmins[2] = v[2];if (nmaxs[2] < v[2]) nmaxs[2] = v[2];
1240 // calculate center and radius
1241 ncenter[0] = (nmins[0] + nmaxs[0]) * 0.5f;
1242 ncenter[1] = (nmins[1] + nmaxs[1]) * 0.5f;
1243 ncenter[2] = (nmins[2] + nmaxs[2]) * 0.5f;
1245 for (mesh = firstmesh;mesh;mesh = mesh->next)
1247 for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
1249 VectorSubtract(v, ncenter, temp);
1250 dist2 = DotProduct(temp, temp);
1251 if (nradius2 < dist2)
1257 VectorCopy(nmins, mins);
1259 VectorCopy(nmaxs, maxs);
1261 VectorCopy(ncenter, center);
1263 *radius = sqrt(nradius2);
1266 void Mod_ShadowMesh_Free(shadowmesh_t *mesh)
1268 shadowmesh_t *nextmesh;
1269 for (;mesh;mesh = nextmesh)
1272 R_Mesh_DestroyBufferObject(mesh->ebo3i);
1274 R_Mesh_DestroyBufferObject(mesh->ebo3s);
1276 R_Mesh_DestroyBufferObject(mesh->vbo);
1277 nextmesh = mesh->next;
1282 void Mod_CreateCollisionMesh(dp_model_t *mod)
1285 int numcollisionmeshtriangles;
1286 const msurface_t *surface;
1287 mempool_t *mempool = mod->mempool;
1288 if (!mempool && mod->brush.parentmodel)
1289 mempool = mod->brush.parentmodel->mempool;
1290 // make a single combined collision mesh for physics engine use
1291 // TODO rewrite this to use the collision brushes as source, to fix issues with e.g. common/caulk which creates no drawsurface
1292 numcollisionmeshtriangles = 0;
1293 for (k = 0;k < mod->nummodelsurfaces;k++)
1295 surface = mod->data_surfaces + mod->firstmodelsurface + k;
1296 if (!(surface->texture->supercontents & SUPERCONTENTS_SOLID))
1298 numcollisionmeshtriangles += surface->num_triangles;
1300 mod->brush.collisionmesh = Mod_ShadowMesh_Begin(mempool, numcollisionmeshtriangles * 3, numcollisionmeshtriangles, NULL, NULL, NULL, false, false, true);
1301 for (k = 0;k < mod->nummodelsurfaces;k++)
1303 surface = mod->data_surfaces + mod->firstmodelsurface + k;
1304 if (!(surface->texture->supercontents & SUPERCONTENTS_SOLID))
1306 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));
1308 mod->brush.collisionmesh = Mod_ShadowMesh_Finish(mempool, mod->brush.collisionmesh, false, true, false);
1311 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)
1316 if (ix >= 0 && iy >= 0 && ix < imagewidth && iy < imageheight)
1317 v[2] = (imagepixels[((iy*imagewidth)+ix)*4+0] + imagepixels[((iy*imagewidth)+ix)*4+1] + imagepixels[((iy*imagewidth)+ix)*4+2]) * (1.0f / 765.0f);
1320 Matrix4x4_Transform(pixelstepmatrix, v, vertex3f);
1321 Matrix4x4_Transform(pixeltexturestepmatrix, v, tc);
1322 texcoord2f[0] = tc[0];
1323 texcoord2f[1] = tc[1];
1326 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)
1328 float vup[3], vdown[3], vleft[3], vright[3];
1329 float tcup[3], tcdown[3], tcleft[3], tcright[3];
1330 float sv[3], tv[3], nl[3];
1331 Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, pixelstepmatrix, pixeltexturestepmatrix);
1332 Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy - 1, vup, tcup, pixelstepmatrix, pixeltexturestepmatrix);
1333 Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy + 1, vdown, tcdown, pixelstepmatrix, pixeltexturestepmatrix);
1334 Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix - 1, iy, vleft, tcleft, pixelstepmatrix, pixeltexturestepmatrix);
1335 Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix + 1, iy, vright, tcright, pixelstepmatrix, pixeltexturestepmatrix);
1336 Mod_BuildBumpVectors(vertex3f, vup, vright, texcoord2f, tcup, tcright, svector3f, tvector3f, normal3f);
1337 Mod_BuildBumpVectors(vertex3f, vright, vdown, texcoord2f, tcright, tcdown, sv, tv, nl);
1338 VectorAdd(svector3f, sv, svector3f);
1339 VectorAdd(tvector3f, tv, tvector3f);
1340 VectorAdd(normal3f, nl, normal3f);
1341 Mod_BuildBumpVectors(vertex3f, vdown, vleft, texcoord2f, tcdown, tcleft, sv, tv, nl);
1342 VectorAdd(svector3f, sv, svector3f);
1343 VectorAdd(tvector3f, tv, tvector3f);
1344 VectorAdd(normal3f, nl, normal3f);
1345 Mod_BuildBumpVectors(vertex3f, vleft, vup, texcoord2f, tcleft, tcup, sv, tv, nl);
1346 VectorAdd(svector3f, sv, svector3f);
1347 VectorAdd(tvector3f, tv, tvector3f);
1348 VectorAdd(normal3f, nl, normal3f);
1351 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)
1353 int x, y, ix, iy, *e;
1355 for (y = 0;y < height;y++)
1357 for (x = 0;x < width;x++)
1359 e[0] = (y + 1) * (width + 1) + (x + 0);
1360 e[1] = (y + 0) * (width + 1) + (x + 0);
1361 e[2] = (y + 1) * (width + 1) + (x + 1);
1362 e[3] = (y + 0) * (width + 1) + (x + 0);
1363 e[4] = (y + 0) * (width + 1) + (x + 1);
1364 e[5] = (y + 1) * (width + 1) + (x + 1);
1368 Mod_BuildTriangleNeighbors(neighbor3i, element3i, width*height*2);
1369 for (y = 0, iy = y1;y < height + 1;y++, iy++)
1370 for (x = 0, ix = x1;x < width + 1;x++, ix++, vertex3f += 3, texcoord2f += 2, svector3f += 3, tvector3f += 3, normal3f += 3)
1371 Mod_GetTerrainVertexFromBGRA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, svector3f, tvector3f, normal3f, pixelstepmatrix, pixeltexturestepmatrix);
1375 void Mod_Terrain_SurfaceRecurseChunk(dp_model_t *model, int stepsize, int x, int y)
1379 float chunkwidth = min(stepsize, model->terrain.width - 1 - x);
1380 float chunkheight = min(stepsize, model->terrain.height - 1 - y);
1381 float viewvector[3];
1382 unsigned int firstvertex;
1385 if (chunkwidth < 2 || chunkheight < 2)
1387 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]);
1388 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]);
1389 viewvector[0] = bound(mins[0], localvieworigin, maxs[0]) - model->terrain.vieworigin[0];
1390 viewvector[1] = bound(mins[1], localvieworigin, maxs[1]) - model->terrain.vieworigin[1];
1391 viewvector[2] = bound(mins[2], localvieworigin, maxs[2]) - model->terrain.vieworigin[2];
1392 if (stepsize > 1 && VectorLength(viewvector) < stepsize*model->terrain.scale[0]*r_terrain_lodscale.value)
1394 // too close for this stepsize, emit as 4 chunks instead
1396 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x, y);
1397 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x+stepsize, y);
1398 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x, y+stepsize);
1399 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x+stepsize, y+stepsize);
1402 // emit the geometry at stepsize into our vertex buffer / index buffer
1403 // we add two columns and two rows for skirt
1404 outwidth = chunkwidth+2;
1405 outheight = chunkheight+2;
1406 outwidth2 = outwidth-1;
1407 outheight2 = outheight-1;
1408 outwidth3 = outwidth+1;
1409 outheight3 = outheight+1;
1410 firstvertex = numvertices;
1411 e = model->terrain.element3i + numtriangles;
1412 numtriangles += chunkwidth*chunkheight*2+chunkwidth*2*2+chunkheight*2*2;
1413 v = model->terrain.vertex3f + numvertices;
1414 numvertices += (chunkwidth+1)*(chunkheight+1)+(chunkwidth+1)*2+(chunkheight+1)*2;
1415 // emit the triangles (note: the skirt is treated as two extra rows and two extra columns)
1416 for (ty = 0;ty < outheight;ty++)
1418 for (tx = 0;tx < outwidth;tx++)
1420 *e++ = firstvertex + (ty )*outwidth3+(tx );
1421 *e++ = firstvertex + (ty )*outwidth3+(tx+1);
1422 *e++ = firstvertex + (ty+1)*outwidth3+(tx+1);
1423 *e++ = firstvertex + (ty )*outwidth3+(tx );
1424 *e++ = firstvertex + (ty+1)*outwidth3+(tx+1);
1425 *e++ = firstvertex + (ty+1)*outwidth3+(tx );
1428 // TODO: emit surface vertices (x+tx*stepsize, y+ty*stepsize)
1429 for (ty = 0;ty <= outheight;ty++)
1431 skirtrow = ty == 0 || ty == outheight;
1432 ry = y+bound(1, ty, outheight)*stepsize;
1433 for (tx = 0;tx <= outwidth;tx++)
1435 skirt = skirtrow || tx == 0 || tx == outwidth;
1436 rx = x+bound(1, tx, outwidth)*stepsize;
1439 v[2] = heightmap[ry*terrainwidth+rx]*scale[2];
1443 // TODO: emit skirt vertices
1446 void Mod_Terrain_UpdateSurfacesForViewOrigin(dp_model_t *model)
1448 for (y = 0;y < model->terrain.size[1];y += model->terrain.
1449 Mod_Terrain_SurfaceRecurseChunk(model, model->terrain.maxstepsize, x, y);
1450 Mod_Terrain_BuildChunk(model,
1454 q3wavefunc_t Mod_LoadQ3Shaders_EnumerateWaveFunc(const char *s)
1456 if (!strcasecmp(s, "sin")) return Q3WAVEFUNC_SIN;
1457 if (!strcasecmp(s, "square")) return Q3WAVEFUNC_SQUARE;
1458 if (!strcasecmp(s, "triangle")) return Q3WAVEFUNC_TRIANGLE;
1459 if (!strcasecmp(s, "sawtooth")) return Q3WAVEFUNC_SAWTOOTH;
1460 if (!strcasecmp(s, "inversesawtooth")) return Q3WAVEFUNC_INVERSESAWTOOTH;
1461 if (!strcasecmp(s, "noise")) return Q3WAVEFUNC_NOISE;
1462 Con_DPrintf("Mod_LoadQ3Shaders: unknown wavefunc %s\n", s);
1463 return Q3WAVEFUNC_NONE;
1466 void Mod_FreeQ3Shaders(void)
1468 Mem_FreePool(&q3shaders_mem);
1471 static void Q3Shader_AddToHash (q3shaderinfo_t* shader)
1473 unsigned short hash = CRC_Block_CaseInsensitive ((const unsigned char *)shader->name, strlen (shader->name));
1474 q3shader_hash_entry_t* entry = q3shader_data->hash + (hash % Q3SHADER_HASH_SIZE);
1475 q3shader_hash_entry_t* lastEntry = NULL;
1476 while (entry != NULL)
1478 if (strcasecmp (entry->shader.name, shader->name) == 0)
1480 unsigned char *start, *end, *start2;
1481 start = (unsigned char *) (&shader->Q3SHADERINFO_COMPARE_START);
1482 end = ((unsigned char *) (&shader->Q3SHADERINFO_COMPARE_END)) + sizeof(shader->Q3SHADERINFO_COMPARE_END);
1483 start2 = (unsigned char *) (&entry->shader.Q3SHADERINFO_COMPARE_START);
1484 if(memcmp(start, start2, end - start))
1485 Con_Printf("Shader '%s' already defined, ignoring mismatching redeclaration\n", shader->name);
1487 Con_DPrintf("Shader '%s' already defined\n", shader->name);
1491 entry = entry->chain;
1495 if (lastEntry->shader.name[0] != 0)
1498 q3shader_hash_entry_t* newEntry = (q3shader_hash_entry_t*)
1499 Mem_ExpandableArray_AllocRecord (&q3shader_data->hash_entries);
1501 while (lastEntry->chain != NULL) lastEntry = lastEntry->chain;
1502 lastEntry->chain = newEntry;
1503 newEntry->chain = NULL;
1504 lastEntry = newEntry;
1506 /* else: head of chain, in hash entry array */
1509 memcpy (&entry->shader, shader, sizeof (q3shaderinfo_t));
1512 extern cvar_t r_picmipworld;
1513 void Mod_LoadQ3Shaders(void)
1520 q3shaderinfo_t shader;
1521 q3shaderinfo_layer_t *layer;
1523 char parameter[TEXTURE_MAXFRAMES + 4][Q3PATHLENGTH];
1525 Mod_FreeQ3Shaders();
1527 q3shaders_mem = Mem_AllocPool("q3shaders", 0, NULL);
1528 q3shader_data = (q3shader_data_t*)Mem_Alloc (q3shaders_mem,
1529 sizeof (q3shader_data_t));
1530 Mem_ExpandableArray_NewArray (&q3shader_data->hash_entries,
1531 q3shaders_mem, sizeof (q3shader_hash_entry_t), 256);
1532 Mem_ExpandableArray_NewArray (&q3shader_data->char_ptrs,
1533 q3shaders_mem, sizeof (char**), 256);
1535 search = FS_Search("scripts/*.shader", true, false);
1538 for (fileindex = 0;fileindex < search->numfilenames;fileindex++)
1540 text = f = (char *)FS_LoadFile(search->filenames[fileindex], tempmempool, false, NULL);
1543 while (COM_ParseToken_QuakeC(&text, false))
1545 memset (&shader, 0, sizeof(shader));
1546 shader.reflectmin = 0;
1547 shader.reflectmax = 1;
1548 shader.refractfactor = 1;
1549 Vector4Set(shader.refractcolor4f, 1, 1, 1, 1);
1550 shader.reflectfactor = 1;
1551 Vector4Set(shader.reflectcolor4f, 1, 1, 1, 1);
1552 shader.r_water_wateralpha = 1;
1553 shader.specularscalemod = 1;
1554 shader.specularpowermod = 1;
1556 strlcpy(shader.name, com_token, sizeof(shader.name));
1557 if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1559 Con_Printf("%s parsing error - expected \"{\", found \"%s\"\n", search->filenames[fileindex], com_token);
1562 while (COM_ParseToken_QuakeC(&text, false))
1564 if (!strcasecmp(com_token, "}"))
1566 if (!strcasecmp(com_token, "{"))
1568 static q3shaderinfo_layer_t dummy;
1569 if (shader.numlayers < Q3SHADER_MAXLAYERS)
1571 layer = shader.layers + shader.numlayers++;
1575 // parse and process it anyway, just don't store it (so a map $lightmap or such stuff still is found)
1576 memset(&dummy, 0, sizeof(dummy));
1579 layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1580 layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1581 layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1582 layer->blendfunc[0] = GL_ONE;
1583 layer->blendfunc[1] = GL_ZERO;
1584 while (COM_ParseToken_QuakeC(&text, false))
1586 if (!strcasecmp(com_token, "}"))
1588 if (!strcasecmp(com_token, "\n"))
1591 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1593 if (j < TEXTURE_MAXFRAMES + 4)
1595 strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1596 numparameters = j + 1;
1598 if (!COM_ParseToken_QuakeC(&text, true))
1601 //for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1602 // parameter[j][0] = 0;
1603 if (developer.integer >= 100)
1605 Con_Printf("%s %i: ", shader.name, shader.numlayers - 1);
1606 for (j = 0;j < numparameters;j++)
1607 Con_Printf(" %s", parameter[j]);
1610 if (numparameters >= 2 && !strcasecmp(parameter[0], "blendfunc"))
1612 if (numparameters == 2)
1614 if (!strcasecmp(parameter[1], "add"))
1616 layer->blendfunc[0] = GL_ONE;
1617 layer->blendfunc[1] = GL_ONE;
1619 else if (!strcasecmp(parameter[1], "filter"))
1621 layer->blendfunc[0] = GL_DST_COLOR;
1622 layer->blendfunc[1] = GL_ZERO;
1624 else if (!strcasecmp(parameter[1], "blend"))
1626 layer->blendfunc[0] = GL_SRC_ALPHA;
1627 layer->blendfunc[1] = GL_ONE_MINUS_SRC_ALPHA;
1630 else if (numparameters == 3)
1633 for (k = 0;k < 2;k++)
1635 if (!strcasecmp(parameter[k+1], "GL_ONE"))
1636 layer->blendfunc[k] = GL_ONE;
1637 else if (!strcasecmp(parameter[k+1], "GL_ZERO"))
1638 layer->blendfunc[k] = GL_ZERO;
1639 else if (!strcasecmp(parameter[k+1], "GL_SRC_COLOR"))
1640 layer->blendfunc[k] = GL_SRC_COLOR;
1641 else if (!strcasecmp(parameter[k+1], "GL_SRC_ALPHA"))
1642 layer->blendfunc[k] = GL_SRC_ALPHA;
1643 else if (!strcasecmp(parameter[k+1], "GL_DST_COLOR"))
1644 layer->blendfunc[k] = GL_DST_COLOR;
1645 else if (!strcasecmp(parameter[k+1], "GL_DST_ALPHA"))
1646 layer->blendfunc[k] = GL_ONE_MINUS_DST_ALPHA;
1647 else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_COLOR"))
1648 layer->blendfunc[k] = GL_ONE_MINUS_SRC_COLOR;
1649 else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_ALPHA"))
1650 layer->blendfunc[k] = GL_ONE_MINUS_SRC_ALPHA;
1651 else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_COLOR"))
1652 layer->blendfunc[k] = GL_ONE_MINUS_DST_COLOR;
1653 else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_ALPHA"))
1654 layer->blendfunc[k] = GL_ONE_MINUS_DST_ALPHA;
1656 layer->blendfunc[k] = GL_ONE; // default in case of parsing error
1660 if (numparameters >= 2 && !strcasecmp(parameter[0], "alphafunc"))
1661 layer->alphatest = true;
1662 if (numparameters >= 2 && (!strcasecmp(parameter[0], "map") || !strcasecmp(parameter[0], "clampmap")))
1664 if (!strcasecmp(parameter[0], "clampmap"))
1665 layer->clampmap = true;
1666 layer->numframes = 1;
1667 layer->framerate = 1;
1668 layer->texturename = (char**)Mem_ExpandableArray_AllocRecord (
1669 &q3shader_data->char_ptrs);
1670 layer->texturename[0] = Mem_strdup (q3shaders_mem, parameter[1]);
1671 if (!strcasecmp(parameter[1], "$lightmap"))
1672 shader.lighting = true;
1674 else if (numparameters >= 3 && (!strcasecmp(parameter[0], "animmap") || !strcasecmp(parameter[0], "animclampmap")))
1677 layer->numframes = min(numparameters - 2, TEXTURE_MAXFRAMES);
1678 layer->framerate = atof(parameter[1]);
1679 layer->texturename = (char **) Mem_Alloc (q3shaders_mem, sizeof (char*) * layer->numframes);
1680 for (i = 0;i < layer->numframes;i++)
1681 layer->texturename[i] = Mem_strdup (q3shaders_mem, parameter[i + 2]);
1683 else if (numparameters >= 2 && !strcasecmp(parameter[0], "rgbgen"))
1686 for (i = 0;i < numparameters - 2 && i < Q3RGBGEN_MAXPARMS;i++)
1687 layer->rgbgen.parms[i] = atof(parameter[i+2]);
1688 if (!strcasecmp(parameter[1], "identity")) layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1689 else if (!strcasecmp(parameter[1], "const")) layer->rgbgen.rgbgen = Q3RGBGEN_CONST;
1690 else if (!strcasecmp(parameter[1], "entity")) layer->rgbgen.rgbgen = Q3RGBGEN_ENTITY;
1691 else if (!strcasecmp(parameter[1], "exactvertex")) layer->rgbgen.rgbgen = Q3RGBGEN_EXACTVERTEX;
1692 else if (!strcasecmp(parameter[1], "identitylighting")) layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITYLIGHTING;
1693 else if (!strcasecmp(parameter[1], "lightingdiffuse")) layer->rgbgen.rgbgen = Q3RGBGEN_LIGHTINGDIFFUSE;
1694 else if (!strcasecmp(parameter[1], "oneminusentity")) layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSENTITY;
1695 else if (!strcasecmp(parameter[1], "oneminusvertex")) layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSVERTEX;
1696 else if (!strcasecmp(parameter[1], "vertex")) layer->rgbgen.rgbgen = Q3RGBGEN_VERTEX;
1697 else if (!strcasecmp(parameter[1], "wave"))
1699 layer->rgbgen.rgbgen = Q3RGBGEN_WAVE;
1700 layer->rgbgen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1701 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1702 layer->rgbgen.waveparms[i] = atof(parameter[i+3]);
1704 else Con_DPrintf("%s parsing warning: unknown rgbgen %s\n", search->filenames[fileindex], parameter[1]);
1706 else if (numparameters >= 2 && !strcasecmp(parameter[0], "alphagen"))
1709 for (i = 0;i < numparameters - 2 && i < Q3ALPHAGEN_MAXPARMS;i++)
1710 layer->alphagen.parms[i] = atof(parameter[i+2]);
1711 if (!strcasecmp(parameter[1], "identity")) layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1712 else if (!strcasecmp(parameter[1], "const")) layer->alphagen.alphagen = Q3ALPHAGEN_CONST;
1713 else if (!strcasecmp(parameter[1], "entity")) layer->alphagen.alphagen = Q3ALPHAGEN_ENTITY;
1714 else if (!strcasecmp(parameter[1], "lightingspecular")) layer->alphagen.alphagen = Q3ALPHAGEN_LIGHTINGSPECULAR;
1715 else if (!strcasecmp(parameter[1], "oneminusentity")) layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSENTITY;
1716 else if (!strcasecmp(parameter[1], "oneminusvertex")) layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSVERTEX;
1717 else if (!strcasecmp(parameter[1], "portal")) layer->alphagen.alphagen = Q3ALPHAGEN_PORTAL;
1718 else if (!strcasecmp(parameter[1], "vertex")) layer->alphagen.alphagen = Q3ALPHAGEN_VERTEX;
1719 else if (!strcasecmp(parameter[1], "wave"))
1721 layer->alphagen.alphagen = Q3ALPHAGEN_WAVE;
1722 layer->alphagen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1723 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1724 layer->alphagen.waveparms[i] = atof(parameter[i+3]);
1726 else Con_DPrintf("%s parsing warning: unknown alphagen %s\n", search->filenames[fileindex], parameter[1]);
1728 else if (numparameters >= 2 && (!strcasecmp(parameter[0], "texgen") || !strcasecmp(parameter[0], "tcgen")))
1731 // observed values: tcgen environment
1732 // no other values have been observed in real shaders
1733 for (i = 0;i < numparameters - 2 && i < Q3TCGEN_MAXPARMS;i++)
1734 layer->tcgen.parms[i] = atof(parameter[i+2]);
1735 if (!strcasecmp(parameter[1], "base")) layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1736 else if (!strcasecmp(parameter[1], "texture")) layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1737 else if (!strcasecmp(parameter[1], "environment")) layer->tcgen.tcgen = Q3TCGEN_ENVIRONMENT;
1738 else if (!strcasecmp(parameter[1], "lightmap")) layer->tcgen.tcgen = Q3TCGEN_LIGHTMAP;
1739 else if (!strcasecmp(parameter[1], "vector")) layer->tcgen.tcgen = Q3TCGEN_VECTOR;
1740 else Con_DPrintf("%s parsing warning: unknown tcgen mode %s\n", search->filenames[fileindex], parameter[1]);
1742 else if (numparameters >= 2 && !strcasecmp(parameter[0], "tcmod"))
1749 // tcmod stretch sin # # # #
1750 // tcmod stretch triangle # # # #
1751 // tcmod transform # # # # # #
1752 // tcmod turb # # # #
1753 // tcmod turb sin # # # # (this is bogus)
1754 // no other values have been observed in real shaders
1755 for (tcmodindex = 0;tcmodindex < Q3MAXTCMODS;tcmodindex++)
1756 if (!layer->tcmods[tcmodindex].tcmod)
1758 if (tcmodindex < Q3MAXTCMODS)
1760 for (i = 0;i < numparameters - 2 && i < Q3TCMOD_MAXPARMS;i++)
1761 layer->tcmods[tcmodindex].parms[i] = atof(parameter[i+2]);
1762 if (!strcasecmp(parameter[1], "entitytranslate")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ENTITYTRANSLATE;
1763 else if (!strcasecmp(parameter[1], "rotate")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ROTATE;
1764 else if (!strcasecmp(parameter[1], "scale")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCALE;
1765 else if (!strcasecmp(parameter[1], "scroll")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCROLL;
1766 else if (!strcasecmp(parameter[1], "page")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_PAGE;
1767 else if (!strcasecmp(parameter[1], "stretch"))
1769 layer->tcmods[tcmodindex].tcmod = Q3TCMOD_STRETCH;
1770 layer->tcmods[tcmodindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1771 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1772 layer->tcmods[tcmodindex].waveparms[i] = atof(parameter[i+3]);
1774 else if (!strcasecmp(parameter[1], "transform")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TRANSFORM;
1775 else if (!strcasecmp(parameter[1], "turb")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TURBULENT;
1776 else Con_DPrintf("%s parsing warning: unknown tcmod mode %s\n", search->filenames[fileindex], parameter[1]);
1779 Con_DPrintf("%s parsing warning: too many tcmods on one layer\n", search->filenames[fileindex]);
1781 // break out a level if it was a closing brace (not using the character here to not confuse vim)
1782 if (!strcasecmp(com_token, "}"))
1785 if (layer->rgbgen.rgbgen == Q3RGBGEN_LIGHTINGDIFFUSE || layer->rgbgen.rgbgen == Q3RGBGEN_VERTEX)
1786 shader.lighting = true;
1787 if (layer->alphagen.alphagen == Q3ALPHAGEN_VERTEX)
1789 if (layer == shader.layers + 0)
1791 // vertex controlled transparency
1792 shader.vertexalpha = true;
1796 // multilayer terrain shader or similar
1797 shader.textureblendalpha = true;
1800 layer->texflags = TEXF_ALPHA | TEXF_PRECACHE;
1801 if (!(shader.surfaceparms & Q3SURFACEPARM_NOMIPMAPS))
1802 layer->texflags |= TEXF_MIPMAP;
1803 if (!(shader.textureflags & Q3TEXTUREFLAG_NOPICMIP))
1804 layer->texflags |= TEXF_PICMIP | TEXF_COMPRESS;
1805 if (layer->clampmap)
1806 layer->texflags |= TEXF_CLAMP;
1810 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1812 if (j < TEXTURE_MAXFRAMES + 4)
1814 strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1815 numparameters = j + 1;
1817 if (!COM_ParseToken_QuakeC(&text, true))
1820 //for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1821 // parameter[j][0] = 0;
1822 if (fileindex == 0 && !strcasecmp(com_token, "}"))
1824 if (developer.integer >= 100)
1826 Con_Printf("%s: ", shader.name);
1827 for (j = 0;j < numparameters;j++)
1828 Con_Printf(" %s", parameter[j]);
1831 if (numparameters < 1)
1833 if (!strcasecmp(parameter[0], "surfaceparm") && numparameters >= 2)
1835 if (!strcasecmp(parameter[1], "alphashadow"))
1836 shader.surfaceparms |= Q3SURFACEPARM_ALPHASHADOW;
1837 else if (!strcasecmp(parameter[1], "areaportal"))
1838 shader.surfaceparms |= Q3SURFACEPARM_AREAPORTAL;
1839 else if (!strcasecmp(parameter[1], "botclip"))
1840 shader.surfaceparms |= Q3SURFACEPARM_BOTCLIP;
1841 else if (!strcasecmp(parameter[1], "clusterportal"))
1842 shader.surfaceparms |= Q3SURFACEPARM_CLUSTERPORTAL;
1843 else if (!strcasecmp(parameter[1], "detail"))
1844 shader.surfaceparms |= Q3SURFACEPARM_DETAIL;
1845 else if (!strcasecmp(parameter[1], "donotenter"))
1846 shader.surfaceparms |= Q3SURFACEPARM_DONOTENTER;
1847 else if (!strcasecmp(parameter[1], "dust"))
1848 shader.surfaceparms |= Q3SURFACEPARM_DUST;
1849 else if (!strcasecmp(parameter[1], "hint"))
1850 shader.surfaceparms |= Q3SURFACEPARM_HINT;
1851 else if (!strcasecmp(parameter[1], "fog"))
1852 shader.surfaceparms |= Q3SURFACEPARM_FOG;
1853 else if (!strcasecmp(parameter[1], "lava"))
1854 shader.surfaceparms |= Q3SURFACEPARM_LAVA;
1855 else if (!strcasecmp(parameter[1], "lightfilter"))
1856 shader.surfaceparms |= Q3SURFACEPARM_LIGHTFILTER;
1857 else if (!strcasecmp(parameter[1], "lightgrid"))
1858 shader.surfaceparms |= Q3SURFACEPARM_LIGHTGRID;
1859 else if (!strcasecmp(parameter[1], "metalsteps"))
1860 shader.surfaceparms |= Q3SURFACEPARM_METALSTEPS;
1861 else if (!strcasecmp(parameter[1], "nodamage"))
1862 shader.surfaceparms |= Q3SURFACEPARM_NODAMAGE;
1863 else if (!strcasecmp(parameter[1], "nodlight"))
1864 shader.surfaceparms |= Q3SURFACEPARM_NODLIGHT;
1865 else if (!strcasecmp(parameter[1], "nodraw"))
1866 shader.surfaceparms |= Q3SURFACEPARM_NODRAW;
1867 else if (!strcasecmp(parameter[1], "nodrop"))
1868 shader.surfaceparms |= Q3SURFACEPARM_NODROP;
1869 else if (!strcasecmp(parameter[1], "noimpact"))
1870 shader.surfaceparms |= Q3SURFACEPARM_NOIMPACT;
1871 else if (!strcasecmp(parameter[1], "nolightmap"))
1872 shader.surfaceparms |= Q3SURFACEPARM_NOLIGHTMAP;
1873 else if (!strcasecmp(parameter[1], "nomarks"))
1874 shader.surfaceparms |= Q3SURFACEPARM_NOMARKS;
1875 else if (!strcasecmp(parameter[1], "nomipmaps"))
1876 shader.surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
1877 else if (!strcasecmp(parameter[1], "nonsolid"))
1878 shader.surfaceparms |= Q3SURFACEPARM_NONSOLID;
1879 else if (!strcasecmp(parameter[1], "origin"))
1880 shader.surfaceparms |= Q3SURFACEPARM_ORIGIN;
1881 else if (!strcasecmp(parameter[1], "playerclip"))
1882 shader.surfaceparms |= Q3SURFACEPARM_PLAYERCLIP;
1883 else if (!strcasecmp(parameter[1], "sky"))
1884 shader.surfaceparms |= Q3SURFACEPARM_SKY;
1885 else if (!strcasecmp(parameter[1], "slick"))
1886 shader.surfaceparms |= Q3SURFACEPARM_SLICK;
1887 else if (!strcasecmp(parameter[1], "slime"))
1888 shader.surfaceparms |= Q3SURFACEPARM_SLIME;
1889 else if (!strcasecmp(parameter[1], "structural"))
1890 shader.surfaceparms |= Q3SURFACEPARM_STRUCTURAL;
1891 else if (!strcasecmp(parameter[1], "trans"))
1892 shader.surfaceparms |= Q3SURFACEPARM_TRANS;
1893 else if (!strcasecmp(parameter[1], "water"))
1894 shader.surfaceparms |= Q3SURFACEPARM_WATER;
1895 else if (!strcasecmp(parameter[1], "pointlight"))
1896 shader.surfaceparms |= Q3SURFACEPARM_POINTLIGHT;
1897 else if (!strcasecmp(parameter[1], "antiportal"))
1898 shader.surfaceparms |= Q3SURFACEPARM_ANTIPORTAL;
1900 Con_DPrintf("%s parsing warning: unknown surfaceparm \"%s\"\n", search->filenames[fileindex], parameter[1]);
1902 else if (!strcasecmp(parameter[0], "dpshadow"))
1903 shader.dpshadow = true;
1904 else if (!strcasecmp(parameter[0], "dpnoshadow"))
1905 shader.dpnoshadow = true;
1906 else if (!strcasecmp(parameter[0], "sky") && numparameters >= 2)
1908 // some q3 skies don't have the sky parm set
1909 shader.surfaceparms |= Q3SURFACEPARM_SKY;
1910 strlcpy(shader.skyboxname, parameter[1], sizeof(shader.skyboxname));
1912 else if (!strcasecmp(parameter[0], "skyparms") && numparameters >= 2)
1914 // some q3 skies don't have the sky parm set
1915 shader.surfaceparms |= Q3SURFACEPARM_SKY;
1916 if (!atoi(parameter[1]) && strcasecmp(parameter[1], "-"))
1917 strlcpy(shader.skyboxname, parameter[1], sizeof(shader.skyboxname));
1919 else if (!strcasecmp(parameter[0], "cull") && numparameters >= 2)
1921 if (!strcasecmp(parameter[1], "disable") || !strcasecmp(parameter[1], "none") || !strcasecmp(parameter[1], "twosided"))
1922 shader.textureflags |= Q3TEXTUREFLAG_TWOSIDED;
1924 else if (!strcasecmp(parameter[0], "nomipmaps"))
1925 shader.surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
1926 else if (!strcasecmp(parameter[0], "nopicmip"))
1927 shader.textureflags |= Q3TEXTUREFLAG_NOPICMIP;
1928 else if (!strcasecmp(parameter[0], "polygonoffset"))
1929 shader.textureflags |= Q3TEXTUREFLAG_POLYGONOFFSET;
1930 else if (!strcasecmp(parameter[0], "dp_refract") && numparameters >= 5)
1932 shader.textureflags |= Q3TEXTUREFLAG_REFRACTION;
1933 shader.refractfactor = atof(parameter[1]);
1934 Vector4Set(shader.refractcolor4f, atof(parameter[2]), atof(parameter[3]), atof(parameter[4]), 1);
1936 else if (!strcasecmp(parameter[0], "dp_reflect") && numparameters >= 6)
1938 shader.textureflags |= Q3TEXTUREFLAG_REFLECTION;
1939 shader.reflectfactor = atof(parameter[1]);
1940 Vector4Set(shader.reflectcolor4f, atof(parameter[2]), atof(parameter[3]), atof(parameter[4]), atof(parameter[5]));
1942 else if (!strcasecmp(parameter[0], "dp_water") && numparameters >= 12)
1944 shader.textureflags |= Q3TEXTUREFLAG_WATERSHADER;
1945 shader.reflectmin = atof(parameter[1]);
1946 shader.reflectmax = atof(parameter[2]);
1947 shader.refractfactor = atof(parameter[3]);
1948 shader.reflectfactor = atof(parameter[4]);
1949 Vector4Set(shader.refractcolor4f, atof(parameter[5]), atof(parameter[6]), atof(parameter[7]), 1);
1950 Vector4Set(shader.reflectcolor4f, atof(parameter[8]), atof(parameter[9]), atof(parameter[10]), 1);
1951 shader.r_water_wateralpha = atof(parameter[11]);
1953 else if (!strcasecmp(parameter[0], "dp_glossintensitymod") && numparameters >= 2)
1955 shader.specularscalemod = atof(parameter[1]);
1957 else if (!strcasecmp(parameter[0], "dp_glossexponentmod") && numparameters >= 2)
1959 shader.specularpowermod = atof(parameter[1]);
1961 else if (!strcasecmp(parameter[0], "deformvertexes") && numparameters >= 2)
1964 for (deformindex = 0;deformindex < Q3MAXDEFORMS;deformindex++)
1965 if (!shader.deforms[deformindex].deform)
1967 if (deformindex < Q3MAXDEFORMS)
1969 for (i = 0;i < numparameters - 2 && i < Q3DEFORM_MAXPARMS;i++)
1970 shader.deforms[deformindex].parms[i] = atof(parameter[i+2]);
1971 if (!strcasecmp(parameter[1], "projectionshadow")) shader.deforms[deformindex].deform = Q3DEFORM_PROJECTIONSHADOW;
1972 else if (!strcasecmp(parameter[1], "autosprite" )) shader.deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE;
1973 else if (!strcasecmp(parameter[1], "autosprite2" )) shader.deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE2;
1974 else if (!strcasecmp(parameter[1], "text0" )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT0;
1975 else if (!strcasecmp(parameter[1], "text1" )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT1;
1976 else if (!strcasecmp(parameter[1], "text2" )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT2;
1977 else if (!strcasecmp(parameter[1], "text3" )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT3;
1978 else if (!strcasecmp(parameter[1], "text4" )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT4;
1979 else if (!strcasecmp(parameter[1], "text5" )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT5;
1980 else if (!strcasecmp(parameter[1], "text6" )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT6;
1981 else if (!strcasecmp(parameter[1], "text7" )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT7;
1982 else if (!strcasecmp(parameter[1], "bulge" )) shader.deforms[deformindex].deform = Q3DEFORM_BULGE;
1983 else if (!strcasecmp(parameter[1], "normal" )) shader.deforms[deformindex].deform = Q3DEFORM_NORMAL;
1984 else if (!strcasecmp(parameter[1], "wave" ))
1986 shader.deforms[deformindex].deform = Q3DEFORM_WAVE;
1987 shader.deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[3]);
1988 for (i = 0;i < numparameters - 4 && i < Q3WAVEPARMS;i++)
1989 shader.deforms[deformindex].waveparms[i] = atof(parameter[i+4]);
1991 else if (!strcasecmp(parameter[1], "move" ))
1993 shader.deforms[deformindex].deform = Q3DEFORM_MOVE;
1994 shader.deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[5]);
1995 for (i = 0;i < numparameters - 6 && i < Q3WAVEPARMS;i++)
1996 shader.deforms[deformindex].waveparms[i] = atof(parameter[i+6]);
2001 // pick the primary layer to render with
2002 if (shader.numlayers)
2004 shader.backgroundlayer = -1;
2005 shader.primarylayer = 0;
2006 // if lightmap comes first this is definitely an ordinary texture
2007 // if the first two layers have the correct blendfuncs and use vertex alpha, it is a blended terrain shader
2008 if ((shader.layers[shader.primarylayer].texturename != NULL)
2009 && !strcasecmp(shader.layers[shader.primarylayer].texturename[0], "$lightmap"))
2011 shader.backgroundlayer = -1;
2012 shader.primarylayer = 1;
2014 else if (shader.numlayers >= 2
2015 && shader.layers[1].alphagen.alphagen == Q3ALPHAGEN_VERTEX
2016 && (shader.layers[0].blendfunc[0] == GL_ONE && shader.layers[0].blendfunc[1] == GL_ZERO && !shader.layers[0].alphatest)
2017 && ((shader.layers[1].blendfunc[0] == GL_SRC_ALPHA && shader.layers[1].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA)
2018 || (shader.layers[1].blendfunc[0] == GL_ONE && shader.layers[1].blendfunc[1] == GL_ZERO && shader.layers[1].alphatest)))
2020 // terrain blending or other effects
2021 shader.backgroundlayer = 0;
2022 shader.primarylayer = 1;
2025 // fix up multiple reflection types
2026 if(shader.textureflags & Q3TEXTUREFLAG_WATERSHADER)
2027 shader.textureflags &= ~(Q3TEXTUREFLAG_REFRACTION | Q3TEXTUREFLAG_REFLECTION);
2029 Q3Shader_AddToHash (&shader);
2033 FS_FreeSearch(search);
2036 q3shaderinfo_t *Mod_LookupQ3Shader(const char *name)
2038 unsigned short hash;
2039 q3shader_hash_entry_t* entry;
2041 Mod_LoadQ3Shaders();
2042 hash = CRC_Block_CaseInsensitive ((const unsigned char *)name, strlen (name));
2043 entry = q3shader_data->hash + (hash % Q3SHADER_HASH_SIZE);
2044 while (entry != NULL)
2046 if (strcasecmp (entry->shader.name, name) == 0)
2047 return &entry->shader;
2048 entry = entry->chain;
2053 qboolean Mod_LoadTextureFromQ3Shader(texture_t *texture, const char *name, qboolean warnmissing, qboolean fallback, int defaulttexflags)
2057 qboolean success = true;
2058 q3shaderinfo_t *shader;
2061 strlcpy(texture->name, name, sizeof(texture->name));
2062 shader = name[0] ? Mod_LookupQ3Shader(name) : NULL;
2065 if(!(defaulttexflags & TEXF_PICMIP))
2066 texflagsmask &= ~TEXF_PICMIP;
2067 if(!(defaulttexflags & TEXF_COMPRESS))
2068 texflagsmask &= ~TEXF_COMPRESS;
2069 texture->specularscalemod = 1; // unless later loaded from the shader
2070 texture->specularpowermod = 1; // unless later loaded from the shader
2074 if (developer_loading.integer)
2075 Con_Printf("%s: loaded shader for %s\n", loadmodel->name, name);
2076 texture->surfaceparms = shader->surfaceparms;
2078 // allow disabling of picmip or compression by defaulttexflags
2079 texture->textureflags = shader->textureflags & texflagsmask;
2081 if (shader->surfaceparms & Q3SURFACEPARM_SKY)
2083 texture->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
2084 if (shader->skyboxname[0])
2086 // quake3 seems to append a _ to the skybox name, so this must do so as well
2087 dpsnprintf(loadmodel->brush.skybox, sizeof(loadmodel->brush.skybox), "%s_", shader->skyboxname);
2090 else if ((texture->surfaceflags & Q3SURFACEFLAG_NODRAW) || shader->numlayers == 0)
2091 texture->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2093 texture->basematerialflags = MATERIALFLAG_WALL;
2095 if (shader->layers[0].alphatest)
2096 texture->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
2097 if (shader->textureflags & Q3TEXTUREFLAG_TWOSIDED)
2098 texture->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
2099 if (shader->textureflags & Q3TEXTUREFLAG_POLYGONOFFSET)
2100 texture->biaspolygonoffset -= 2;
2101 if (shader->textureflags & Q3TEXTUREFLAG_REFRACTION)
2102 texture->basematerialflags |= MATERIALFLAG_REFRACTION;
2103 if (shader->textureflags & Q3TEXTUREFLAG_REFLECTION)
2104 texture->basematerialflags |= MATERIALFLAG_REFLECTION;
2105 if (shader->textureflags & Q3TEXTUREFLAG_WATERSHADER)
2106 texture->basematerialflags |= MATERIALFLAG_WATERSHADER;
2107 texture->customblendfunc[0] = GL_ONE;
2108 texture->customblendfunc[1] = GL_ZERO;
2109 if (shader->numlayers > 0)
2111 texture->customblendfunc[0] = shader->layers[0].blendfunc[0];
2112 texture->customblendfunc[1] = shader->layers[0].blendfunc[1];
2114 Q3 shader blendfuncs actually used in the game (* = supported by DP)
2115 * additive GL_ONE GL_ONE
2116 additive weird GL_ONE GL_SRC_ALPHA
2117 additive weird 2 GL_ONE GL_ONE_MINUS_SRC_ALPHA
2118 * alpha GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA
2119 alpha inverse GL_ONE_MINUS_SRC_ALPHA GL_SRC_ALPHA
2120 brighten GL_DST_COLOR GL_ONE
2121 brighten GL_ONE GL_SRC_COLOR
2122 brighten weird GL_DST_COLOR GL_ONE_MINUS_DST_ALPHA
2123 brighten weird 2 GL_DST_COLOR GL_SRC_ALPHA
2124 * modulate GL_DST_COLOR GL_ZERO
2125 * modulate GL_ZERO GL_SRC_COLOR
2126 modulate inverse GL_ZERO GL_ONE_MINUS_SRC_COLOR
2127 modulate inverse alpha GL_ZERO GL_SRC_ALPHA
2128 modulate weird inverse GL_ONE_MINUS_DST_COLOR GL_ZERO
2129 * modulate x2 GL_DST_COLOR GL_SRC_COLOR
2130 * no blend GL_ONE GL_ZERO
2131 nothing GL_ZERO GL_ONE
2133 // if not opaque, figure out what blendfunc to use
2134 if (shader->layers[0].blendfunc[0] != GL_ONE || shader->layers[0].blendfunc[1] != GL_ZERO)
2136 if (shader->layers[0].blendfunc[0] == GL_ONE && shader->layers[0].blendfunc[1] == GL_ONE)
2137 texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2138 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE)
2139 texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2140 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA)
2141 texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2143 texture->basematerialflags |= MATERIALFLAG_CUSTOMBLEND | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2146 if (!shader->lighting)
2147 texture->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
2148 if (shader->primarylayer >= 0)
2150 q3shaderinfo_layer_t* primarylayer = shader->layers + shader->primarylayer;
2151 // copy over many primarylayer parameters
2152 texture->rgbgen = primarylayer->rgbgen;
2153 texture->alphagen = primarylayer->alphagen;
2154 texture->tcgen = primarylayer->tcgen;
2155 memcpy(texture->tcmods, primarylayer->tcmods, sizeof(texture->tcmods));
2156 // load the textures
2157 texture->numskinframes = primarylayer->numframes;
2158 texture->skinframerate = primarylayer->framerate;
2159 for (j = 0;j < primarylayer->numframes;j++)
2161 if(cls.state == ca_dedicated)
2163 texture->skinframes[j] = NULL;
2165 else if (!(texture->skinframes[j] = R_SkinFrame_LoadExternal(primarylayer->texturename[j], primarylayer->texflags & texflagsmask, false)))
2167 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);
2168 texture->skinframes[j] = R_SkinFrame_LoadMissing();
2172 if (shader->backgroundlayer >= 0)
2174 q3shaderinfo_layer_t* backgroundlayer = shader->layers + shader->backgroundlayer;
2175 // copy over one secondarylayer parameter
2176 memcpy(texture->backgroundtcmods, backgroundlayer->tcmods, sizeof(texture->backgroundtcmods));
2177 // load the textures
2178 texture->backgroundnumskinframes = backgroundlayer->numframes;
2179 texture->backgroundskinframerate = backgroundlayer->framerate;
2180 for (j = 0;j < backgroundlayer->numframes;j++)
2182 if(cls.state == ca_dedicated)
2184 texture->skinframes[j] = NULL;
2186 else if (!(texture->backgroundskinframes[j] = R_SkinFrame_LoadExternal(backgroundlayer->texturename[j], backgroundlayer->texflags & texflagsmask, false)))
2188 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);
2189 texture->backgroundskinframes[j] = R_SkinFrame_LoadMissing();
2193 if (shader->dpshadow)
2194 texture->basematerialflags &= ~MATERIALFLAG_NOSHADOW;
2195 if (shader->dpnoshadow)
2196 texture->basematerialflags |= MATERIALFLAG_NOSHADOW;
2197 memcpy(texture->deforms, shader->deforms, sizeof(texture->deforms));
2198 texture->reflectmin = shader->reflectmin;
2199 texture->reflectmax = shader->reflectmax;
2200 texture->refractfactor = shader->refractfactor;
2201 Vector4Copy(shader->refractcolor4f, texture->refractcolor4f);
2202 texture->reflectfactor = shader->reflectfactor;
2203 Vector4Copy(shader->reflectcolor4f, texture->reflectcolor4f);
2204 texture->r_water_wateralpha = shader->r_water_wateralpha;
2205 texture->specularscalemod = shader->specularscalemod;
2206 texture->specularpowermod = shader->specularpowermod;
2208 else if (!strcmp(texture->name, "noshader") || !texture->name[0])
2210 if (developer.integer >= 100)
2211 Con_Printf("^1%s:^7 using fallback noshader material for ^3\"%s\"\n", loadmodel->name, name);
2212 texture->surfaceparms = 0;
2214 else if (!strcmp(texture->name, "common/nodraw") || !strcmp(texture->name, "textures/common/nodraw"))
2216 if (developer.integer >= 100)
2217 Con_Printf("^1%s:^7 using fallback nodraw material for ^3\"%s\"\n", loadmodel->name, name);
2218 texture->surfaceparms = 0;
2219 texture->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2223 if (developer.integer >= 100)
2224 Con_Printf("^1%s:^7 No shader found for texture ^3\"%s\"\n", loadmodel->name, texture->name);
2225 texture->surfaceparms = 0;
2226 if (texture->surfaceflags & Q3SURFACEFLAG_NODRAW)
2227 texture->basematerialflags |= MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2228 else if (texture->surfaceflags & Q3SURFACEFLAG_SKY)
2229 texture->basematerialflags |= MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
2231 texture->basematerialflags |= MATERIALFLAG_WALL;
2232 texture->numskinframes = 1;
2233 if(cls.state == ca_dedicated)
2235 texture->skinframes[0] = NULL;
2242 if ((texture->skinframes[0] = R_SkinFrame_LoadExternal_CheckAlpha(texture->name, defaulttexflags, false, &has_alpha)))
2244 if(has_alpha && (defaulttexflags & TEXF_ALPHA))
2245 texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2252 if (!success && warnmissing)
2253 Con_Printf("^1%s:^7 could not load texture ^3\"%s\"\n", loadmodel->name, texture->name);
2256 // init the animation variables
2257 texture->currentframe = texture;
2258 if (texture->numskinframes < 1)
2259 texture->numskinframes = 1;
2260 if (!texture->skinframes[0])
2261 texture->skinframes[0] = R_SkinFrame_LoadMissing();
2262 texture->currentskinframe = texture->skinframes[0];
2263 texture->backgroundcurrentskinframe = texture->backgroundskinframes[0];
2267 skinfile_t *Mod_LoadSkinFiles(void)
2269 int i, words, line, wordsoverflow;
2272 skinfile_t *skinfile = NULL, *first = NULL;
2273 skinfileitem_t *skinfileitem;
2274 char word[10][MAX_QPATH];
2278 U_bodyBox,models/players/Legoman/BikerA2.tga
2279 U_RArm,models/players/Legoman/BikerA1.tga
2280 U_LArm,models/players/Legoman/BikerA1.tga
2281 U_armor,common/nodraw
2282 U_sword,common/nodraw
2283 U_shield,common/nodraw
2284 U_homb,common/nodraw
2285 U_backpack,common/nodraw
2286 U_colcha,common/nodraw
2291 memset(word, 0, sizeof(word));
2292 for (i = 0;i < 256 && (data = text = (char *)FS_LoadFile(va("%s_%i.skin", loadmodel->name, i), tempmempool, true, NULL));i++)
2294 // If it's the first file we parse
2295 if (skinfile == NULL)
2297 skinfile = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
2302 skinfile->next = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
2303 skinfile = skinfile->next;
2305 skinfile->next = NULL;
2307 for(line = 0;;line++)
2310 if (!COM_ParseToken_QuakeC(&data, true))
2312 if (!strcmp(com_token, "\n"))
2315 wordsoverflow = false;
2319 strlcpy(word[words++], com_token, sizeof (word[0]));
2321 wordsoverflow = true;
2323 while (COM_ParseToken_QuakeC(&data, true) && strcmp(com_token, "\n"));
2326 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);
2329 // words is always >= 1
2330 if (!strcmp(word[0], "replace"))
2334 if (developer_loading.integer)
2335 Con_Printf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[1], word[2]);
2336 skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
2337 skinfileitem->next = skinfile->items;
2338 skinfile->items = skinfileitem;
2339 strlcpy (skinfileitem->name, word[1], sizeof (skinfileitem->name));
2340 strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
2343 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]);
2345 else if (words >= 2 && !strncmp(word[0], "tag_", 4))
2347 // tag name, like "tag_weapon,"
2348 // not used for anything (not even in Quake3)
2350 else if (words >= 2 && !strcmp(word[1], ","))
2352 // mesh shader name, like "U_RArm,models/players/Legoman/BikerA1.tga"
2353 if (developer_loading.integer)
2354 Con_Printf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[0], word[2]);
2355 skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
2356 skinfileitem->next = skinfile->items;
2357 skinfile->items = skinfileitem;
2358 strlcpy (skinfileitem->name, word[0], sizeof (skinfileitem->name));
2359 strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
2362 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);
2367 loadmodel->numskins = i;
2371 void Mod_FreeSkinFiles(skinfile_t *skinfile)
2374 skinfileitem_t *skinfileitem, *nextitem;
2375 for (;skinfile;skinfile = next)
2377 next = skinfile->next;
2378 for (skinfileitem = skinfile->items;skinfileitem;skinfileitem = nextitem)
2380 nextitem = skinfileitem->next;
2381 Mem_Free(skinfileitem);
2387 int Mod_CountSkinFiles(skinfile_t *skinfile)
2390 for (i = 0;skinfile;skinfile = skinfile->next, i++);
2394 void Mod_SnapVertices(int numcomponents, int numvertices, float *vertices, float snap)
2397 double isnap = 1.0 / snap;
2398 for (i = 0;i < numvertices*numcomponents;i++)
2399 vertices[i] = floor(vertices[i]*isnap)*snap;
2402 int Mod_RemoveDegenerateTriangles(int numtriangles, const int *inelement3i, int *outelement3i, const float *vertex3f)
2404 int i, outtriangles;
2405 float edgedir1[3], edgedir2[3], temp[3];
2406 // a degenerate triangle is one with no width (thickness, surface area)
2407 // these are characterized by having all 3 points colinear (along a line)
2408 // or having two points identical
2409 // the simplest check is to calculate the triangle's area
2410 for (i = 0, outtriangles = 0;i < numtriangles;i++, inelement3i += 3)
2412 // calculate first edge
2413 VectorSubtract(vertex3f + inelement3i[1] * 3, vertex3f + inelement3i[0] * 3, edgedir1);
2414 VectorSubtract(vertex3f + inelement3i[2] * 3, vertex3f + inelement3i[0] * 3, edgedir2);
2415 CrossProduct(edgedir1, edgedir2, temp);
2416 if (VectorLength2(temp) < 0.001f)
2417 continue; // degenerate triangle (no area)
2418 // valid triangle (has area)
2419 VectorCopy(inelement3i, outelement3i);
2423 return outtriangles;
2426 void Mod_VertexRangeFromElements(int numelements, const int *elements, int *firstvertexpointer, int *lastvertexpointer)
2429 int firstvertex, lastvertex;
2430 if (numelements > 0 && elements)
2432 firstvertex = lastvertex = elements[0];
2433 for (i = 1;i < numelements;i++)
2436 firstvertex = min(firstvertex, e);
2437 lastvertex = max(lastvertex, e);
2441 firstvertex = lastvertex = 0;
2442 if (firstvertexpointer)
2443 *firstvertexpointer = firstvertex;
2444 if (lastvertexpointer)
2445 *lastvertexpointer = lastvertex;
2448 void Mod_MakeSortedSurfaces(dp_model_t *mod)
2450 // make an optimal set of texture-sorted batches to draw...
2452 int *firstsurfacefortexture;
2453 int *numsurfacesfortexture;
2454 if (!mod->sortedmodelsurfaces)
2455 mod->sortedmodelsurfaces = (int *) Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
2456 firstsurfacefortexture = (int *) Mem_Alloc(tempmempool, mod->num_textures * sizeof(*firstsurfacefortexture));
2457 numsurfacesfortexture = (int *) Mem_Alloc(tempmempool, mod->num_textures * sizeof(*numsurfacesfortexture));
2458 memset(numsurfacesfortexture, 0, mod->num_textures * sizeof(*numsurfacesfortexture));
2459 for (j = 0;j < mod->nummodelsurfaces;j++)
2461 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
2462 int t = (int)(surface->texture - mod->data_textures);
2463 numsurfacesfortexture[t]++;
2466 for (t = 0;t < mod->num_textures;t++)
2468 firstsurfacefortexture[t] = j;
2469 j += numsurfacesfortexture[t];
2471 for (j = 0;j < mod->nummodelsurfaces;j++)
2473 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
2474 int t = (int)(surface->texture - mod->data_textures);
2475 mod->sortedmodelsurfaces[firstsurfacefortexture[t]++] = j + mod->firstmodelsurface;
2477 Mem_Free(firstsurfacefortexture);
2478 Mem_Free(numsurfacesfortexture);
2481 static void Mod_BuildVBOs(void)
2483 if (developer.integer && loadmodel->surfmesh.data_element3s && loadmodel->surfmesh.data_element3i)
2486 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2488 if (loadmodel->surfmesh.data_element3s[i] != loadmodel->surfmesh.data_element3i[i])
2490 Con_Printf("Mod_BuildVBOs: element %u is incorrect (%u should be %u)\n", i, loadmodel->surfmesh.data_element3s[i], loadmodel->surfmesh.data_element3i[i]);
2491 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2496 if (!gl_support_arb_vertex_buffer_object)
2499 // element buffer is easy because it's just one array
2500 if (loadmodel->surfmesh.num_triangles)
2502 if (loadmodel->surfmesh.data_element3s)
2503 loadmodel->surfmesh.ebo3s = R_Mesh_CreateStaticBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB, loadmodel->surfmesh.data_element3s, loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]), loadmodel->name);
2505 loadmodel->surfmesh.ebo3i = R_Mesh_CreateStaticBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles * sizeof(unsigned int[3]), loadmodel->name);
2508 // vertex buffer is several arrays and we put them in the same buffer
2510 // is this wise? the texcoordtexture2f array is used with dynamic
2511 // vertex/svector/tvector/normal when rendering animated models, on the
2512 // other hand animated models don't use a lot of vertices anyway...
2513 if (loadmodel->surfmesh.num_vertices)
2518 loadmodel->surfmesh.vbooffset_vertex3f = size;if (loadmodel->surfmesh.data_vertex3f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2519 loadmodel->surfmesh.vbooffset_svector3f = size;if (loadmodel->surfmesh.data_svector3f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2520 loadmodel->surfmesh.vbooffset_tvector3f = size;if (loadmodel->surfmesh.data_tvector3f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2521 loadmodel->surfmesh.vbooffset_normal3f = size;if (loadmodel->surfmesh.data_normal3f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2522 loadmodel->surfmesh.vbooffset_texcoordtexture2f = size;if (loadmodel->surfmesh.data_texcoordtexture2f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
2523 loadmodel->surfmesh.vbooffset_texcoordlightmap2f = size;if (loadmodel->surfmesh.data_texcoordlightmap2f) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
2524 loadmodel->surfmesh.vbooffset_lightmapcolor4f = size;if (loadmodel->surfmesh.data_lightmapcolor4f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[4]);
2525 mem = (unsigned char *)Mem_Alloc(tempmempool, size);
2526 if (loadmodel->surfmesh.data_vertex3f ) memcpy(mem + loadmodel->surfmesh.vbooffset_vertex3f , loadmodel->surfmesh.data_vertex3f , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2527 if (loadmodel->surfmesh.data_svector3f ) memcpy(mem + loadmodel->surfmesh.vbooffset_svector3f , loadmodel->surfmesh.data_svector3f , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2528 if (loadmodel->surfmesh.data_tvector3f ) memcpy(mem + loadmodel->surfmesh.vbooffset_tvector3f , loadmodel->surfmesh.data_tvector3f , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2529 if (loadmodel->surfmesh.data_normal3f ) memcpy(mem + loadmodel->surfmesh.vbooffset_normal3f , loadmodel->surfmesh.data_normal3f , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2530 if (loadmodel->surfmesh.data_texcoordtexture2f ) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordtexture2f , loadmodel->surfmesh.data_texcoordtexture2f , loadmodel->surfmesh.num_vertices * sizeof(float[2]));
2531 if (loadmodel->surfmesh.data_texcoordlightmap2f) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordlightmap2f, loadmodel->surfmesh.data_texcoordlightmap2f, loadmodel->surfmesh.num_vertices * sizeof(float[2]));
2532 if (loadmodel->surfmesh.data_lightmapcolor4f ) memcpy(mem + loadmodel->surfmesh.vbooffset_lightmapcolor4f , loadmodel->surfmesh.data_lightmapcolor4f , loadmodel->surfmesh.num_vertices * sizeof(float[4]));
2533 loadmodel->surfmesh.vbo = R_Mesh_CreateStaticBufferObject(GL_ARRAY_BUFFER_ARB, mem, size, loadmodel->name);
2538 static void Mod_Decompile_OBJ(dp_model_t *model, const char *filename, const char *mtlfilename, const char *originalfilename)
2540 int vertexindex, surfaceindex, triangleindex, textureindex, countvertices = 0, countsurfaces = 0, countfaces = 0, counttextures = 0;
2542 const char *texname;
2544 const float *v, *vn, *vt;
2546 size_t outbufferpos = 0;
2547 size_t outbuffermax = 0x100000;
2548 char *outbuffer = (char *) Z_Malloc(outbuffermax), *oldbuffer;
2549 const msurface_t *surface;
2550 const int maxtextures = 256;
2551 char *texturenames = (char *) Z_Malloc(maxtextures * MAX_QPATH);
2553 // construct the mtllib file
2554 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "# mtllib for %s exported by darkplaces engine\n", originalfilename);
2557 for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->num_surfaces;surfaceindex++, surface++)
2560 countvertices += surface->num_vertices;
2561 countfaces += surface->num_triangles;
2562 texname = (surface->texture && surface->texture->name[0]) ? surface->texture->name : "default";
2563 for (textureindex = 0;textureindex < counttextures;textureindex++)
2564 if (!strcmp(texturenames + textureindex * MAX_QPATH, texname))
2566 if (textureindex < counttextures)
2567 continue; // already wrote this material entry
2568 if (textureindex >= maxtextures)
2569 continue; // just a precaution
2570 textureindex = counttextures++;
2571 strlcpy(texturenames + textureindex * MAX_QPATH, texname, MAX_QPATH);
2572 if (outbufferpos >= outbuffermax >> 1)
2575 oldbuffer = outbuffer;
2576 outbuffer = (char *) Z_Malloc(outbuffermax);
2577 memcpy(outbuffer, oldbuffer, outbufferpos);
2580 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");
2585 // write the mtllib file
2586 FS_WriteFile(mtlfilename, outbuffer, outbufferpos);
2589 // construct the obj file
2590 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);
2593 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)
2595 if (outbufferpos >= outbuffermax >> 1)
2598 oldbuffer = outbuffer;
2599 outbuffer = (char *) Z_Malloc(outbuffermax);
2600 memcpy(outbuffer, oldbuffer, outbufferpos);
2603 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]);
2607 for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->num_surfaces;surfaceindex++, surface++)
2609 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "usemtl %s\n", (surface->texture && surface->texture->name[0]) ? surface->texture->name : "default");
2612 for (triangleindex = 0, e = model->surfmesh.data_element3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
2614 if (outbufferpos >= outbuffermax >> 1)
2617 oldbuffer = outbuffer;
2618 outbuffer = (char *) Z_Malloc(outbuffermax);
2619 memcpy(outbuffer, oldbuffer, outbufferpos);
2625 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);
2631 // write the obj file
2632 FS_WriteFile(filename, outbuffer, outbufferpos);
2636 Z_Free(texturenames);
2639 Con_Printf("Wrote %s (%i bytes, %i vertices, %i faces, %i surfaces with %i distinct textures)\n", filename, (int)outbufferpos, countvertices, countfaces, countsurfaces, counttextures);
2642 static void Mod_Decompile_SMD(dp_model_t *model, const char *filename, int firstpose, int numposes, qboolean writetriangles)
2644 int countnodes = 0, counttriangles = 0, countframes = 0;
2654 size_t outbufferpos = 0;
2655 size_t outbuffermax = 0x100000;
2656 char *outbuffer = (char *) Z_Malloc(outbuffermax), *oldbuffer;
2657 const msurface_t *surface;
2658 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "version 1\nnodes\n");
2662 if(model->num_poses >= 0)
2663 modelscale = sqrt(model->data_poses[0] * model->data_poses[0] + model->data_poses[1] * model->data_poses[1] + model->data_poses[2] * model->data_poses[2]);
2664 if(fabs(modelscale - 1) > 1e-4)
2666 if(firstpose == 0) // only print the when writing the reference pose
2667 Con_Printf("The model has an old-style model scale of %f\n", modelscale);
2671 for (transformindex = 0;transformindex < model->num_bones;transformindex++)
2673 if (outbufferpos >= outbuffermax >> 1)
2676 oldbuffer = outbuffer;
2677 outbuffer = (char *) Z_Malloc(outbuffermax);
2678 memcpy(outbuffer, oldbuffer, outbufferpos);
2682 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i \"%s\" %3i\n", transformindex, model->data_bones[transformindex].name, model->data_bones[transformindex].parent);
2686 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\nskeleton\n");
2689 for (poseindex = 0, pose = model->data_poses + model->num_bones * 12 * firstpose;poseindex < numposes;poseindex++)
2692 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "time %i\n", poseindex);
2695 for (transformindex = 0;transformindex < model->num_bones;transformindex++, pose += 12)
2700 if (outbufferpos >= outbuffermax >> 1)
2703 oldbuffer = outbuffer;
2704 outbuffer = (char *) Z_Malloc(outbuffermax);
2705 memcpy(outbuffer, oldbuffer, outbufferpos);
2709 // strangely the smd angles are for a transposed matrix, so we
2710 // have to generate a transposed matrix, then convert that...
2711 mtest[0][0] = pose[ 0];
2712 mtest[0][1] = pose[ 4];
2713 mtest[0][2] = pose[ 8];
2714 mtest[0][3] = pose[ 3];
2715 mtest[1][0] = pose[ 1];
2716 mtest[1][1] = pose[ 5];
2717 mtest[1][2] = pose[ 9];
2718 mtest[1][3] = pose[ 7];
2719 mtest[2][0] = pose[ 2];
2720 mtest[2][1] = pose[ 6];
2721 mtest[2][2] = pose[10];
2722 mtest[2][3] = pose[11];
2723 AnglesFromVectors(angles, mtest[0], mtest[2], false);
2724 if (angles[0] >= 180) angles[0] -= 360;
2725 if (angles[1] >= 180) angles[1] -= 360;
2726 if (angles[2] >= 180) angles[2] -= 360;
2728 a = DEG2RAD(angles[ROLL]);
2729 b = DEG2RAD(angles[PITCH]);
2730 c = DEG2RAD(angles[YAW]);
2734 float cy, sy, cp, sp, cr, sr;
2736 // smd matrix construction, for comparing to non-transposed m
2747 test[0][1] = sr*sp*cy+cr*-sy;
2748 test[1][1] = sr*sp*sy+cr*cy;
2750 test[0][2] = (cr*sp*cy+-sr*-sy);
2751 test[1][2] = (cr*sp*sy+-sr*cy);
2753 test[0][3] = pose[3];
2754 test[1][3] = pose[7];
2755 test[2][3] = pose[11];
2758 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f\n", transformindex, pose[3] * modelscale, pose[7] * modelscale, pose[11] * modelscale, DEG2RAD(angles[ROLL]), DEG2RAD(angles[PITCH]), DEG2RAD(angles[YAW]));
2763 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\n");
2768 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "triangles\n");
2771 for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->num_surfaces;surfaceindex++, surface++)
2773 for (triangleindex = 0, e = model->surfmesh.data_element3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
2776 if (outbufferpos >= outbuffermax >> 1)
2779 oldbuffer = outbuffer;
2780 outbuffer = (char *) Z_Malloc(outbuffermax);
2781 memcpy(outbuffer, oldbuffer, outbufferpos);
2784 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%s\n", surface->texture && surface->texture->name[0] ? surface->texture->name : "default.bmp");
2787 for (cornerindex = 0;cornerindex < 3;cornerindex++)
2789 const int index = e[2-cornerindex];
2790 const float *v = model->surfmesh.data_vertex3f + index * 3;
2791 const float *vn = model->surfmesh.data_normal3f + index * 3;
2792 const float *vt = model->surfmesh.data_texcoordtexture2f + index * 2;
2793 const int *wi = model->surfmesh.data_vertexweightindex4i + index * 4;
2794 const float *wf = model->surfmesh.data_vertexweightinfluence4f + index * 4;
2795 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], wi[1], wf[1], wi[2], wf[2], wi[3], wf[3]);
2796 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], wi[1], wf[1], wi[2], wf[2]);
2797 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], wi[1], wf[1]);
2798 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]);
2804 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\n");
2809 FS_WriteFile(filename, outbuffer, outbufferpos);
2812 Con_Printf("Wrote %s (%i bytes, %i nodes, %i frames, %i triangles)\n", filename, (int)outbufferpos, countnodes, countframes, counttriangles);
2819 decompiles a model to editable files
2822 static void Mod_Decompile_f(void)
2824 int i, j, k, l, first, count;
2826 char inname[MAX_QPATH];
2827 char outname[MAX_QPATH];
2828 char mtlname[MAX_QPATH];
2829 char basename[MAX_QPATH];
2830 char animname[MAX_QPATH];
2831 char animname2[MAX_QPATH];
2832 char zymtextbuffer[16384];
2833 char dpmtextbuffer[16384];
2834 int zymtextsize = 0;
2835 int dpmtextsize = 0;
2837 if (Cmd_Argc() != 2)
2839 Con_Print("usage: modeldecompile <filename>\n");
2843 strlcpy(inname, Cmd_Argv(1), sizeof(inname));
2844 FS_StripExtension(inname, basename, sizeof(basename));
2846 mod = Mod_ForName(inname, false, true, inname[0] == '*' ? cl.model_name[1] : NULL);
2847 if (mod->brush.submodel)
2849 // if we're decompiling a submodel, be sure to give it a proper name based on its parent
2850 FS_StripExtension(cl.model_name[1], outname, sizeof(outname));
2851 dpsnprintf(basename, sizeof(basename), "%s/%s", outname, mod->name);
2856 Con_Print("No such model\n");
2859 if (!mod->surfmesh.num_triangles)
2861 Con_Print("Empty model (or sprite)\n");
2865 // export OBJ if possible (not on sprites)
2866 if (mod->surfmesh.num_triangles)
2868 dpsnprintf(outname, sizeof(outname), "%s_decompiled.obj", basename);
2869 dpsnprintf(mtlname, sizeof(mtlname), "%s_decompiled.mtl", basename);
2870 Mod_Decompile_OBJ(mod, outname, mtlname, inname);
2873 // export SMD if possible (only for skeletal models)
2874 if (mod->surfmesh.num_triangles && mod->num_bones)
2876 dpsnprintf(outname, sizeof(outname), "%s_decompiled/ref1.smd", basename);
2877 Mod_Decompile_SMD(mod, outname, 0, 1, true);
2878 l = dpsnprintf(zymtextbuffer + zymtextsize, sizeof(zymtextbuffer) - zymtextsize, "output out.zym\nscale 1\norigin 0 0 0\nmesh ref1.smd\n");
2879 if (l > 0) zymtextsize += l;
2880 l = dpsnprintf(dpmtextbuffer + dpmtextsize, sizeof(dpmtextbuffer) - dpmtextsize, "outputdir .\nmodel out\nscale 1\norigin 0 0 0\nscene ref1.smd\n");
2881 if (l > 0) dpmtextsize += l;
2882 for (i = 0;i < mod->numframes;i = j)
2884 strlcpy(animname, mod->animscenes[i].name, sizeof(animname));
2885 first = mod->animscenes[i].firstframe;
2886 if (mod->animscenes[i].framecount > 1)
2889 count = mod->animscenes[i].framecount;
2895 // check for additional frames with same name
2896 for (l = 0, k = strlen(animname);animname[l];l++)
2897 if ((animname[l] < '0' || animname[l] > '9') && animname[l] != '_')
2900 count = mod->num_poses - first;
2901 for (j = i + 1;j < mod->numframes;j++)
2903 strlcpy(animname2, mod->animscenes[j].name, sizeof(animname2));
2904 for (l = 0, k = strlen(animname2);animname2[l];l++)
2905 if ((animname2[l] < '0' || animname2[l] > '9') && animname2[l] != '_')
2908 if (strcmp(animname2, animname) || mod->animscenes[j].framecount > 1)
2910 count = mod->animscenes[j].firstframe - first;
2914 // if it's only one frame, use the original frame name
2916 strlcpy(animname, mod->animscenes[i].name, sizeof(animname));
2919 dpsnprintf(outname, sizeof(outname), "%s_decompiled/%s.smd", basename, animname);
2920 Mod_Decompile_SMD(mod, outname, first, count, false);
2921 if (zymtextsize < (int)sizeof(zymtextbuffer) - 100)
2923 l = dpsnprintf(zymtextbuffer + zymtextsize, sizeof(zymtextbuffer) - zymtextsize, "scene %s.smd fps %g\n", animname, mod->animscenes[i].framerate);
2924 if (l > 0) zymtextsize += l;
2926 if (dpmtextsize < (int)sizeof(dpmtextbuffer) - 100)
2928 l = dpsnprintf(dpmtextbuffer + dpmtextsize, sizeof(dpmtextbuffer) - dpmtextsize, "scene %s.smd\n", animname);
2929 if (l > 0) dpmtextsize += l;
2933 FS_WriteFile(va("%s_decompiled/out_zym.txt", basename), zymtextbuffer, (fs_offset_t)zymtextsize);
2935 FS_WriteFile(va("%s_decompiled/out_dpm.txt", basename), dpmtextbuffer, (fs_offset_t)dpmtextsize);
2939 void Mod_AllocLightmap_Init(mod_alloclightmap_state_t *state, int width, int height)
2942 memset(state, 0, sizeof(*state));
2943 state->width = width;
2944 state->height = height;
2945 state->currentY = 0;
2946 state->rows = Mem_Alloc(tempmempool, state->height * sizeof(*state->rows));
2947 for (y = 0;y < state->height;y++)
2949 state->rows[y].currentX = 0;
2950 state->rows[y].rowY = -1;
2954 void Mod_AllocLightmap_Reset(mod_alloclightmap_state_t *state)
2957 state->currentY = 0;
2958 for (y = 0;y < state->height;y++)
2960 state->rows[y].currentX = 0;
2961 state->rows[y].rowY = -1;
2965 void Mod_AllocLightmap_Free(mod_alloclightmap_state_t *state)
2968 Mem_Free(state->rows);
2969 memset(state, 0, sizeof(*state));
2972 qboolean Mod_AllocLightmap_Block(mod_alloclightmap_state_t *state, int blockwidth, int blockheight, int *outx, int *outy)
2974 mod_alloclightmap_row_t *row;
2977 row = state->rows + blockheight;
2978 if ((row->rowY < 0) || (row->currentX + blockwidth > state->width))
2980 if (state->currentY + blockheight <= state->height)
2982 // use the current allocation position
2983 row->rowY = state->currentY;
2985 state->currentY += blockheight;
2989 // find another position
2990 for (y = blockheight;y < state->height;y++)
2992 if ((state->rows[y].rowY >= 0) && (state->rows[y].currentX + blockwidth <= state->width))
2994 row = state->rows + y;
2998 if (y == state->height)
3003 *outx = row->currentX;
3004 row->currentX += blockwidth;
3009 typedef struct lightmapsample_s
3013 float *vertex_color;
3014 unsigned char *lm_bgr;
3015 unsigned char *lm_dir;
3019 typedef struct lightmapvertex_s
3024 float texcoordbase[2];
3025 float texcoordlightmap[2];
3026 float lightcolor[4];
3030 typedef struct lightmaptriangle_s
3038 // 2D modelspace coordinates of min corner
3039 // snapped to lightmap grid but not in grid coordinates
3041 // 2D modelspace to lightmap coordinate scale
3049 typedef struct lightmaplight_s
3060 lightmaptriangle_t *mod_generatelightmaps_lightmaptriangles;
3062 #define MAX_LIGHTMAPSAMPLES 64
3063 static int mod_generatelightmaps_numoffsets[3];
3064 static float mod_generatelightmaps_offsets[3][MAX_LIGHTMAPSAMPLES][3];
3066 static int mod_generatelightmaps_numlights;
3067 static lightmaplight_t *mod_generatelightmaps_lightinfo;
3069 static void Mod_GenerateLightmaps_CreateLights_ComputeSVBSP_InsertSurfaces(const dp_model_t *model, svbsp_t *svbsp, const float *mins, const float *maxs)
3073 const msurface_t *surface;
3074 const float *vertex3f = model->surfmesh.data_vertex3f;
3075 const int *element3i = model->surfmesh.data_element3i;
3078 for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->nummodelsurfaces;surfaceindex++, surface++)
3080 if (!BoxesOverlap(surface->mins, surface->maxs, mins, maxs))
3082 if (R_GetCurrentTexture(surface->texture)->currentmaterialflags & MATERIALFLAG_NOSHADOW)
3084 for (triangleindex = 0, e = element3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
3086 VectorCopy(vertex3f + 3*e[0], v2[0]);
3087 VectorCopy(vertex3f + 3*e[1], v2[1]);
3088 VectorCopy(vertex3f + 3*e[2], v2[2]);
3089 SVBSP_AddPolygon(svbsp, 3, v2[0], true, NULL, NULL, 0);
3094 static void Mod_GenerateLightmaps_CreateLights_ComputeSVBSP(dp_model_t *model, lightmaplight_t *lightinfo)
3096 int maxnodes = 1<<14;
3097 svbsp_node_t *nodes;
3102 VectorSet(mins, lightinfo->origin[0] - lightinfo->radius, lightinfo->origin[1] - lightinfo->radius, lightinfo->origin[2] - lightinfo->radius);
3103 VectorSet(maxs, lightinfo->origin[0] + lightinfo->radius, lightinfo->origin[1] + lightinfo->radius, lightinfo->origin[2] + lightinfo->radius);
3104 VectorCopy(lightinfo->origin, origin);
3105 nodes = Mem_Alloc(tempmempool, maxnodes * sizeof(*nodes));
3108 SVBSP_Init(&svbsp, origin, maxnodes, nodes);
3109 Mod_GenerateLightmaps_CreateLights_ComputeSVBSP_InsertSurfaces(model, &svbsp, mins, maxs);
3110 if (svbsp.ranoutofnodes)
3113 if (maxnodes >= 1<<22)
3119 nodes = Mem_Alloc(tempmempool, maxnodes * sizeof(*nodes));
3124 if (svbsp.numnodes > 0)
3126 svbsp.nodes = Mem_Alloc(tempmempool, svbsp.numnodes * sizeof(*nodes));
3127 memcpy(svbsp.nodes, nodes, svbsp.numnodes * sizeof(*nodes));
3128 lightinfo->svbsp = svbsp;
3133 extern int R_Shadow_GetRTLightInfo(unsigned int lightindex, float *origin, float *radius, float *color);
3134 static void Mod_GenerateLightmaps_CreateLights(dp_model_t *model)
3138 lightmaplight_t *lightinfo;
3142 mod_generatelightmaps_numlights = 0;
3143 for (index = 0;;index++)
3145 result = R_Shadow_GetRTLightInfo(index, origin, &radius, color);
3149 mod_generatelightmaps_numlights++;
3151 if (mod_generatelightmaps_numlights > 0)
3153 mod_generatelightmaps_lightinfo = Mem_Alloc(tempmempool, mod_generatelightmaps_numlights * sizeof(*mod_generatelightmaps_lightinfo));
3154 lightinfo = mod_generatelightmaps_lightinfo;
3155 for (index = 0;;index++)
3157 result = R_Shadow_GetRTLightInfo(index, lightinfo->origin, &lightinfo->radius, lightinfo->color);
3164 for (index = 0, lightinfo = mod_generatelightmaps_lightinfo;index < mod_generatelightmaps_numlights;index++, lightinfo++)
3166 lightinfo->iradius = 1.0f / lightinfo->radius;
3167 lightinfo->radius2 = lightinfo->radius * lightinfo->radius;
3168 // TODO: compute svbsp
3169 Mod_GenerateLightmaps_CreateLights_ComputeSVBSP(model, lightinfo);
3173 static void Mod_GenerateLightmaps_DestroyLights(dp_model_t *model)
3176 if (mod_generatelightmaps_lightinfo)
3178 for (i = 0;i < mod_generatelightmaps_numlights;i++)
3179 if (mod_generatelightmaps_lightinfo[i].svbsp.nodes)
3180 Mem_Free(mod_generatelightmaps_lightinfo[i].svbsp.nodes);
3181 Mem_Free(mod_generatelightmaps_lightinfo);
3183 mod_generatelightmaps_lightinfo = NULL;
3184 mod_generatelightmaps_numlights = 0;
3187 static qboolean Mod_GenerateLightmaps_SamplePoint_SVBSP(const svbsp_t *svbsp, const float *pos)
3189 const svbsp_node_t *node;
3190 const svbsp_node_t *nodes = svbsp->nodes;
3195 num = node->children[DotProduct(node->plane, pos) < node->plane[3]];
3197 return num == -1; // true if empty, false if solid (shadowed)
3200 extern cvar_t r_shadow_lightattenuationdividebias;
3201 extern cvar_t r_shadow_lightattenuationlinearscale;
3202 static void Mod_GenerateLightmaps_SamplePoint(const float *pos, const float *normal, float *sample, int numoffsets, const float *offsets)
3205 float relativepoint[3];
3214 const lightmaplight_t *lightinfo;
3216 for (i = 0;i < 5*3;i++)
3218 for (i = 0, lightinfo = mod_generatelightmaps_lightinfo;i < mod_generatelightmaps_numlights;i++, lightinfo++)
3220 //R_SampleRTLights(pos, sample, numoffsets, offsets);
3221 VectorSubtract(lightinfo->origin, pos, relativepoint);
3222 // don't accept light from behind a surface, it causes bad shading
3223 if (normal && DotProduct(relativepoint, normal) <= 0)
3225 dist2 = VectorLength2(relativepoint);
3226 if (dist2 >= lightinfo->radius2)
3228 dist = sqrt(dist2) * lightinfo->iradius;
3229 intensity = dist < 1 ? ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) : 0;
3232 if (cl.worldmodel && cl.worldmodel->TraceLine && numoffsets > 0)
3236 if (Mod_GenerateLightmaps_SamplePoint_SVBSP(&lightinfo->svbsp, pos))
3238 for (offsetindex = 1;offsetindex < numoffsets;offsetindex++)
3240 VectorAdd(pos, offsets + 3*offsetindex, offsetpos);
3243 // for light grid we'd better check visibility of the offset point
3244 cl.worldmodel->TraceLine(cl.worldmodel, NULL, NULL, &trace, pos, offsetpos, SUPERCONTENTS_VISBLOCKERMASK);
3245 if (trace.fraction < 1)
3246 VectorLerp(pos, trace.fraction, offsetpos, offsetpos);
3249 if (Mod_GenerateLightmaps_SamplePoint_SVBSP(&lightinfo->svbsp, offsetpos))
3254 // scale intensity according to how many rays succeeded
3255 // we know one test is valid, half of the rest will fail...
3256 //if (normal && tests > 1)
3257 // intensity *= (tests - 1.0f) / tests;
3258 intensity *= (float)hits / tests;
3260 // scale down intensity to add to both ambient and diffuse
3261 //intensity *= 0.5f;
3262 VectorNormalize(relativepoint);
3263 VectorScale(lightinfo->color, intensity, color);
3264 VectorMA(sample , 0.5f , color, sample );
3265 VectorMA(sample + 3, relativepoint[0], color, sample + 3);
3266 VectorMA(sample + 6, relativepoint[1], color, sample + 6);
3267 VectorMA(sample + 9, relativepoint[2], color, sample + 9);
3268 // calculate a weighted average light direction as well
3269 intensity *= VectorLength(color);
3270 VectorMA(sample + 12, intensity, relativepoint, sample + 12);
3274 static void Mod_GenerateLightmaps_LightmapSample(const float *pos, const float *normal, unsigned char *lm_bgr, unsigned char *lm_dir)
3280 Mod_GenerateLightmaps_SamplePoint(pos, normal, sample, mod_generatelightmaps_numoffsets[0], mod_generatelightmaps_offsets[0][0]);
3281 //VectorSet(dir, sample[3] + sample[4] + sample[5], sample[6] + sample[7] + sample[8], sample[9] + sample[10] + sample[11]);
3282 VectorCopy(sample + 12, dir);
3283 VectorNormalize(dir);
3284 //VectorAdd(dir, normal, dir);
3285 //VectorNormalize(dir);
3286 f = DotProduct(dir, normal);
3287 f = max(0, f) * 255.0f;
3288 VectorScale(sample, f, color);
3289 //VectorCopy(normal, dir);
3290 VectorSet(dir, (dir[0]+1.0f)*127.5f, (dir[1]+1.0f)*127.5f, (dir[2]+1.0f)*127.5f);
3291 lm_bgr[0] = (unsigned char)bound(0.0f, color[2], 255.0f);
3292 lm_bgr[1] = (unsigned char)bound(0.0f, color[1], 255.0f);
3293 lm_bgr[2] = (unsigned char)bound(0.0f, color[0], 255.0f);
3295 lm_dir[0] = (unsigned char)dir[2];
3296 lm_dir[1] = (unsigned char)dir[1];
3297 lm_dir[2] = (unsigned char)dir[0];
3301 static void Mod_GenerateLightmaps_VertexSample(const float *pos, const float *normal, float *vertex_color)
3304 Mod_GenerateLightmaps_SamplePoint(pos, normal, sample, mod_generatelightmaps_numoffsets[1], mod_generatelightmaps_offsets[1][0]);
3305 VectorCopy(sample, vertex_color);
3308 static void Mod_GenerateLightmaps_GridSample(const float *pos, q3dlightgrid_t *s)
3314 Mod_GenerateLightmaps_SamplePoint(pos, NULL, sample, mod_generatelightmaps_numoffsets[2], mod_generatelightmaps_offsets[2][0]);
3315 // calculate the direction we'll use to reduce the sample to a directional light source
3316 VectorCopy(sample + 12, dir);
3317 //VectorSet(dir, sample[3] + sample[4] + sample[5], sample[6] + sample[7] + sample[8], sample[9] + sample[10] + sample[11]);
3318 VectorNormalize(dir);
3319 // extract the diffuse color along the chosen direction and scale it
3320 diffuse[0] = (dir[0]*sample[3] + dir[1]*sample[6] + dir[2]*sample[ 9] + sample[ 0]) * 127.5f;
3321 diffuse[1] = (dir[0]*sample[4] + dir[1]*sample[7] + dir[2]*sample[10] + sample[ 1]) * 127.5f;
3322 diffuse[2] = (dir[0]*sample[5] + dir[1]*sample[8] + dir[2]*sample[11] + sample[ 2]) * 127.5f;
3323 // scale the ambient from 0-2 to 0-255 and subtract some of diffuse
3324 VectorScale(sample, 127.5f, ambient);
3325 VectorMA(ambient, -0.333f, diffuse, ambient);
3326 // encode to the grid format
3327 s->ambientrgb[0] = (unsigned char)bound(0.0f, ambient[0], 255.0f);
3328 s->ambientrgb[1] = (unsigned char)bound(0.0f, ambient[1], 255.0f);
3329 s->ambientrgb[2] = (unsigned char)bound(0.0f, ambient[2], 255.0f);
3330 s->diffusergb[0] = (unsigned char)bound(0.0f, diffuse[0], 255.0f);
3331 s->diffusergb[1] = (unsigned char)bound(0.0f, diffuse[1], 255.0f);
3332 s->diffusergb[2] = (unsigned char)bound(0.0f, diffuse[2], 255.0f);
3333 if (dir[2] >= 0.99f) {s->diffusepitch = 0;s->diffuseyaw = 0;}
3334 else if (dir[2] <= -0.99f) {s->diffusepitch = 128;s->diffuseyaw = 0;}
3335 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));}
3338 static void Mod_GenerateLightmaps_InitSampleOffsets(dp_model_t *model)
3343 memset(mod_generatelightmaps_offsets, 0, sizeof(mod_generatelightmaps_offsets));
3344 mod_generatelightmaps_numoffsets[0] = min(MAX_LIGHTMAPSAMPLES, mod_generatelightmaps_lightmapsamples.integer);
3345 mod_generatelightmaps_numoffsets[1] = min(MAX_LIGHTMAPSAMPLES, mod_generatelightmaps_vertexsamples.integer);
3346 mod_generatelightmaps_numoffsets[2] = min(MAX_LIGHTMAPSAMPLES, mod_generatelightmaps_gridsamples.integer);
3347 radius[0] = mod_generatelightmaps_lightmapradius.value;
3348 radius[1] = mod_generatelightmaps_vertexradius.value;
3349 radius[2] = mod_generatelightmaps_gridradius.value;
3350 for (i = 0;i < 3;i++)
3352 for (j = 1;j < mod_generatelightmaps_numoffsets[i];j++)
3355 VectorScale(temp, radius[i], mod_generatelightmaps_offsets[i][j]);
3360 static void Mod_GenerateLightmaps_DestroyLightmaps(dp_model_t *model)
3362 msurface_t *surface;
3365 for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3367 surface = model->data_surfaces + surfaceindex;
3368 surface->lightmaptexture = NULL;
3369 surface->deluxemaptexture = NULL;
3371 if (model->brushq3.data_lightmaps)
3373 for (i = 0;i < model->brushq3.num_mergedlightmaps;i++)
3374 R_FreeTexture(model->brushq3.data_lightmaps[i]);
3375 Mem_Free(model->brushq3.data_lightmaps);
3376 model->brushq3.data_lightmaps = NULL;
3378 if (model->brushq3.data_deluxemaps)
3380 for (i = 0;i < model->brushq3.num_mergedlightmaps;i++)
3381 R_FreeTexture(model->brushq3.data_deluxemaps[i]);
3382 Mem_Free(model->brushq3.data_deluxemaps);
3383 model->brushq3.data_deluxemaps = NULL;
3387 static void Mod_GenerateLightmaps_UnweldTriangles(dp_model_t *model)
3389 msurface_t *surface;
3395 surfmesh_t oldsurfmesh;
3397 unsigned char *data;
3398 oldsurfmesh = model->surfmesh;
3399 model->surfmesh.num_triangles = oldsurfmesh.num_triangles;
3400 model->surfmesh.num_vertices = oldsurfmesh.num_triangles * 3;
3402 size += model->surfmesh.num_vertices * sizeof(float[3]);
3403 size += model->surfmesh.num_vertices * sizeof(float[3]);
3404 size += model->surfmesh.num_vertices * sizeof(float[3]);
3405 size += model->surfmesh.num_vertices * sizeof(float[3]);
3406 size += model->surfmesh.num_vertices * sizeof(float[2]);
3407 size += model->surfmesh.num_vertices * sizeof(float[2]);
3408 size += model->surfmesh.num_vertices * sizeof(float[4]);
3409 data = (unsigned char *)Mem_Alloc(model->mempool, size);
3410 model->surfmesh.data_vertex3f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[3]);
3411 model->surfmesh.data_normal3f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[3]);
3412 model->surfmesh.data_svector3f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[3]);
3413 model->surfmesh.data_tvector3f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[3]);
3414 model->surfmesh.data_texcoordtexture2f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[2]);
3415 model->surfmesh.data_texcoordlightmap2f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[2]);
3416 model->surfmesh.data_lightmapcolor4f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[4]);
3417 if (model->surfmesh.num_vertices > 65536)
3418 model->surfmesh.data_element3s = NULL;
3420 if (model->surfmesh.vbo)
3421 R_Mesh_DestroyBufferObject(model->surfmesh.vbo);
3422 model->surfmesh.vbo = 0;
3423 if (model->surfmesh.ebo3i)
3424 R_Mesh_DestroyBufferObject(model->surfmesh.ebo3i);
3425 model->surfmesh.ebo3i = 0;
3426 if (model->surfmesh.ebo3s)
3427 R_Mesh_DestroyBufferObject(model->surfmesh.ebo3s);
3428 model->surfmesh.ebo3s = 0;
3430 // convert all triangles to unique vertex data
3432 for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3434 surface = model->data_surfaces + surfaceindex;
3435 surface->num_firstvertex = outvertexindex;
3436 surface->num_vertices = surface->num_triangles*3;
3437 e = oldsurfmesh.data_element3i + surface->num_firsttriangle*3;
3438 for (i = 0;i < surface->num_triangles*3;i++)
3441 model->surfmesh.data_vertex3f[outvertexindex*3+0] = oldsurfmesh.data_vertex3f[vertexindex*3+0];
3442 model->surfmesh.data_vertex3f[outvertexindex*3+1] = oldsurfmesh.data_vertex3f[vertexindex*3+1];
3443 model->surfmesh.data_vertex3f[outvertexindex*3+2] = oldsurfmesh.data_vertex3f[vertexindex*3+2];
3444 model->surfmesh.data_normal3f[outvertexindex*3+0] = oldsurfmesh.data_normal3f[vertexindex*3+0];
3445 model->surfmesh.data_normal3f[outvertexindex*3+1] = oldsurfmesh.data_normal3f[vertexindex*3+1];
3446 model->surfmesh.data_normal3f[outvertexindex*3+2] = oldsurfmesh.data_normal3f[vertexindex*3+2];
3447 model->surfmesh.data_svector3f[outvertexindex*3+0] = oldsurfmesh.data_svector3f[vertexindex*3+0];
3448 model->surfmesh.data_svector3f[outvertexindex*3+1] = oldsurfmesh.data_svector3f[vertexindex*3+1];
3449 model->surfmesh.data_svector3f[outvertexindex*3+2] = oldsurfmesh.data_svector3f[vertexindex*3+2];
3450 model->surfmesh.data_tvector3f[outvertexindex*3+0] = oldsurfmesh.data_tvector3f[vertexindex*3+0];
3451 model->surfmesh.data_tvector3f[outvertexindex*3+1] = oldsurfmesh.data_tvector3f[vertexindex*3+1];
3452 model->surfmesh.data_tvector3f[outvertexindex*3+2] = oldsurfmesh.data_tvector3f[vertexindex*3+2];
3453 model->surfmesh.data_texcoordtexture2f[outvertexindex*2+0] = oldsurfmesh.data_texcoordtexture2f[vertexindex*2+0];
3454 model->surfmesh.data_texcoordtexture2f[outvertexindex*2+1] = oldsurfmesh.data_texcoordtexture2f[vertexindex*2+1];
3455 model->surfmesh.data_texcoordlightmap2f[outvertexindex*2+0] = oldsurfmesh.data_texcoordlightmap2f[vertexindex*2+0];
3456 model->surfmesh.data_texcoordlightmap2f[outvertexindex*2+1] = oldsurfmesh.data_texcoordlightmap2f[vertexindex*2+1];
3457 model->surfmesh.data_lightmapcolor4f[outvertexindex*4+0] = oldsurfmesh.data_lightmapcolor4f[vertexindex*4+0];
3458 model->surfmesh.data_lightmapcolor4f[outvertexindex*4+1] = oldsurfmesh.data_lightmapcolor4f[vertexindex*4+1];
3459 model->surfmesh.data_lightmapcolor4f[outvertexindex*4+2] = oldsurfmesh.data_lightmapcolor4f[vertexindex*4+2];
3460 model->surfmesh.data_lightmapcolor4f[outvertexindex*4+3] = oldsurfmesh.data_lightmapcolor4f[vertexindex*4+3];
3461 model->surfmesh.data_element3i[surface->num_firsttriangle*3+i] = outvertexindex;
3465 if (model->surfmesh.data_element3s)
3466 for (i = 0;i < model->surfmesh.num_triangles*3;i++)
3467 model->surfmesh.data_element3s[i] = model->surfmesh.data_element3i[i];
3469 // find and update all submodels to use this new surfmesh data
3470 for (i = 0;i < model->brush.numsubmodels;i++)
3471 model->brush.submodels[i]->surfmesh = model->surfmesh;
3474 static void Mod_GenerateLightmaps_CreateTriangleInformation(dp_model_t *model)
3476 msurface_t *surface;
3482 lightmaptriangle_t *triangle;
3483 // generate lightmap triangle structs
3484 mod_generatelightmaps_lightmaptriangles = Mem_Alloc(model->mempool, model->surfmesh.num_triangles * sizeof(lightmaptriangle_t));
3485 for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3487 surface = model->data_surfaces + surfaceindex;
3488 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
3489 for (i = 0;i < surface->num_triangles;i++)
3491 triangle = &mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle+i];
3492 triangle->triangleindex = surface->num_firsttriangle+i;
3493 triangle->surfaceindex = surfaceindex;
3494 VectorCopy(model->surfmesh.data_vertex3f + 3*e[i*3+0], triangle->vertex[0]);
3495 VectorCopy(model->surfmesh.data_vertex3f + 3*e[i*3+1], triangle->vertex[1]);
3496 VectorCopy(model->surfmesh.data_vertex3f + 3*e[i*3+2], triangle->vertex[2]);
3497 // calculate bounds of triangle
3498 triangle->mins[0] = min(triangle->vertex[0][0], min(triangle->vertex[1][0], triangle->vertex[2][0]));
3499 triangle->mins[1] = min(triangle->vertex[0][1], min(triangle->vertex[1][1], triangle->vertex[2][1]));
3500 triangle->mins[2] = min(triangle->vertex[0][2], min(triangle->vertex[1][2], triangle->vertex[2][2]));
3501 triangle->maxs[0] = max(triangle->vertex[0][0], max(triangle->vertex[1][0], triangle->vertex[2][0]));
3502 triangle->maxs[1] = max(triangle->vertex[0][1], max(triangle->vertex[1][1], triangle->vertex[2][1]));
3503 triangle->maxs[2] = max(triangle->vertex[0][2], max(triangle->vertex[1][2], triangle->vertex[2][2]));
3504 // pick an axial projection based on the triangle normal
3505 TriangleNormal(triangle->vertex[0], triangle->vertex[1], triangle->vertex[2], normal);
3507 if (fabs(normal[1]) > fabs(normal[axis]))
3509 if (fabs(normal[2]) > fabs(normal[axis]))
3511 triangle->axis = axis;
3516 static void Mod_GenerateLightmaps_DestroyTriangleInformation(dp_model_t *model)
3518 if (mod_generatelightmaps_lightmaptriangles)
3519 Mem_Free(mod_generatelightmaps_lightmaptriangles);
3520 mod_generatelightmaps_lightmaptriangles = NULL;
3523 float lmaxis[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
3525 static void Mod_GenerateLightmaps_CreateLightmaps(dp_model_t *model)
3527 msurface_t *surface;
3541 float trianglenormal[3];
3542 float samplecenter[3];
3543 float samplenormal[3];
3549 float lmscalepixels;
3552 float lm_basescalepixels;
3553 int lm_borderpixels;
3557 lightmaptriangle_t *triangle;
3558 unsigned char *lightmappixels;
3559 unsigned char *deluxemappixels;
3560 mod_alloclightmap_state_t lmstate;
3562 // generate lightmap projection information for all triangles
3563 if (model->texturepool == NULL)
3564 model->texturepool = R_AllocTexturePool();
3565 lm_basescalepixels = 1.0f / max(0.0001f, mod_generatelightmaps_unitspersample.value);
3566 lm_borderpixels = mod_generatelightmaps_borderpixels.integer;
3567 lm_texturesize = bound(lm_borderpixels*2+1, 64, gl_max_texture_size);
3568 lm_maxpixels = lm_texturesize-(lm_borderpixels*2+1);
3569 Mod_AllocLightmap_Init(&lmstate, lm_texturesize, lm_texturesize);
3571 for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3573 surface = model->data_surfaces + surfaceindex;
3574 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
3575 lmscalepixels = lm_basescalepixels;
3576 for (retry = 0;retry < 30;retry++)
3578 // after a couple failed attempts, degrade quality to make it fit
3580 lmscalepixels *= 0.5f;
3581 for (i = 0;i < surface->num_triangles;i++)
3583 triangle = &mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle+i];
3584 triangle->lightmapindex = lightmapnumber;
3585 // calculate lightmap bounds in 3D pixel coordinates, limit size,
3586 // pick two planar axes for projection
3587 // lightmap coordinates here are in pixels
3588 // lightmap projections are snapped to pixel grid explicitly, such
3589 // that two neighboring triangles sharing an edge and projection
3590 // axis will have identical sampl espacing along their shared edge
3592 for (j = 0;j < 3;j++)
3594 if (j == triangle->axis)
3596 lmmins = floor(triangle->mins[j]*lmscalepixels)-lm_borderpixels;
3597 lmmaxs = floor(triangle->maxs[j]*lmscalepixels)+lm_borderpixels;
3598 triangle->lmsize[k] = (int)(lmmaxs-lmmins);
3599 triangle->lmbase[k] = lmmins/lmscalepixels;
3600 triangle->lmscale[k] = lmscalepixels;
3603 if (!Mod_AllocLightmap_Block(&lmstate, triangle->lmsize[0], triangle->lmsize[1], &triangle->lmoffset[0], &triangle->lmoffset[1]))
3606 // if all fit in this texture, we're done with this surface
3607 if (i == surface->num_triangles)
3609 // if we haven't maxed out the lightmap size yet, we retry the
3610 // entire surface batch...
3611 if (lm_texturesize * 2 <= min(mod_generatelightmaps_texturesize.integer, gl_max_texture_size))
3613 lm_texturesize *= 2;
3616 Mod_AllocLightmap_Free(&lmstate);
3617 Mod_AllocLightmap_Init(&lmstate, lm_texturesize, lm_texturesize);
3620 // if we have maxed out the lightmap size, and this triangle does
3621 // not fit in the same texture as the rest of the surface, we have
3622 // to retry the entire surface in a new texture (can only use one)
3623 // with multiple retries, the lightmap quality degrades until it
3624 // fits (or gives up)
3625 if (surfaceindex > 0)
3627 Mod_AllocLightmap_Reset(&lmstate);
3631 Mod_AllocLightmap_Free(&lmstate);
3633 // now together lightmap textures
3634 model->brushq3.deluxemapping_modelspace = true;
3635 model->brushq3.deluxemapping = true;
3636 model->brushq3.num_mergedlightmaps = lightmapnumber;
3637 model->brushq3.data_lightmaps = Mem_Alloc(model->mempool, model->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
3638 model->brushq3.data_deluxemaps = Mem_Alloc(model->mempool, model->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
3639 lightmappixels = Mem_Alloc(tempmempool, model->brushq3.num_mergedlightmaps * lm_texturesize * lm_texturesize * 4);
3640 deluxemappixels = Mem_Alloc(tempmempool, model->brushq3.num_mergedlightmaps * lm_texturesize * lm_texturesize * 4);
3641 for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3643 surface = model->data_surfaces + surfaceindex;
3644 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
3645 for (i = 0;i < surface->num_triangles;i++)
3647 triangle = &mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle+i];
3648 TriangleNormal(triangle->vertex[0], triangle->vertex[1], triangle->vertex[2], trianglenormal);
3649 VectorNormalize(trianglenormal);
3650 VectorCopy(trianglenormal, samplenormal); // FIXME: this is supposed to be interpolated per pixel from vertices
3651 axis = triangle->axis;
3652 axis1 = axis == 0 ? 1 : 0;
3653 axis2 = axis == 2 ? 1 : 2;
3654 lmiscale[0] = 1.0f / triangle->lmscale[0];
3655 lmiscale[1] = 1.0f / triangle->lmscale[1];
3656 if (trianglenormal[axis] < 0)
3657 VectorNegate(trianglenormal, trianglenormal);
3658 CrossProduct(lmaxis[axis2], trianglenormal, temp);slopex = temp[axis] / temp[axis1];
3659 CrossProduct(lmaxis[axis1], trianglenormal, temp);slopey = temp[axis] / temp[axis2];
3660 slopebase = triangle->vertex[0][axis] - triangle->vertex[0][axis1]*slopex - triangle->vertex[0][axis2]*slopey;
3661 for (j = 0;j < 3;j++)
3663 float *t2f = model->surfmesh.data_texcoordlightmap2f + e[i*3+j]*2;
3664 t2f[0] = ((triangle->vertex[j][axis1] - triangle->lmbase[0]) * triangle->lmscale[0] + triangle->lmoffset[0]) / lm_texturesize;
3665 t2f[1] = ((triangle->vertex[j][axis2] - triangle->lmbase[1]) * triangle->lmscale[1] + triangle->lmoffset[1]) / lm_texturesize;
3667 samplecenter[axis1] = (t2f[0]*lm_texturesize-triangle->lmoffset[0])*lmiscale[0] + triangle->lmbase[0];
3668 samplecenter[axis2] = (t2f[1]*lm_texturesize-triangle->lmoffset[1])*lmiscale[1] + triangle->lmbase[1];
3669 samplecenter[axis] = samplecenter[axis1]*slopex + samplecenter[axis2]*slopey + slopebase;
3670 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]);
3680 forward[1] = 1.0f / triangle->lmscale[0];
3684 left[2] = 1.0f / triangle->lmscale[1];
3689 origin[1] = triangle->lmbase[0];
3690 origin[2] = triangle->lmbase[1];
3693 forward[0] = 1.0f / triangle->lmscale[0];
3698 left[2] = 1.0f / triangle->lmscale[1];
3702 origin[0] = triangle->lmbase[0];
3704 origin[2] = triangle->lmbase[1];
3707 forward[0] = 1.0f / triangle->lmscale[0];
3711 left[1] = 1.0f / triangle->lmscale[1];
3716 origin[0] = triangle->lmbase[0];
3717 origin[1] = triangle->lmbase[1];
3721 Matrix4x4_FromVectors(&backmatrix, forward, left, up, origin);
3723 #define LM_DIST_EPSILON (1.0f / 32.0f)
3724 for (y = 0;y < triangle->lmsize[1];y++)
3726 pixeloffset = ((triangle->lightmapindex * lm_texturesize + y + triangle->lmoffset[1]) * lm_texturesize + triangle->lmoffset[0]) * 4;
3727 for (x = 0;x < triangle->lmsize[0];x++, pixeloffset += 4)
3729 samplecenter[axis1] = (x+0.5f)*lmiscale[0] + triangle->lmbase[0];
3730 samplecenter[axis2] = (y+0.5f)*lmiscale[1] + triangle->lmbase[1];
3731 samplecenter[axis] = samplecenter[axis1]*slopex + samplecenter[axis2]*slopey + slopebase;
3732 VectorMA(samplecenter, 0.125f, samplenormal, samplecenter);
3733 Mod_GenerateLightmaps_LightmapSample(samplecenter, samplenormal, lightmappixels + pixeloffset, deluxemappixels + pixeloffset);
3739 for (lightmapindex = 0;lightmapindex < model->brushq3.num_mergedlightmaps;lightmapindex++)
3741 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 | TEXF_PRECACHE, NULL);
3742 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 | TEXF_PRECACHE, NULL);
3746 Mem_Free(lightmappixels);
3747 if (deluxemappixels)
3748 Mem_Free(deluxemappixels);
3750 for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3752 surface = model->data_surfaces + surfaceindex;
3753 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
3754 if (!surface->num_triangles)
3756 lightmapindex = mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle].lightmapindex;
3757 surface->lightmaptexture = model->brushq3.data_lightmaps[lightmapindex];
3758 surface->deluxemaptexture = model->brushq3.data_deluxemaps[lightmapindex];
3762 static void Mod_GenerateLightmaps_UpdateVertexColors(dp_model_t *model)
3765 for (i = 0;i < model->surfmesh.num_vertices;i++)
3766 Mod_GenerateLightmaps_VertexSample(model->surfmesh.data_vertex3f + 3*i, model->surfmesh.data_normal3f + 3*i, model->surfmesh.data_lightmapcolor4f + 4*i);
3769 static void Mod_GenerateLightmaps_UpdateLightGrid(dp_model_t *model)
3776 for (z = 0;z < model->brushq3.num_lightgrid_isize[2];z++)
3778 pos[2] = (model->brushq3.num_lightgrid_imins[2] + z + 0.5f) * model->brushq3.num_lightgrid_cellsize[2];
3779 for (y = 0;y < model->brushq3.num_lightgrid_isize[1];y++)
3781 pos[1] = (model->brushq3.num_lightgrid_imins[1] + y + 0.5f) * model->brushq3.num_lightgrid_cellsize[1];
3782 for (x = 0;x < model->brushq3.num_lightgrid_isize[0];x++, index++)
3784 pos[0] = (model->brushq3.num_lightgrid_imins[0] + x + 0.5f) * model->brushq3.num_lightgrid_cellsize[0];
3785 Mod_GenerateLightmaps_GridSample(pos, model->brushq3.data_lightgrid + index);
3791 extern cvar_t mod_q3bsp_nolightmaps;
3792 static void Mod_GenerateLightmaps(dp_model_t *model)
3794 //lightmaptriangle_t *lightmaptriangles = Mem_Alloc(model->mempool, model->surfmesh.num_triangles * sizeof(lightmaptriangle_t));
3795 dp_model_t *oldloadmodel = loadmodel;
3798 Mod_GenerateLightmaps_InitSampleOffsets(model);
3799 Mod_GenerateLightmaps_DestroyLightmaps(model);
3800 Mod_GenerateLightmaps_UnweldTriangles(model);
3801 Mod_GenerateLightmaps_CreateTriangleInformation(model);
3802 Mod_GenerateLightmaps_CreateLights(model);
3803 if(!mod_q3bsp_nolightmaps.integer)
3804 Mod_GenerateLightmaps_CreateLightmaps(model);
3805 Mod_GenerateLightmaps_UpdateVertexColors(model);
3806 Mod_GenerateLightmaps_UpdateLightGrid(model);
3807 Mod_GenerateLightmaps_DestroyLights(model);
3808 Mod_GenerateLightmaps_DestroyTriangleInformation(model);
3810 loadmodel = oldloadmodel;
3813 static void Mod_GenerateLightmaps_f(void)
3815 if (Cmd_Argc() != 1)
3817 Con_Printf("usage: mod_generatelightmaps\n");
3822 Con_Printf("no worldmodel loaded\n");
3825 Mod_GenerateLightmaps(cl.worldmodel);