OgreImporter.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  1. //
  2. // Copyright (c) 2008-2020 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include <Urho3D/Core/Context.h>
  23. #include <Urho3D/Core/ProcessUtils.h>
  24. #include <Urho3D/Core/StringUtils.h>
  25. #include <Urho3D/Graphics/Tangent.h>
  26. #include <Urho3D/IO/File.h>
  27. #include <Urho3D/IO/FileSystem.h>
  28. #include <Urho3D/Resource/XMLFile.h>
  29. #include "OgreImporterUtils.h"
  30. #ifdef WIN32
  31. #include <windows.h>
  32. #endif
  33. #include <Urho3D/DebugNew.h>
  34. static const int VERTEX_CACHE_SIZE = 32;
  35. SharedPtr<Context> context_(new Context());
  36. SharedPtr<XMLFile> meshFile_(new XMLFile(context_));
  37. SharedPtr<XMLFile> skelFile_(new XMLFile(context_));
  38. Vector<ModelIndexBuffer> indexBuffers_;
  39. Vector<ModelVertexBuffer> vertexBuffers_;
  40. Vector<Vector<ModelSubGeometryLodLevel> > subGeometries_;
  41. Vector<Vector3> subGeometryCenters_;
  42. Vector<ModelBone> bones_;
  43. Vector<ModelMorph> morphs_;
  44. Vector<String> materialNames_;
  45. BoundingBox boundingBox_;
  46. unsigned maxBones_ = 64;
  47. unsigned numSubMeshes_ = 0;
  48. bool useOneBuffer_ = true;
  49. int main(int argc, char** argv);
  50. void Run(const Vector<String>& arguments);
  51. void LoadSkeleton(const String& skeletonFileName);
  52. void LoadMesh(const String& inputFileName, bool generateTangents, bool splitSubMeshes, bool exportMorphs);
  53. void WriteOutput(const String& outputFileName, bool exportAnimations, bool rotationsOnly, bool saveMaterialList);
  54. void OptimizeIndices(ModelSubGeometryLodLevel* subGeom, ModelVertexBuffer* vb, ModelIndexBuffer* ib);
  55. void CalculateScore(ModelVertex& vertex);
  56. String SanitateAssetName(const String& name);
  57. int main(int argc, char** argv)
  58. {
  59. Vector<String> arguments;
  60. #ifdef WIN32
  61. arguments = ParseArguments(GetCommandLineW());
  62. #else
  63. arguments = ParseArguments(argc, argv);
  64. #endif
  65. Run(arguments);
  66. return 0;
  67. }
  68. void Run(const Vector<String>& arguments)
  69. {
  70. if (arguments.Size() < 2)
  71. {
  72. ErrorExit(
  73. "Usage: OgreImporter <input file> <output file> [options]\n\n"
  74. "Options:\n"
  75. "-l Output a material list file\n"
  76. "-na Do not output animations\n"
  77. "-nm Do not output morphs\n"
  78. "-r Output only rotations from animations\n"
  79. "-s Split each submesh into own vertex buffer\n"
  80. "-t Generate tangents\n"
  81. "-mb <x> Maximum number of bones per submesh, default 64\n"
  82. );
  83. }
  84. bool generateTangents = false;
  85. bool splitSubMeshes = false;
  86. bool exportAnimations = true;
  87. bool exportMorphs = true;
  88. bool rotationsOnly = false;
  89. bool saveMaterialList = false;
  90. if (arguments.Size() > 2)
  91. {
  92. for (unsigned i = 2; i < arguments.Size(); ++i)
  93. {
  94. if (arguments[i].Length() > 1 && arguments[i][0] == '-')
  95. {
  96. String argument = arguments[i].Substring(1).ToLower();
  97. if (argument == "l")
  98. saveMaterialList = true;
  99. else if (argument == "r")
  100. rotationsOnly = true;
  101. else if (argument == "s")
  102. splitSubMeshes = true;
  103. else if (argument == "t")
  104. generateTangents = true;
  105. else if (argument.Length() == 2 && argument[0] == 'n')
  106. {
  107. switch (tolower(argument[1]))
  108. {
  109. case 'a':
  110. exportAnimations = false;
  111. break;
  112. case 'm':
  113. exportMorphs = false;
  114. break;
  115. }
  116. break;
  117. }
  118. else if (argument == "mb" && i < arguments.Size() - 1)
  119. {
  120. maxBones_ = ToUInt(arguments[i + 1]);
  121. if (maxBones_ < 1)
  122. maxBones_ = 1;
  123. ++i;
  124. }
  125. }
  126. }
  127. }
  128. LoadMesh(arguments[0], generateTangents, splitSubMeshes, exportMorphs);
  129. WriteOutput(arguments[1], exportAnimations, rotationsOnly, saveMaterialList);
  130. PrintLine("Finished");
  131. }
  132. void LoadSkeleton(const String& skeletonFileName)
  133. {
  134. // Process skeleton first (if found)
  135. XMLElement skeletonRoot;
  136. File skeletonFileSource(context_);
  137. skeletonFileSource.Open(skeletonFileName);
  138. if (!skelFile_->Load(skeletonFileSource))
  139. PrintLine("Failed to load skeleton " + skeletonFileName);
  140. skeletonRoot = skelFile_->GetRoot();
  141. if (skeletonRoot)
  142. {
  143. XMLElement bonesRoot = skeletonRoot.GetChild("bones");
  144. XMLElement bone = bonesRoot.GetChild("bone");
  145. while (bone)
  146. {
  147. unsigned index = bone.GetInt("id");
  148. String name = bone.GetAttribute("name");
  149. if (index >= bones_.Size())
  150. bones_.Resize(index + 1);
  151. // Convert from right- to left-handed
  152. XMLElement position = bone.GetChild("position");
  153. float x = position.GetFloat("x");
  154. float y = position.GetFloat("y");
  155. float z = position.GetFloat("z");
  156. Vector3 pos(x, y, -z);
  157. XMLElement rotation = bone.GetChild("rotation");
  158. XMLElement axis = rotation.GetChild("axis");
  159. float angle = -rotation.GetFloat("angle") * M_RADTODEG;
  160. x = axis.GetFloat("x");
  161. y = axis.GetFloat("y");
  162. z = axis.GetFloat("z");
  163. Vector3 axisVec(x, y, -z);
  164. Quaternion rot(angle, axisVec);
  165. bones_[index].name_ = name;
  166. bones_[index].parentIndex_ = index; // Fill in the correct parent later
  167. bones_[index].bindPosition_ = pos;
  168. bones_[index].bindRotation_ = rot;
  169. bones_[index].bindScale_ = Vector3::ONE;
  170. bones_[index].collisionMask_ = 0;
  171. bones_[index].radius_ = 0.0f;
  172. bone = bone.GetNext("bone");
  173. }
  174. // Go through the bone hierarchy
  175. XMLElement boneHierarchy = skeletonRoot.GetChild("bonehierarchy");
  176. XMLElement boneParent = boneHierarchy.GetChild("boneparent");
  177. while (boneParent)
  178. {
  179. String bone = boneParent.GetAttribute("bone");
  180. String parent = boneParent.GetAttribute("parent");
  181. unsigned i = 0, j = 0;
  182. for (i = 0; i < bones_.Size() && bones_[i].name_ != bone; ++i);
  183. for (j = 0; j < bones_.Size() && bones_[j].name_ != parent; ++j);
  184. if (i >= bones_.Size() || j >= bones_.Size())
  185. ErrorExit("Found indeterminate parent bone assignment");
  186. bones_[i].parentIndex_ = j;
  187. boneParent = boneParent.GetNext("boneparent");
  188. }
  189. // Calculate bone derived positions
  190. for (unsigned i = 0; i < bones_.Size(); ++i)
  191. {
  192. Vector3 derivedPosition = bones_[i].bindPosition_;
  193. Quaternion derivedRotation = bones_[i].bindRotation_;
  194. Vector3 derivedScale = bones_[i].bindScale_;
  195. unsigned index = bones_[i].parentIndex_;
  196. if (index != i)
  197. {
  198. for (;;)
  199. {
  200. derivedPosition = bones_[index].bindPosition_ + (bones_[index].bindRotation_ * (bones_[index].bindScale_ * derivedPosition));
  201. derivedRotation = bones_[index].bindRotation_ * derivedRotation;
  202. derivedScale = bones_[index].bindScale_ * derivedScale;
  203. if (bones_[index].parentIndex_ != index)
  204. index = bones_[index].parentIndex_;
  205. else
  206. break;
  207. }
  208. }
  209. bones_[i].derivedPosition_ = derivedPosition;
  210. bones_[i].derivedRotation_ = derivedRotation;
  211. bones_[i].derivedScale_ = derivedScale;
  212. bones_[i].worldTransform_ = Matrix3x4(derivedPosition, derivedRotation, derivedScale);
  213. bones_[i].inverseWorldTransform_ = bones_[i].worldTransform_.Inverse();
  214. }
  215. PrintLine("Processed skeleton");
  216. }
  217. }
  218. void LoadMesh(const String& inputFileName, bool generateTangents, bool splitSubMeshes, bool exportMorphs)
  219. {
  220. File meshFileSource(context_);
  221. meshFileSource.Open(inputFileName);
  222. if (!meshFile_->Load(meshFileSource))
  223. ErrorExit("Could not load input file " + inputFileName);
  224. XMLElement root = meshFile_->GetRoot("mesh");
  225. XMLElement subMeshes = root.GetChild("submeshes");
  226. XMLElement skeletonLink = root.GetChild("skeletonlink");
  227. if (root.IsNull())
  228. ErrorExit("Could not load input file " + inputFileName);
  229. String skeletonName = skeletonLink.GetAttribute("name");
  230. if (!skeletonName.Empty())
  231. LoadSkeleton(GetPath(inputFileName) + GetFileName(skeletonName) + ".skeleton.xml");
  232. // Check whether there's benefit of avoiding 32bit indices by splitting each submesh into own buffer
  233. XMLElement subMesh = subMeshes.GetChild("submesh");
  234. unsigned totalVertices = 0;
  235. unsigned maxSubMeshVertices = 0;
  236. while (subMesh)
  237. {
  238. materialNames_.Push(subMesh.GetAttribute("material"));
  239. XMLElement geometry = subMesh.GetChild("geometry");
  240. if (geometry)
  241. {
  242. unsigned vertices = geometry.GetInt("vertexcount");
  243. totalVertices += vertices;
  244. if (maxSubMeshVertices < vertices)
  245. maxSubMeshVertices = vertices;
  246. }
  247. ++numSubMeshes_;
  248. subMesh = subMesh.GetNext("submesh");
  249. }
  250. XMLElement sharedGeometry = root.GetChild("sharedgeometry");
  251. if (sharedGeometry)
  252. {
  253. unsigned vertices = sharedGeometry.GetInt("vertexcount");
  254. totalVertices += vertices;
  255. if (maxSubMeshVertices < vertices)
  256. maxSubMeshVertices = vertices;
  257. }
  258. if (!sharedGeometry && (splitSubMeshes || (totalVertices > 65535 && maxSubMeshVertices <= 65535)))
  259. {
  260. useOneBuffer_ = false;
  261. vertexBuffers_.Resize(numSubMeshes_);
  262. indexBuffers_.Resize(numSubMeshes_);
  263. }
  264. else
  265. {
  266. vertexBuffers_.Resize(1);
  267. indexBuffers_.Resize(1);
  268. }
  269. subMesh = subMeshes.GetChild("submesh");
  270. unsigned indexStart = 0;
  271. unsigned vertexStart = 0;
  272. unsigned subMeshIndex = 0;
  273. PODVector<unsigned> vertexStarts;
  274. vertexStarts.Resize(numSubMeshes_);
  275. while (subMesh)
  276. {
  277. XMLElement geometry = subMesh.GetChild("geometry");
  278. XMLElement faces = subMesh.GetChild("faces");
  279. // If no submesh vertexbuffer, process the shared geometry, but do it only once
  280. unsigned vertices = 0;
  281. if (!geometry)
  282. {
  283. vertexStart = 0;
  284. if (!subMeshIndex)
  285. geometry = root.GetChild("sharedgeometry");
  286. }
  287. if (geometry)
  288. vertices = geometry.GetInt("vertexcount");
  289. ModelSubGeometryLodLevel subGeometryLodLevel;
  290. ModelVertexBuffer* vBuf;
  291. ModelIndexBuffer* iBuf;
  292. if (useOneBuffer_)
  293. {
  294. vBuf = &vertexBuffers_[0];
  295. if (vertices)
  296. vBuf->vertices_.Resize(vertexStart + vertices);
  297. iBuf = &indexBuffers_[0];
  298. subGeometryLodLevel.vertexBuffer_ = 0;
  299. subGeometryLodLevel.indexBuffer_ = 0;
  300. }
  301. else
  302. {
  303. vertexStart = 0;
  304. indexStart = 0;
  305. vBuf = &vertexBuffers_[subMeshIndex];
  306. vBuf->vertices_.Resize(vertices);
  307. iBuf = &indexBuffers_[subMeshIndex];
  308. subGeometryLodLevel.vertexBuffer_ = subMeshIndex;
  309. subGeometryLodLevel.indexBuffer_ = subMeshIndex;
  310. }
  311. // Store the start vertex for later use
  312. vertexStarts[subMeshIndex] = vertexStart;
  313. // Ogre may have multiple buffers in one submesh. These will be merged into one
  314. XMLElement bufferDef;
  315. if (geometry)
  316. bufferDef = geometry.GetChild("vertexbuffer");
  317. while (bufferDef)
  318. {
  319. if (bufferDef.HasAttribute("positions"))
  320. vBuf->elementMask_ |= MASK_POSITION;
  321. if (bufferDef.HasAttribute("normals"))
  322. vBuf->elementMask_ |= MASK_NORMAL;
  323. if (bufferDef.HasAttribute("texture_coords"))
  324. {
  325. vBuf->elementMask_ |= MASK_TEXCOORD1;
  326. if (bufferDef.GetInt("texture_coords") > 1)
  327. vBuf->elementMask_ |= MASK_TEXCOORD2;
  328. }
  329. unsigned vertexNum = vertexStart;
  330. if (vertices)
  331. {
  332. XMLElement vertex = bufferDef.GetChild("vertex");
  333. while (vertex)
  334. {
  335. XMLElement position = vertex.GetChild("position");
  336. if (position)
  337. {
  338. // Convert from right- to left-handed
  339. float x = position.GetFloat("x");
  340. float y = position.GetFloat("y");
  341. float z = position.GetFloat("z");
  342. Vector3 vec(x, y, -z);
  343. vBuf->vertices_[vertexNum].position_ = vec;
  344. boundingBox_.Merge(vec);
  345. }
  346. XMLElement normal = vertex.GetChild("normal");
  347. if (normal)
  348. {
  349. // Convert from right- to left-handed
  350. float x = normal.GetFloat("x");
  351. float y = normal.GetFloat("y");
  352. float z = normal.GetFloat("z");
  353. Vector3 vec(x, y, -z);
  354. vBuf->vertices_[vertexNum].normal_ = vec;
  355. }
  356. XMLElement uv = vertex.GetChild("texcoord");
  357. if (uv)
  358. {
  359. float x = uv.GetFloat("u");
  360. float y = uv.GetFloat("v");
  361. Vector2 vec(x, y);
  362. vBuf->vertices_[vertexNum].texCoord1_ = vec;
  363. if (vBuf->elementMask_ & MASK_TEXCOORD2)
  364. {
  365. uv = uv.GetNext("texcoord");
  366. if (uv)
  367. {
  368. float x = uv.GetFloat("u");
  369. float y = uv.GetFloat("v");
  370. Vector2 vec(x, y);
  371. vBuf->vertices_[vertexNum].texCoord2_ = vec;
  372. }
  373. }
  374. }
  375. vertexNum++;
  376. vertex = vertex.GetNext("vertex");
  377. }
  378. }
  379. bufferDef = bufferDef.GetNext("vertexbuffer");
  380. }
  381. unsigned triangles = faces.GetInt("count");
  382. unsigned indices = triangles * 3;
  383. XMLElement triangle = faces.GetChild("face");
  384. while (triangle)
  385. {
  386. unsigned v1 = triangle.GetInt("v1");
  387. unsigned v2 = triangle.GetInt("v2");
  388. unsigned v3 = triangle.GetInt("v3");
  389. iBuf->indices_.Push(v3 + vertexStart);
  390. iBuf->indices_.Push(v2 + vertexStart);
  391. iBuf->indices_.Push(v1 + vertexStart);
  392. triangle = triangle.GetNext("face");
  393. }
  394. subGeometryLodLevel.indexStart_ = indexStart;
  395. subGeometryLodLevel.indexCount_ = indices;
  396. if (vertexStart + vertices > 65535)
  397. iBuf->indexSize_ = sizeof(unsigned);
  398. XMLElement boneAssignments = subMesh.GetChild("boneassignments");
  399. if (bones_.Size())
  400. {
  401. if (boneAssignments)
  402. {
  403. XMLElement boneAssignment = boneAssignments.GetChild("vertexboneassignment");
  404. while (boneAssignment)
  405. {
  406. unsigned vertex = boneAssignment.GetInt("vertexindex") + vertexStart;
  407. unsigned bone = boneAssignment.GetInt("boneindex");
  408. float weight = boneAssignment.GetFloat("weight");
  409. BoneWeightAssignment assign{static_cast<unsigned char>(bone), weight};
  410. // Source data might have 0 weights. Disregard these
  411. if (assign.weight_ > 0.0f)
  412. {
  413. subGeometryLodLevel.boneWeights_[vertex].Push(assign);
  414. // Require skinning weight to be sufficiently large before vertex contributes to bone hitbox
  415. if (assign.weight_ > 0.33f)
  416. {
  417. // Check distance of vertex from bone to get bone max. radius information
  418. Vector3 bonePos = bones_[bone].derivedPosition_;
  419. Vector3 vertexPos = vBuf->vertices_[vertex].position_;
  420. float distance = (bonePos - vertexPos).Length();
  421. if (distance > bones_[bone].radius_)
  422. {
  423. bones_[bone].collisionMask_ |= 1;
  424. bones_[bone].radius_ = distance;
  425. }
  426. // Build the hitbox for the bone
  427. bones_[bone].boundingBox_.Merge(bones_[bone].inverseWorldTransform_ * (vertexPos));
  428. bones_[bone].collisionMask_ |= 2;
  429. }
  430. }
  431. boneAssignment = boneAssignment.GetNext("vertexboneassignment");
  432. }
  433. }
  434. if ((subGeometryLodLevel.boneWeights_.Size()) && bones_.Size())
  435. {
  436. vBuf->elementMask_ |= MASK_BLENDWEIGHTS | MASK_BLENDINDICES;
  437. bool sorted = false;
  438. // If amount of bones is larger than supported by HW skinning, must remap per submesh
  439. if (bones_.Size() > maxBones_)
  440. {
  441. HashMap<unsigned, unsigned> usedBoneMap;
  442. unsigned remapIndex = 0;
  443. for (HashMap<unsigned, PODVector<BoneWeightAssignment> >::Iterator i =
  444. subGeometryLodLevel.boneWeights_.Begin(); i != subGeometryLodLevel.boneWeights_.End(); ++i)
  445. {
  446. // Sort the bone assigns by weight
  447. Sort(i->second_.Begin(), i->second_.End(), CompareWeights);
  448. // Use only the first 4 weights
  449. for (unsigned j = 0; j < i->second_.Size() && j < 4; ++j)
  450. {
  451. unsigned originalIndex = i->second_[j].boneIndex_;
  452. if (!usedBoneMap.Contains(originalIndex))
  453. {
  454. usedBoneMap[originalIndex] = remapIndex;
  455. remapIndex++;
  456. }
  457. i->second_[j].boneIndex_ = usedBoneMap[originalIndex];
  458. }
  459. }
  460. // If still too many bones in one subgeometry, error
  461. if (usedBoneMap.Size() > maxBones_)
  462. ErrorExit("Too many bones (limit " + String(maxBones_) + ") in submesh " + String(subMeshIndex + 1));
  463. // Write mapping of vertex buffer bone indices to original bone indices
  464. subGeometryLodLevel.boneMapping_.Resize(usedBoneMap.Size());
  465. for (HashMap<unsigned, unsigned>::Iterator j = usedBoneMap.Begin(); j != usedBoneMap.End(); ++j)
  466. subGeometryLodLevel.boneMapping_[j->second_] = j->first_;
  467. sorted = true;
  468. }
  469. for (HashMap<unsigned, PODVector<BoneWeightAssignment> >::Iterator i = subGeometryLodLevel.boneWeights_.Begin();
  470. i != subGeometryLodLevel.boneWeights_.End(); ++i)
  471. {
  472. // Sort the bone assigns by weight, if not sorted yet in bone remapping pass
  473. if (!sorted)
  474. Sort(i->second_.Begin(), i->second_.End(), CompareWeights);
  475. float totalWeight = 0.0f;
  476. float normalizationFactor = 0.0f;
  477. // Calculate normalization factor in case there are more than 4 blend weights, or they do not add up to 1
  478. for (unsigned j = 0; j < i->second_.Size() && j < 4; ++j)
  479. totalWeight += i->second_[j].weight_;
  480. if (totalWeight > 0.0f)
  481. normalizationFactor = 1.0f / totalWeight;
  482. for (unsigned j = 0; j < i->second_.Size() && j < 4; ++j)
  483. {
  484. vBuf->vertices_[i->first_].blendIndices_[j] = i->second_[j].boneIndex_;
  485. vBuf->vertices_[i->first_].blendWeights_[j] = i->second_[j].weight_ * normalizationFactor;
  486. }
  487. // If there are less than 4 blend weights, fill rest with zero
  488. for (unsigned j = i->second_.Size(); j < 4; ++j)
  489. {
  490. vBuf->vertices_[i->first_].blendIndices_[j] = 0;
  491. vBuf->vertices_[i->first_].blendWeights_[j] = 0.0f;
  492. }
  493. vBuf->vertices_[i->first_].hasBlendWeights_ = true;
  494. }
  495. }
  496. }
  497. else if (boneAssignments)
  498. PrintLine("No skeleton loaded, skipping skinning information");
  499. // Calculate center for the subgeometry
  500. Vector3 center = Vector3::ZERO;
  501. for (unsigned i = 0; i < iBuf->indices_.Size(); i += 3)
  502. {
  503. center += vBuf->vertices_[iBuf->indices_[i]].position_;
  504. center += vBuf->vertices_[iBuf->indices_[i + 1]].position_;
  505. center += vBuf->vertices_[iBuf->indices_[i + 2]].position_;
  506. }
  507. if (iBuf->indices_.Size())
  508. center /= (float)iBuf->indices_.Size();
  509. subGeometryCenters_.Push(center);
  510. indexStart += indices;
  511. vertexStart += vertices;
  512. OptimizeIndices(&subGeometryLodLevel, vBuf, iBuf);
  513. PrintLine("Processed submesh " + String(subMeshIndex + 1) + ": " + String(vertices) + " vertices " +
  514. String(triangles) + " triangles");
  515. Vector<ModelSubGeometryLodLevel> thisSubGeometry;
  516. thisSubGeometry.Push(subGeometryLodLevel);
  517. subGeometries_.Push(thisSubGeometry);
  518. subMesh = subMesh.GetNext("submesh");
  519. subMeshIndex++;
  520. }
  521. // Process LOD levels, if any
  522. XMLElement lods = root.GetChild("levelofdetail");
  523. if (lods)
  524. {
  525. try
  526. {
  527. // For now, support only generated LODs, where the vertices are the same
  528. XMLElement lod = lods.GetChild("lodgenerated");
  529. while (lod)
  530. {
  531. float distance = M_EPSILON;
  532. if (lod.HasAttribute("fromdepthsquared"))
  533. distance = sqrtf(lod.GetFloat("fromdepthsquared"));
  534. if (lod.HasAttribute("value"))
  535. distance = lod.GetFloat("value");
  536. XMLElement lodSubMesh = lod.GetChild("lodfacelist");
  537. while (lodSubMesh)
  538. {
  539. unsigned subMeshIndex = lodSubMesh.GetInt("submeshindex");
  540. unsigned triangles = lodSubMesh.GetInt("numfaces");
  541. ModelSubGeometryLodLevel newLodLevel;
  542. ModelSubGeometryLodLevel& originalLodLevel = subGeometries_[subMeshIndex][0];
  543. // Copy all initial values
  544. newLodLevel = originalLodLevel;
  545. ModelVertexBuffer* vBuf;
  546. ModelIndexBuffer* iBuf;
  547. if (useOneBuffer_)
  548. {
  549. vBuf = &vertexBuffers_[0];
  550. iBuf = &indexBuffers_[0];
  551. }
  552. else
  553. {
  554. vBuf = &vertexBuffers_[subMeshIndex];
  555. iBuf = &indexBuffers_[subMeshIndex];
  556. }
  557. unsigned indexStart = iBuf->indices_.Size();
  558. unsigned indexCount = triangles * 3;
  559. unsigned vertexStart = vertexStarts[subMeshIndex];
  560. newLodLevel.distance_ = distance;
  561. newLodLevel.indexStart_ = indexStart;
  562. newLodLevel.indexCount_ = indexCount;
  563. // Append indices to the original index buffer
  564. XMLElement triangle = lodSubMesh.GetChild("face");
  565. while (triangle)
  566. {
  567. unsigned v1 = triangle.GetInt("v1");
  568. unsigned v2 = triangle.GetInt("v2");
  569. unsigned v3 = triangle.GetInt("v3");
  570. iBuf->indices_.Push(v3 + vertexStart);
  571. iBuf->indices_.Push(v2 + vertexStart);
  572. iBuf->indices_.Push(v1 + vertexStart);
  573. triangle = triangle.GetNext("face");
  574. }
  575. OptimizeIndices(&newLodLevel, vBuf, iBuf);
  576. subGeometries_[subMeshIndex].Push(newLodLevel);
  577. PrintLine("Processed LOD level for submesh " + String(subMeshIndex + 1) + ": distance " + String(distance));
  578. lodSubMesh = lodSubMesh.GetNext("lodfacelist");
  579. }
  580. lod = lod.GetNext("lodgenerated");
  581. }
  582. }
  583. catch (...) {}
  584. }
  585. // Process poses/morphs
  586. // First find out all pose definitions
  587. if (exportMorphs)
  588. {
  589. try
  590. {
  591. Vector<XMLElement> poses;
  592. XMLElement posesRoot = root.GetChild("poses");
  593. if (posesRoot)
  594. {
  595. XMLElement pose = posesRoot.GetChild("pose");
  596. while (pose)
  597. {
  598. poses.Push(pose);
  599. pose = pose.GetNext("pose");
  600. }
  601. }
  602. // Then process animations using the poses
  603. XMLElement animsRoot = root.GetChild("animations");
  604. if (animsRoot)
  605. {
  606. XMLElement anim = animsRoot.GetChild("animation");
  607. while (anim)
  608. {
  609. String name = anim.GetAttribute("name");
  610. float length = anim.GetFloat("length");
  611. HashSet<unsigned> usedPoses;
  612. XMLElement tracks = anim.GetChild("tracks");
  613. if (tracks)
  614. {
  615. XMLElement track = tracks.GetChild("track");
  616. while (track)
  617. {
  618. XMLElement keyframes = track.GetChild("keyframes");
  619. if (keyframes)
  620. {
  621. XMLElement keyframe = keyframes.GetChild("keyframe");
  622. while (keyframe)
  623. {
  624. float time = keyframe.GetFloat("time");
  625. XMLElement poseref = keyframe.GetChild("poseref");
  626. // Get only the end pose
  627. if (poseref && time == length)
  628. usedPoses.Insert(poseref.GetInt("poseindex"));
  629. keyframe = keyframe.GetNext("keyframe");
  630. }
  631. }
  632. track = track.GetNext("track");
  633. }
  634. }
  635. if (usedPoses.Size())
  636. {
  637. ModelMorph newMorph;
  638. newMorph.name_ = name;
  639. if (useOneBuffer_)
  640. newMorph.buffers_.Resize(1);
  641. else
  642. newMorph.buffers_.Resize(usedPoses.Size());
  643. unsigned bufIndex = 0;
  644. for (HashSet<unsigned>::Iterator i = usedPoses.Begin(); i != usedPoses.End(); ++i)
  645. {
  646. XMLElement pose = poses[*i];
  647. unsigned targetSubMesh = pose.GetInt("index");
  648. XMLElement poseOffset = pose.GetChild("poseoffset");
  649. if (useOneBuffer_)
  650. newMorph.buffers_[bufIndex].vertexBuffer_ = 0;
  651. else
  652. newMorph.buffers_[bufIndex].vertexBuffer_ = targetSubMesh;
  653. newMorph.buffers_[bufIndex].elementMask_ = MASK_POSITION;
  654. ModelVertexBuffer* vBuf = &vertexBuffers_[newMorph.buffers_[bufIndex].vertexBuffer_];
  655. while (poseOffset)
  656. {
  657. // Convert from right- to left-handed
  658. unsigned vertexIndex = poseOffset.GetInt("index") + vertexStarts[targetSubMesh];
  659. float x = poseOffset.GetFloat("x");
  660. float y = poseOffset.GetFloat("y");
  661. float z = poseOffset.GetFloat("z");
  662. Vector3 vec(x, y, -z);
  663. if (vBuf->morphCount_ == 0)
  664. {
  665. vBuf->morphStart_ = vertexIndex;
  666. vBuf->morphCount_ = 1;
  667. }
  668. else
  669. {
  670. unsigned first = vBuf->morphStart_;
  671. unsigned last = first + vBuf->morphCount_ - 1;
  672. if (vertexIndex < first)
  673. first = vertexIndex;
  674. if (vertexIndex > last)
  675. last = vertexIndex;
  676. vBuf->morphStart_ = first;
  677. vBuf->morphCount_ = last - first + 1;
  678. }
  679. ModelVertex newVertex;
  680. newVertex.position_ = vec;
  681. newMorph.buffers_[bufIndex].vertices_.Push(MakePair(vertexIndex, newVertex));
  682. poseOffset = poseOffset.GetNext("poseoffset");
  683. }
  684. if (!useOneBuffer_)
  685. ++bufIndex;
  686. }
  687. morphs_.Push(newMorph);
  688. PrintLine("Processed morph " + name + " with " + String(usedPoses.Size()) + " sub-poses");
  689. }
  690. anim = anim.GetNext("animation");
  691. }
  692. }
  693. }
  694. catch (...) {}
  695. }
  696. // Check any of the buffers for vertices with missing blend weight assignments
  697. for (unsigned i = 0; i < vertexBuffers_.Size(); ++i)
  698. {
  699. if (vertexBuffers_[i].elementMask_ & MASK_BLENDWEIGHTS)
  700. {
  701. for (unsigned j = 0; j < vertexBuffers_[i].vertices_.Size(); ++j)
  702. if (!vertexBuffers_[i].vertices_[j].hasBlendWeights_)
  703. ErrorExit("Found a vertex with missing skinning information");
  704. }
  705. }
  706. // Tangent generation
  707. if (generateTangents)
  708. {
  709. for (unsigned i = 0; i < subGeometries_.Size(); ++i)
  710. {
  711. for (unsigned j = 0; j < subGeometries_[i].Size(); ++j)
  712. {
  713. ModelVertexBuffer& vBuf = vertexBuffers_[subGeometries_[i][j].vertexBuffer_];
  714. ModelIndexBuffer& iBuf = indexBuffers_[subGeometries_[i][j].indexBuffer_];
  715. unsigned indexStart = subGeometries_[i][j].indexStart_;
  716. unsigned indexCount = subGeometries_[i][j].indexCount_;
  717. // If already has tangents, do not regenerate
  718. if (vBuf.elementMask_ & MASK_TANGENT || vBuf.vertices_.Empty() || iBuf.indices_.Empty())
  719. continue;
  720. vBuf.elementMask_ |= MASK_TANGENT;
  721. if ((vBuf.elementMask_ & (MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1)) != (MASK_POSITION | MASK_NORMAL |
  722. MASK_TEXCOORD1))
  723. ErrorExit("To generate tangents, positions normals and texcoords are required");
  724. GenerateTangents(&vBuf.vertices_[0], sizeof(ModelVertex), &iBuf.indices_[0], sizeof(unsigned), indexStart,
  725. indexCount, offsetof(ModelVertex, normal_), offsetof(ModelVertex, texCoord1_), offsetof(ModelVertex,
  726. tangent_));
  727. PrintLine("Generated tangents");
  728. }
  729. }
  730. }
  731. }
  732. void WriteOutput(const String& outputFileName, bool exportAnimations, bool rotationsOnly, bool saveMaterialList)
  733. {
  734. /// \todo Use save functions of Model & Animation classes
  735. // Begin serialization
  736. {
  737. File dest(context_);
  738. if (!dest.Open(outputFileName, FILE_WRITE))
  739. ErrorExit("Could not open output file " + outputFileName);
  740. // ID
  741. dest.WriteFileID("UMD2");
  742. // Vertexbuffers
  743. dest.WriteUInt(vertexBuffers_.Size());
  744. for (unsigned i = 0; i < vertexBuffers_.Size(); ++i)
  745. vertexBuffers_[i].WriteData(dest);
  746. // Indexbuffers
  747. dest.WriteUInt(indexBuffers_.Size());
  748. for (unsigned i = 0; i < indexBuffers_.Size(); ++i)
  749. indexBuffers_[i].WriteData(dest);
  750. // Subgeometries
  751. dest.WriteUInt(subGeometries_.Size());
  752. for (unsigned i = 0; i < subGeometries_.Size(); ++i)
  753. {
  754. // Write bone mapping info from the first LOD level. It does not change for further LODs
  755. dest.WriteUInt(subGeometries_[i][0].boneMapping_.Size());
  756. for (unsigned k = 0; k < subGeometries_[i][0].boneMapping_.Size(); ++k)
  757. dest.WriteUInt(subGeometries_[i][0].boneMapping_[k]);
  758. // Lod levels for this subgeometry
  759. dest.WriteUInt(subGeometries_[i].Size());
  760. for (unsigned j = 0; j < subGeometries_[i].Size(); ++j)
  761. {
  762. dest.WriteFloat(subGeometries_[i][j].distance_);
  763. dest.WriteUInt((unsigned)subGeometries_[i][j].primitiveType_);
  764. dest.WriteUInt(subGeometries_[i][j].vertexBuffer_);
  765. dest.WriteUInt(subGeometries_[i][j].indexBuffer_);
  766. dest.WriteUInt(subGeometries_[i][j].indexStart_);
  767. dest.WriteUInt(subGeometries_[i][j].indexCount_);
  768. }
  769. }
  770. // Morphs
  771. dest.WriteUInt(morphs_.Size());
  772. for (unsigned i = 0; i < morphs_.Size(); ++i)
  773. morphs_[i].WriteData(dest);
  774. // Skeleton
  775. dest.WriteUInt(bones_.Size());
  776. for (unsigned i = 0; i < bones_.Size(); ++i)
  777. {
  778. dest.WriteString(bones_[i].name_);
  779. dest.WriteUInt(bones_[i].parentIndex_);
  780. dest.WriteVector3(bones_[i].bindPosition_);
  781. dest.WriteQuaternion(bones_[i].bindRotation_);
  782. dest.WriteVector3(bones_[i].bindScale_);
  783. Matrix3x4 offsetMatrix(bones_[i].derivedPosition_, bones_[i].derivedRotation_, bones_[i].derivedScale_);
  784. offsetMatrix = offsetMatrix.Inverse();
  785. dest.Write(offsetMatrix.Data(), sizeof(Matrix3x4));
  786. dest.WriteUByte(bones_[i].collisionMask_);
  787. if (bones_[i].collisionMask_ & 1u)
  788. dest.WriteFloat(bones_[i].radius_);
  789. if (bones_[i].collisionMask_ & 2u)
  790. dest.WriteBoundingBox(bones_[i].boundingBox_);
  791. }
  792. // Bounding box
  793. dest.WriteBoundingBox(boundingBox_);
  794. // Geometry centers
  795. for (unsigned i = 0; i < subGeometryCenters_.Size(); ++i)
  796. dest.WriteVector3(subGeometryCenters_[i]);
  797. }
  798. if (saveMaterialList)
  799. {
  800. String materialListName = ReplaceExtension(outputFileName, ".txt");
  801. File listFile(context_);
  802. if (listFile.Open(materialListName, FILE_WRITE))
  803. {
  804. for (unsigned i = 0; i < materialNames_.Size(); ++i)
  805. {
  806. // Assume the materials will be located inside the standard Materials subdirectory
  807. listFile.WriteLine("Materials/" + ReplaceExtension(SanitateAssetName(materialNames_[i]), ".xml"));
  808. }
  809. }
  810. else
  811. PrintLine("Warning: could not write material list file " + materialListName);
  812. }
  813. XMLElement skeletonRoot = skelFile_->GetRoot("skeleton");
  814. if (skeletonRoot && exportAnimations)
  815. {
  816. // Go through animations
  817. XMLElement animationsRoot = skeletonRoot.GetChild("animations");
  818. if (animationsRoot)
  819. {
  820. XMLElement animation = animationsRoot.GetChild("animation");
  821. while (animation)
  822. {
  823. ModelAnimation newAnimation;
  824. newAnimation.name_ = animation.GetAttribute("name");
  825. newAnimation.length_ = animation.GetFloat("length");
  826. XMLElement tracksRoot = animation.GetChild("tracks");
  827. XMLElement track = tracksRoot.GetChild("track");
  828. while (track)
  829. {
  830. String trackName = track.GetAttribute("bone");
  831. ModelBone* bone = nullptr;
  832. for (unsigned i = 0; i < bones_.Size(); ++i)
  833. {
  834. if (bones_[i].name_ == trackName)
  835. {
  836. bone = &bones_[i];
  837. break;
  838. }
  839. }
  840. if (!bone)
  841. ErrorExit("Found animation track for unknown bone " + trackName);
  842. AnimationTrack newAnimationTrack;
  843. newAnimationTrack.name_ = trackName;
  844. if (!rotationsOnly)
  845. newAnimationTrack.channelMask_ = CHANNEL_POSITION | CHANNEL_ROTATION;
  846. else
  847. newAnimationTrack.channelMask_ = CHANNEL_ROTATION;
  848. XMLElement keyFramesRoot = track.GetChild("keyframes");
  849. XMLElement keyFrame = keyFramesRoot.GetChild("keyframe");
  850. while (keyFrame)
  851. {
  852. AnimationKeyFrame newKeyFrame;
  853. // Convert from right- to left-handed
  854. XMLElement position = keyFrame.GetChild("translate");
  855. float x = position.GetFloat("x");
  856. float y = position.GetFloat("y");
  857. float z = position.GetFloat("z");
  858. Vector3 pos(x, y, -z);
  859. XMLElement rotation = keyFrame.GetChild("rotate");
  860. XMLElement axis = rotation.GetChild("axis");
  861. float angle = -rotation.GetFloat("angle") * M_RADTODEG;
  862. x = axis.GetFloat("x");
  863. y = axis.GetFloat("y");
  864. z = axis.GetFloat("z");
  865. Vector3 axisVec(x, y, -z);
  866. Quaternion rot(angle, axisVec);
  867. // Transform from bind-pose relative into absolute
  868. pos = bone->bindPosition_ + pos;
  869. rot = bone->bindRotation_ * rot;
  870. newKeyFrame.time_ = keyFrame.GetFloat("time");
  871. newKeyFrame.position_ = pos;
  872. newKeyFrame.rotation_ = rot;
  873. newAnimationTrack.keyFrames_.Push(newKeyFrame);
  874. keyFrame = keyFrame.GetNext("keyframe");
  875. }
  876. // Make sure keyframes are sorted from beginning to end
  877. Sort(newAnimationTrack.keyFrames_.Begin(), newAnimationTrack.keyFrames_.End(), CompareKeyFrames);
  878. // Do not add tracks with no keyframes
  879. if (newAnimationTrack.keyFrames_.Size())
  880. newAnimation.tracks_.Push(newAnimationTrack);
  881. track = track.GetNext("track");
  882. }
  883. // Write each animation into a separate file
  884. String animationFileName = outputFileName.Replaced(".mdl", "");
  885. animationFileName += "_" + newAnimation.name_ + ".ani";
  886. File dest(context_);
  887. if (!dest.Open(animationFileName, FILE_WRITE))
  888. ErrorExit("Could not open output file " + animationFileName);
  889. dest.WriteFileID("UANI");
  890. dest.WriteString(newAnimation.name_);
  891. dest.WriteFloat(newAnimation.length_);
  892. dest.WriteUInt(newAnimation.tracks_.Size());
  893. for (unsigned i = 0; i < newAnimation.tracks_.Size(); ++i)
  894. {
  895. AnimationTrack& track = newAnimation.tracks_[i];
  896. dest.WriteString(track.name_);
  897. dest.WriteUByte(track.channelMask_);
  898. dest.WriteUInt(track.keyFrames_.Size());
  899. for (unsigned j = 0; j < track.keyFrames_.Size(); ++j)
  900. {
  901. AnimationKeyFrame& keyFrame = track.keyFrames_[j];
  902. dest.WriteFloat(keyFrame.time_);
  903. if (track.channelMask_ & CHANNEL_POSITION)
  904. dest.WriteVector3(keyFrame.position_);
  905. if (track.channelMask_ & CHANNEL_ROTATION)
  906. dest.WriteQuaternion(keyFrame.rotation_);
  907. if (track.channelMask_ & CHANNEL_SCALE)
  908. dest.WriteVector3(keyFrame.scale_);
  909. }
  910. }
  911. animation = animation.GetNext("animation");
  912. PrintLine("Processed animation " + newAnimation.name_);
  913. }
  914. }
  915. }
  916. }
  917. void OptimizeIndices(ModelSubGeometryLodLevel* subGeom, ModelVertexBuffer* vb, ModelIndexBuffer* ib)
  918. {
  919. PODVector<Triangle> oldTriangles;
  920. PODVector<Triangle> newTriangles;
  921. if (subGeom->indexCount_ % 3)
  922. {
  923. PrintLine("Index count is not divisible by 3, skipping index optimization");
  924. return;
  925. }
  926. for (unsigned i = 0; i < vb->vertices_.Size(); ++i)
  927. {
  928. vb->vertices_[i].useCount_ = 0;
  929. vb->vertices_[i].cachePosition_ = -1;
  930. }
  931. for (unsigned i = subGeom->indexStart_; i < subGeom->indexStart_ + subGeom->indexCount_; i += 3)
  932. {
  933. Triangle triangle{ib->indices_[i], ib->indices_[i + 1], ib->indices_[i + 2]};
  934. vb->vertices_[triangle.v0_].useCount_++;
  935. vb->vertices_[triangle.v1_].useCount_++;
  936. vb->vertices_[triangle.v2_].useCount_++;
  937. oldTriangles.Push(triangle);
  938. }
  939. for (unsigned i = 0; i < vb->vertices_.Size(); ++i)
  940. CalculateScore(vb->vertices_[i]);
  941. PODVector<unsigned> vertexCache;
  942. while (oldTriangles.Size())
  943. {
  944. unsigned bestTriangle = M_MAX_UNSIGNED;
  945. float bestTriangleScore = -1.0f;
  946. // Find the best triangle at this point
  947. for (unsigned i = 0; i < oldTriangles.Size(); ++i)
  948. {
  949. Triangle& triangle = oldTriangles[i];
  950. float triangleScore =
  951. vb->vertices_[triangle.v0_].score_ +
  952. vb->vertices_[triangle.v1_].score_ +
  953. vb->vertices_[triangle.v2_].score_;
  954. if (triangleScore > bestTriangleScore)
  955. {
  956. bestTriangle = i;
  957. bestTriangleScore = triangleScore;
  958. }
  959. }
  960. if (bestTriangle == M_MAX_UNSIGNED)
  961. {
  962. PrintLine("Could not find next triangle, aborting index optimization");
  963. return;
  964. }
  965. // Add the best triangle
  966. Triangle triangleCopy = oldTriangles[bestTriangle];
  967. newTriangles.Push(triangleCopy);
  968. oldTriangles.Erase(oldTriangles.Begin() + bestTriangle);
  969. // Reduce the use count
  970. vb->vertices_[triangleCopy.v0_].useCount_--;
  971. vb->vertices_[triangleCopy.v1_].useCount_--;
  972. vb->vertices_[triangleCopy.v2_].useCount_--;
  973. // Model the LRU cache behaviour
  974. // Erase the triangle vertices from the middle of the cache, if they were there
  975. for (unsigned i = 0; i < vertexCache.Size(); ++i)
  976. {
  977. if ((vertexCache[i] == triangleCopy.v0_) ||
  978. (vertexCache[i] == triangleCopy.v1_) ||
  979. (vertexCache[i] == triangleCopy.v2_))
  980. {
  981. vertexCache.Erase(vertexCache.Begin() + i);
  982. --i;
  983. }
  984. }
  985. // Then push them to the front
  986. vertexCache.Insert(vertexCache.Begin(), triangleCopy.v0_);
  987. vertexCache.Insert(vertexCache.Begin(), triangleCopy.v1_);
  988. vertexCache.Insert(vertexCache.Begin(), triangleCopy.v2_);
  989. // Update positions & scores of all vertices in the cache
  990. // Give position -1 if vertex is going to be erased
  991. for (unsigned i = 0; i < vertexCache.Size(); ++i)
  992. {
  993. ModelVertex& vertex = vb->vertices_[vertexCache[i]];
  994. if (i >= VERTEX_CACHE_SIZE)
  995. vertex.cachePosition_ = -1;
  996. else
  997. vertex.cachePosition_ = i;
  998. CalculateScore(vertex);
  999. }
  1000. // Finally erase the extra vertices
  1001. if (vertexCache.Size() > VERTEX_CACHE_SIZE)
  1002. vertexCache.Resize(VERTEX_CACHE_SIZE);
  1003. }
  1004. // Rewrite the index data now
  1005. unsigned i = subGeom->indexStart_;
  1006. for (unsigned j = 0; j < newTriangles.Size(); ++j)
  1007. {
  1008. ib->indices_[i++] = newTriangles[j].v0_;
  1009. ib->indices_[i++] = newTriangles[j].v1_;
  1010. ib->indices_[i++] = newTriangles[j].v2_;
  1011. }
  1012. }
  1013. void CalculateScore(ModelVertex& vertex)
  1014. {
  1015. // Linear-Speed Vertex Cache Optimisation by Tom Forsyth from
  1016. // http://home.comcast.net/~tom_forsyth/papers/fast_vert_cache_opt.html
  1017. const float cacheDecayPower = 1.5f;
  1018. const float lastTriScore = 0.75f;
  1019. const float valenceBoostScale = 2.0f;
  1020. const float valenceBoostPower = 0.5f;
  1021. if (vertex.useCount_ == 0)
  1022. {
  1023. // No tri needs this vertex!
  1024. vertex.score_ = -1.0f;
  1025. return;
  1026. }
  1027. float score = 0.0f;
  1028. int cachePosition = vertex.cachePosition_;
  1029. if (cachePosition < 0)
  1030. {
  1031. // Vertex is not in FIFO cache - no score.
  1032. }
  1033. else
  1034. {
  1035. if (cachePosition < 3)
  1036. {
  1037. // This vertex was used in the last triangle,
  1038. // so it has a fixed score, whichever of the three
  1039. // it's in. Otherwise, you can get very different
  1040. // answers depending on whether you add
  1041. // the triangle 1,2,3 or 3,1,2 - which is silly.
  1042. score = lastTriScore;
  1043. }
  1044. else
  1045. {
  1046. // Points for being high in the cache.
  1047. const float scaler = 1.0f / (VERTEX_CACHE_SIZE - 3);
  1048. score = 1.0f - (cachePosition - 3) * scaler;
  1049. score = powf(score, cacheDecayPower);
  1050. }
  1051. }
  1052. // Bonus points for having a low number of tris still to
  1053. // use the vert, so we get rid of lone verts quickly.
  1054. float valenceBoost = powf((float)vertex.useCount_, -valenceBoostPower);
  1055. score += valenceBoostScale * valenceBoost;
  1056. vertex.score_ = score;
  1057. }
  1058. String SanitateAssetName(const String& name)
  1059. {
  1060. String fixedName = name;
  1061. fixedName.Replace("<", "");
  1062. fixedName.Replace(">", "");
  1063. fixedName.Replace("?", "");
  1064. fixedName.Replace("*", "");
  1065. fixedName.Replace(":", "");
  1066. fixedName.Replace("\"", "");
  1067. fixedName.Replace("/", "");
  1068. fixedName.Replace("\\", "");
  1069. fixedName.Replace("|", "");
  1070. return fixedName;
  1071. }