OgreImporter.cpp 50 KB

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