OgreImporter.cpp 50 KB

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