OgreImporter.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  1. //
  2. // Copyright (c) 2008-2015 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;
  410. assign.boneIndex_ = bone;
  411. assign.weight_ = weight;
  412. // Source data might have 0 weights. Disregard these
  413. if (assign.weight_ > 0.0f)
  414. {
  415. subGeometryLodLevel.boneWeights_[vertex].Push(assign);
  416. // Require skinning weight to be sufficiently large before vertex contributes to bone hitbox
  417. if (assign.weight_ > 0.33f)
  418. {
  419. // Check distance of vertex from bone to get bone max. radius information
  420. Vector3 bonePos = bones_[bone].derivedPosition_;
  421. Vector3 vertexPos = vBuf->vertices_[vertex].position_;
  422. float distance = (bonePos - vertexPos).Length();
  423. if (distance > bones_[bone].radius_)
  424. {
  425. bones_[bone].collisionMask_ |= 1;
  426. bones_[bone].radius_ = distance;
  427. }
  428. // Build the hitbox for the bone
  429. bones_[bone].boundingBox_.Merge(bones_[bone].inverseWorldTransform_ * (vertexPos));
  430. bones_[bone].collisionMask_ |= 2;
  431. }
  432. }
  433. boneAssignment = boneAssignment.GetNext("vertexboneassignment");
  434. }
  435. }
  436. if ((subGeometryLodLevel.boneWeights_.Size()) && bones_.Size())
  437. {
  438. vBuf->elementMask_ |= MASK_BLENDWEIGHTS | MASK_BLENDINDICES;
  439. bool sorted = false;
  440. // If amount of bones is larger than supported by HW skinning, must remap per submesh
  441. if (bones_.Size() > maxBones_)
  442. {
  443. HashMap<unsigned, unsigned> usedBoneMap;
  444. unsigned remapIndex = 0;
  445. for (HashMap<unsigned, PODVector<BoneWeightAssignment> >::Iterator i =
  446. subGeometryLodLevel.boneWeights_.Begin(); i != subGeometryLodLevel.boneWeights_.End(); ++i)
  447. {
  448. // Sort the bone assigns by weight
  449. Sort(i->second_.Begin(), i->second_.End(), CompareWeights);
  450. // Use only the first 4 weights
  451. for (unsigned j = 0; j < i->second_.Size() && j < 4; ++j)
  452. {
  453. unsigned originalIndex = i->second_[j].boneIndex_;
  454. if (!usedBoneMap.Contains(originalIndex))
  455. {
  456. usedBoneMap[originalIndex] = remapIndex;
  457. remapIndex++;
  458. }
  459. i->second_[j].boneIndex_ = usedBoneMap[originalIndex];
  460. }
  461. }
  462. // If still too many bones in one subgeometry, error
  463. if (usedBoneMap.Size() > maxBones_)
  464. ErrorExit("Too many bones (limit " + String(maxBones_) + ") in submesh " + String(subMeshIndex + 1));
  465. // Write mapping of vertex buffer bone indices to original bone indices
  466. subGeometryLodLevel.boneMapping_.Resize(usedBoneMap.Size());
  467. for (HashMap<unsigned, unsigned>::Iterator j = usedBoneMap.Begin(); j != usedBoneMap.End(); ++j)
  468. subGeometryLodLevel.boneMapping_[j->second_] = j->first_;
  469. sorted = true;
  470. }
  471. for (HashMap<unsigned, PODVector<BoneWeightAssignment> >::Iterator i = subGeometryLodLevel.boneWeights_.Begin();
  472. i != subGeometryLodLevel.boneWeights_.End(); ++i)
  473. {
  474. // Sort the bone assigns by weight, if not sorted yet in bone remapping pass
  475. if (!sorted)
  476. Sort(i->second_.Begin(), i->second_.End(), CompareWeights);
  477. float totalWeight = 0.0f;
  478. float normalizationFactor = 0.0f;
  479. // Calculate normalization factor in case there are more than 4 blend weights, or they do not add up to 1
  480. for (unsigned j = 0; j < i->second_.Size() && j < 4; ++j)
  481. totalWeight += i->second_[j].weight_;
  482. if (totalWeight > 0.0f)
  483. normalizationFactor = 1.0f / totalWeight;
  484. for (unsigned j = 0; j < i->second_.Size() && j < 4; ++j)
  485. {
  486. vBuf->vertices_[i->first_].blendIndices_[j] = i->second_[j].boneIndex_;
  487. vBuf->vertices_[i->first_].blendWeights_[j] = i->second_[j].weight_ * normalizationFactor;
  488. }
  489. // If there are less than 4 blend weights, fill rest with zero
  490. for (unsigned j = i->second_.Size(); j < 4; ++j)
  491. {
  492. vBuf->vertices_[i->first_].blendIndices_[j] = 0;
  493. vBuf->vertices_[i->first_].blendWeights_[j] = 0.0f;
  494. }
  495. vBuf->vertices_[i->first_].hasBlendWeights_ = true;
  496. }
  497. }
  498. }
  499. else if (boneAssignments)
  500. PrintLine("No skeleton loaded, skipping skinning information");
  501. // Calculate center for the subgeometry
  502. Vector3 center = Vector3::ZERO;
  503. for (unsigned i = 0; i < iBuf->indices_.Size(); i += 3)
  504. {
  505. center += vBuf->vertices_[iBuf->indices_[i]].position_;
  506. center += vBuf->vertices_[iBuf->indices_[i + 1]].position_;
  507. center += vBuf->vertices_[iBuf->indices_[i + 2]].position_;
  508. }
  509. if (iBuf->indices_.Size())
  510. center /= (float)iBuf->indices_.Size();
  511. subGeometryCenters_.Push(center);
  512. indexStart += indices;
  513. vertexStart += vertices;
  514. OptimizeIndices(&subGeometryLodLevel, vBuf, iBuf);
  515. PrintLine("Processed submesh " + String(subMeshIndex + 1) + ": " + String(vertices) + " vertices " +
  516. String(triangles) + " triangles");
  517. Vector<ModelSubGeometryLodLevel> thisSubGeometry;
  518. thisSubGeometry.Push(subGeometryLodLevel);
  519. subGeometries_.Push(thisSubGeometry);
  520. subMesh = subMesh.GetNext("submesh");
  521. subMeshIndex++;
  522. }
  523. // Process LOD levels, if any
  524. XMLElement lods = root.GetChild("levelofdetail");
  525. if (lods)
  526. {
  527. try
  528. {
  529. // For now, support only generated LODs, where the vertices are the same
  530. XMLElement lod = lods.GetChild("lodgenerated");
  531. while (lod)
  532. {
  533. float distance = M_EPSILON;
  534. if (lod.HasAttribute("fromdepthsquared"))
  535. distance = sqrtf(lod.GetFloat("fromdepthsquared"));
  536. if (lod.HasAttribute("value"))
  537. distance = lod.GetFloat("value");
  538. XMLElement lodSubMesh = lod.GetChild("lodfacelist");
  539. while (lodSubMesh)
  540. {
  541. unsigned subMeshIndex = lodSubMesh.GetInt("submeshindex");
  542. unsigned triangles = lodSubMesh.GetInt("numfaces");
  543. ModelSubGeometryLodLevel newLodLevel;
  544. ModelSubGeometryLodLevel& originalLodLevel = subGeometries_[subMeshIndex][0];
  545. // Copy all initial values
  546. newLodLevel = originalLodLevel;
  547. ModelVertexBuffer* vBuf;
  548. ModelIndexBuffer* iBuf;
  549. if (useOneBuffer_)
  550. {
  551. vBuf = &vertexBuffers_[0];
  552. iBuf = &indexBuffers_[0];
  553. }
  554. else
  555. {
  556. vBuf = &vertexBuffers_[subMeshIndex];
  557. iBuf = &indexBuffers_[subMeshIndex];
  558. }
  559. unsigned indexStart = iBuf->indices_.Size();
  560. unsigned indexCount = triangles * 3;
  561. unsigned vertexStart = vertexStarts[subMeshIndex];
  562. newLodLevel.distance_ = distance;
  563. newLodLevel.indexStart_ = indexStart;
  564. newLodLevel.indexCount_ = indexCount;
  565. // Append indices to the original index buffer
  566. XMLElement triangle = lodSubMesh.GetChild("face");
  567. while (triangle)
  568. {
  569. unsigned v1 = triangle.GetInt("v1");
  570. unsigned v2 = triangle.GetInt("v2");
  571. unsigned v3 = triangle.GetInt("v3");
  572. iBuf->indices_.Push(v3 + vertexStart);
  573. iBuf->indices_.Push(v2 + vertexStart);
  574. iBuf->indices_.Push(v1 + vertexStart);
  575. triangle = triangle.GetNext("face");
  576. }
  577. OptimizeIndices(&newLodLevel, vBuf, iBuf);
  578. subGeometries_[subMeshIndex].Push(newLodLevel);
  579. PrintLine("Processed LOD level for submesh " + String(subMeshIndex + 1) + ": distance " + String(distance));
  580. lodSubMesh = lodSubMesh.GetNext("lodfacelist");
  581. }
  582. lod = lod.GetNext("lodgenerated");
  583. }
  584. }
  585. catch (...) {}
  586. }
  587. // Process poses/morphs
  588. // First find out all pose definitions
  589. if (exportMorphs)
  590. {
  591. try
  592. {
  593. Vector<XMLElement> poses;
  594. XMLElement posesRoot = root.GetChild("poses");
  595. if (posesRoot)
  596. {
  597. XMLElement pose = posesRoot.GetChild("pose");
  598. while (pose)
  599. {
  600. poses.Push(pose);
  601. pose = pose.GetNext("pose");
  602. }
  603. }
  604. // Then process animations using the poses
  605. XMLElement animsRoot = root.GetChild("animations");
  606. if (animsRoot)
  607. {
  608. XMLElement anim = animsRoot.GetChild("animation");
  609. while (anim)
  610. {
  611. String name = anim.GetAttribute("name");
  612. float length = anim.GetFloat("length");
  613. HashSet<unsigned> usedPoses;
  614. XMLElement tracks = anim.GetChild("tracks");
  615. if (tracks)
  616. {
  617. XMLElement track = tracks.GetChild("track");
  618. while (track)
  619. {
  620. XMLElement keyframes = track.GetChild("keyframes");
  621. if (keyframes)
  622. {
  623. XMLElement keyframe = keyframes.GetChild("keyframe");
  624. while (keyframe)
  625. {
  626. float time = keyframe.GetFloat("time");
  627. XMLElement poseref = keyframe.GetChild("poseref");
  628. // Get only the end pose
  629. if (poseref && time == length)
  630. usedPoses.Insert(poseref.GetInt("poseindex"));
  631. keyframe = keyframe.GetNext("keyframe");
  632. }
  633. }
  634. track = track.GetNext("track");
  635. }
  636. }
  637. if (usedPoses.Size())
  638. {
  639. ModelMorph newMorph;
  640. newMorph.name_ = name;
  641. if (useOneBuffer_)
  642. newMorph.buffers_.Resize(1);
  643. else
  644. newMorph.buffers_.Resize(usedPoses.Size());
  645. unsigned bufIndex = 0;
  646. for (HashSet<unsigned>::Iterator i = usedPoses.Begin(); i != usedPoses.End(); ++i)
  647. {
  648. XMLElement pose = poses[*i];
  649. unsigned targetSubMesh = pose.GetInt("index");
  650. XMLElement poseOffset = pose.GetChild("poseoffset");
  651. if (useOneBuffer_)
  652. newMorph.buffers_[bufIndex].vertexBuffer_ = 0;
  653. else
  654. newMorph.buffers_[bufIndex].vertexBuffer_ = targetSubMesh;
  655. newMorph.buffers_[bufIndex].elementMask_ = MASK_POSITION;
  656. ModelVertexBuffer* vBuf = &vertexBuffers_[newMorph.buffers_[bufIndex].vertexBuffer_];
  657. while (poseOffset)
  658. {
  659. // Convert from right- to left-handed
  660. unsigned vertexIndex = poseOffset.GetInt("index") + vertexStarts[targetSubMesh];
  661. float x = poseOffset.GetFloat("x");
  662. float y = poseOffset.GetFloat("y");
  663. float z = poseOffset.GetFloat("z");
  664. Vector3 vec(x, y, -z);
  665. if (vBuf->morphCount_ == 0)
  666. {
  667. vBuf->morphStart_ = vertexIndex;
  668. vBuf->morphCount_ = 1;
  669. }
  670. else
  671. {
  672. unsigned first = vBuf->morphStart_;
  673. unsigned last = first + vBuf->morphCount_ - 1;
  674. if (vertexIndex < first)
  675. first = vertexIndex;
  676. if (vertexIndex > last)
  677. last = vertexIndex;
  678. vBuf->morphStart_ = first;
  679. vBuf->morphCount_ = last - first + 1;
  680. }
  681. ModelVertex newVertex;
  682. newVertex.position_ = vec;
  683. newMorph.buffers_[bufIndex].vertices_.Push(MakePair(vertexIndex, newVertex));
  684. poseOffset = poseOffset.GetNext("poseoffset");
  685. }
  686. if (!useOneBuffer_)
  687. ++bufIndex;
  688. }
  689. morphs_.Push(newMorph);
  690. PrintLine("Processed morph " + name + " with " + String(usedPoses.Size()) + " sub-poses");
  691. }
  692. anim = anim.GetNext("animation");
  693. }
  694. }
  695. }
  696. catch (...) {}
  697. }
  698. // Check any of the buffers for vertices with missing blend weight assignments
  699. for (unsigned i = 0; i < vertexBuffers_.Size(); ++i)
  700. {
  701. if (vertexBuffers_[i].elementMask_ & MASK_BLENDWEIGHTS)
  702. {
  703. for (unsigned j = 0; j < vertexBuffers_[i].vertices_.Size(); ++j)
  704. if (!vertexBuffers_[i].vertices_[j].hasBlendWeights_)
  705. ErrorExit("Found a vertex with missing skinning information");
  706. }
  707. }
  708. // Tangent generation
  709. if (generateTangents)
  710. {
  711. for (unsigned i = 0; i < subGeometries_.Size(); ++i)
  712. {
  713. for (unsigned j = 0; j < subGeometries_[i].Size(); ++j)
  714. {
  715. ModelVertexBuffer& vBuf = vertexBuffers_[subGeometries_[i][j].vertexBuffer_];
  716. ModelIndexBuffer& iBuf = indexBuffers_[subGeometries_[i][j].indexBuffer_];
  717. unsigned indexStart = subGeometries_[i][j].indexStart_;
  718. unsigned indexCount = subGeometries_[i][j].indexCount_;
  719. // If already has tangents, do not regenerate
  720. if (vBuf.elementMask_ & MASK_TANGENT || vBuf.vertices_.Empty() || iBuf.indices_.Empty())
  721. continue;
  722. vBuf.elementMask_ |= MASK_TANGENT;
  723. if ((vBuf.elementMask_ & (MASK_POSITION | MASK_NORMAL | MASK_TEXCOORD1)) != (MASK_POSITION | MASK_NORMAL |
  724. MASK_TEXCOORD1))
  725. ErrorExit("To generate tangents, positions normals and texcoords are required");
  726. GenerateTangents(&vBuf.vertices_[0], sizeof(ModelVertex), &iBuf.indices_[0], sizeof(unsigned), indexStart,
  727. indexCount, offsetof(ModelVertex, normal_), offsetof(ModelVertex, texCoord1_), offsetof(ModelVertex,
  728. tangent_));
  729. PrintLine("Generated tangents");
  730. }
  731. }
  732. }
  733. }
  734. void WriteOutput(const String& outputFileName, bool exportAnimations, bool rotationsOnly, bool saveMaterialList)
  735. {
  736. // Begin serialization
  737. {
  738. File dest(context_);
  739. if (!dest.Open(outputFileName, FILE_WRITE))
  740. ErrorExit("Could not open output file " + outputFileName);
  741. // ID
  742. dest.WriteFileID("UMDL");
  743. // Vertexbuffers
  744. dest.WriteUInt(vertexBuffers_.Size());
  745. for (unsigned i = 0; i < vertexBuffers_.Size(); ++i)
  746. vertexBuffers_[i].WriteData(dest);
  747. // Indexbuffers
  748. dest.WriteUInt(indexBuffers_.Size());
  749. for (unsigned i = 0; i < indexBuffers_.Size(); ++i)
  750. indexBuffers_[i].WriteData(dest);
  751. // Subgeometries
  752. dest.WriteUInt(subGeometries_.Size());
  753. for (unsigned i = 0; i < subGeometries_.Size(); ++i)
  754. {
  755. // Write bone mapping info from the first LOD level. It does not change for further LODs
  756. dest.WriteUInt(subGeometries_[i][0].boneMapping_.Size());
  757. for (unsigned k = 0; k < subGeometries_[i][0].boneMapping_.Size(); ++k)
  758. dest.WriteUInt(subGeometries_[i][0].boneMapping_[k]);
  759. // Lod levels for this subgeometry
  760. dest.WriteUInt(subGeometries_[i].Size());
  761. for (unsigned j = 0; j < subGeometries_[i].Size(); ++j)
  762. {
  763. dest.WriteFloat(subGeometries_[i][j].distance_);
  764. dest.WriteUInt((unsigned)subGeometries_[i][j].primitiveType_);
  765. dest.WriteUInt(subGeometries_[i][j].vertexBuffer_);
  766. dest.WriteUInt(subGeometries_[i][j].indexBuffer_);
  767. dest.WriteUInt(subGeometries_[i][j].indexStart_);
  768. dest.WriteUInt(subGeometries_[i][j].indexCount_);
  769. }
  770. }
  771. // Morphs
  772. dest.WriteUInt(morphs_.Size());
  773. for (unsigned i = 0; i < morphs_.Size(); ++i)
  774. morphs_[i].WriteData(dest);
  775. // Skeleton
  776. dest.WriteUInt(bones_.Size());
  777. for (unsigned i = 0; i < bones_.Size(); ++i)
  778. {
  779. dest.WriteString(bones_[i].name_);
  780. dest.WriteUInt(bones_[i].parentIndex_);
  781. dest.WriteVector3(bones_[i].bindPosition_);
  782. dest.WriteQuaternion(bones_[i].bindRotation_);
  783. dest.WriteVector3(bones_[i].bindScale_);
  784. Matrix3x4 offsetMatrix(bones_[i].derivedPosition_, bones_[i].derivedRotation_, bones_[i].derivedScale_);
  785. offsetMatrix = offsetMatrix.Inverse();
  786. dest.Write(offsetMatrix.Data(), sizeof(Matrix3x4));
  787. dest.WriteUByte(bones_[i].collisionMask_);
  788. if (bones_[i].collisionMask_ & 1)
  789. dest.WriteFloat(bones_[i].radius_);
  790. if (bones_[i].collisionMask_ & 2)
  791. dest.WriteBoundingBox(bones_[i].boundingBox_);
  792. }
  793. // Bounding box
  794. dest.WriteBoundingBox(boundingBox_);
  795. // Geometry centers
  796. for (unsigned i = 0; i < subGeometryCenters_.Size(); ++i)
  797. dest.WriteVector3(subGeometryCenters_[i]);
  798. }
  799. if (saveMaterialList)
  800. {
  801. String materialListName = ReplaceExtension(outputFileName, ".txt");
  802. File listFile(context_);
  803. if (listFile.Open(materialListName, FILE_WRITE))
  804. {
  805. for (unsigned i = 0; i < materialNames_.Size(); ++i)
  806. {
  807. // Assume the materials will be located inside the standard Materials subdirectory
  808. listFile.WriteLine("Materials/" + ReplaceExtension(SanitateAssetName(materialNames_[i]), ".xml"));
  809. }
  810. }
  811. else
  812. PrintLine("Warning: could not write material list file " + materialListName);
  813. }
  814. XMLElement skeletonRoot = skelFile_->GetRoot("skeleton");
  815. if (skeletonRoot && exportAnimations)
  816. {
  817. // Go through animations
  818. XMLElement animationsRoot = skeletonRoot.GetChild("animations");
  819. if (animationsRoot)
  820. {
  821. XMLElement animation = animationsRoot.GetChild("animation");
  822. while (animation)
  823. {
  824. ModelAnimation newAnimation;
  825. newAnimation.name_ = animation.GetAttribute("name");
  826. newAnimation.length_ = animation.GetFloat("length");
  827. XMLElement tracksRoot = animation.GetChild("tracks");
  828. XMLElement track = tracksRoot.GetChild("track");
  829. while (track)
  830. {
  831. String trackName = track.GetAttribute("bone");
  832. ModelBone* bone = 0;
  833. for (unsigned i = 0; i < bones_.Size(); ++i)
  834. {
  835. if (bones_[i].name_ == trackName)
  836. {
  837. bone = &bones_[i];
  838. break;
  839. }
  840. }
  841. if (!bone)
  842. ErrorExit("Found animation track for unknown bone " + trackName);
  843. AnimationTrack newAnimationTrack;
  844. newAnimationTrack.name_ = trackName;
  845. if (!rotationsOnly)
  846. newAnimationTrack.channelMask_ = CHANNEL_POSITION | CHANNEL_ROTATION;
  847. else
  848. newAnimationTrack.channelMask_ = CHANNEL_ROTATION;
  849. XMLElement keyFramesRoot = track.GetChild("keyframes");
  850. XMLElement keyFrame = keyFramesRoot.GetChild("keyframe");
  851. while (keyFrame)
  852. {
  853. AnimationKeyFrame newKeyFrame;
  854. // Convert from right- to left-handed
  855. XMLElement position = keyFrame.GetChild("translate");
  856. float x = position.GetFloat("x");
  857. float y = position.GetFloat("y");
  858. float z = position.GetFloat("z");
  859. Vector3 pos(x, y, -z);
  860. XMLElement rotation = keyFrame.GetChild("rotate");
  861. XMLElement axis = rotation.GetChild("axis");
  862. float angle = -rotation.GetFloat("angle") * M_RADTODEG;
  863. x = axis.GetFloat("x");
  864. y = axis.GetFloat("y");
  865. z = axis.GetFloat("z");
  866. Vector3 axisVec(x, y, -z);
  867. Quaternion rot(angle, axisVec);
  868. // Transform from bind-pose relative into absolute
  869. pos = bone->bindPosition_ + bone->bindRotation_ * pos;
  870. rot = bone->bindRotation_ * rot;
  871. newKeyFrame.time_ = keyFrame.GetFloat("time");
  872. newKeyFrame.position_ = pos;
  873. newKeyFrame.rotation_ = rot;
  874. newAnimationTrack.keyFrames_.Push(newKeyFrame);
  875. keyFrame = keyFrame.GetNext("keyframe");
  876. }
  877. // Make sure keyframes are sorted from beginning to end
  878. Sort(newAnimationTrack.keyFrames_.Begin(), newAnimationTrack.keyFrames_.End(), CompareKeyFrames);
  879. // Do not add tracks with no keyframes
  880. if (newAnimationTrack.keyFrames_.Size())
  881. newAnimation.tracks_.Push(newAnimationTrack);
  882. track = track.GetNext("track");
  883. }
  884. // Write each animation into a separate file
  885. String animationFileName = outputFileName.Replaced(".mdl", "");
  886. animationFileName += "_" + newAnimation.name_ + ".ani";
  887. File dest(context_);
  888. if (!dest.Open(animationFileName, FILE_WRITE))
  889. ErrorExit("Could not open output file " + animationFileName);
  890. dest.WriteFileID("UANI");
  891. dest.WriteString(newAnimation.name_);
  892. dest.WriteFloat(newAnimation.length_);
  893. dest.WriteUInt(newAnimation.tracks_.Size());
  894. for (unsigned i = 0; i < newAnimation.tracks_.Size(); ++i)
  895. {
  896. AnimationTrack& track = newAnimation.tracks_[i];
  897. dest.WriteString(track.name_);
  898. dest.WriteUByte(track.channelMask_);
  899. dest.WriteUInt(track.keyFrames_.Size());
  900. for (unsigned j = 0; j < track.keyFrames_.Size(); ++j)
  901. {
  902. AnimationKeyFrame& keyFrame = track.keyFrames_[j];
  903. dest.WriteFloat(keyFrame.time_);
  904. if (track.channelMask_ & CHANNEL_POSITION)
  905. dest.WriteVector3(keyFrame.position_);
  906. if (track.channelMask_ & CHANNEL_ROTATION)
  907. dest.WriteQuaternion(keyFrame.rotation_);
  908. if (track.channelMask_ & CHANNEL_SCALE)
  909. dest.WriteVector3(keyFrame.scale_);
  910. }
  911. }
  912. animation = animation.GetNext("animation");
  913. PrintLine("Processed animation " + newAnimation.name_);
  914. }
  915. }
  916. }
  917. }
  918. void OptimizeIndices(ModelSubGeometryLodLevel* subGeom, ModelVertexBuffer* vb, ModelIndexBuffer* ib)
  919. {
  920. PODVector<Triangle> oldTriangles;
  921. PODVector<Triangle> newTriangles;
  922. if (subGeom->indexCount_ % 3)
  923. {
  924. PrintLine("Index count is not divisible by 3, skipping index optimization");
  925. return;
  926. }
  927. for (unsigned i = 0; i < vb->vertices_.Size(); ++i)
  928. {
  929. vb->vertices_[i].useCount_ = 0;
  930. vb->vertices_[i].cachePosition_ = -1;
  931. }
  932. for (unsigned i = subGeom->indexStart_; i < subGeom->indexStart_ + subGeom->indexCount_; i += 3)
  933. {
  934. Triangle triangle;
  935. triangle.v0_ = ib->indices_[i];
  936. triangle.v1_ = ib->indices_[i + 1];
  937. triangle.v2_ = ib->indices_[i + 2];
  938. vb->vertices_[triangle.v0_].useCount_++;
  939. vb->vertices_[triangle.v1_].useCount_++;
  940. vb->vertices_[triangle.v2_].useCount_++;
  941. oldTriangles.Push(triangle);
  942. }
  943. for (unsigned i = 0; i < vb->vertices_.Size(); ++i)
  944. CalculateScore(vb->vertices_[i]);
  945. PODVector<unsigned> vertexCache;
  946. while (oldTriangles.Size())
  947. {
  948. unsigned bestTriangle = M_MAX_UNSIGNED;
  949. float bestTriangleScore = -1.0f;
  950. // Find the best triangle at this point
  951. for (unsigned i = 0; i < oldTriangles.Size(); ++i)
  952. {
  953. Triangle& triangle = oldTriangles[i];
  954. float triangleScore =
  955. vb->vertices_[triangle.v0_].score_ +
  956. vb->vertices_[triangle.v1_].score_ +
  957. vb->vertices_[triangle.v2_].score_;
  958. if (triangleScore > bestTriangleScore)
  959. {
  960. bestTriangle = i;
  961. bestTriangleScore = triangleScore;
  962. }
  963. }
  964. if (bestTriangle == M_MAX_UNSIGNED)
  965. {
  966. PrintLine("Could not find next triangle, aborting index optimization");
  967. return;
  968. }
  969. // Add the best triangle
  970. Triangle triangleCopy = oldTriangles[bestTriangle];
  971. newTriangles.Push(triangleCopy);
  972. oldTriangles.Erase(oldTriangles.Begin() + bestTriangle);
  973. // Reduce the use count
  974. vb->vertices_[triangleCopy.v0_].useCount_--;
  975. vb->vertices_[triangleCopy.v1_].useCount_--;
  976. vb->vertices_[triangleCopy.v2_].useCount_--;
  977. // Model the LRU cache behaviour
  978. // Erase the triangle vertices from the middle of the cache, if they were there
  979. for (unsigned i = 0; i < vertexCache.Size(); ++i)
  980. {
  981. if ((vertexCache[i] == triangleCopy.v0_) ||
  982. (vertexCache[i] == triangleCopy.v1_) ||
  983. (vertexCache[i] == triangleCopy.v2_))
  984. {
  985. vertexCache.Erase(vertexCache.Begin() + i);
  986. --i;
  987. }
  988. }
  989. // Then push them to the front
  990. vertexCache.Insert(vertexCache.Begin(), triangleCopy.v0_);
  991. vertexCache.Insert(vertexCache.Begin(), triangleCopy.v1_);
  992. vertexCache.Insert(vertexCache.Begin(), triangleCopy.v2_);
  993. // Update positions & scores of all vertices in the cache
  994. // Give position -1 if vertex is going to be erased
  995. for (unsigned i = 0; i < vertexCache.Size(); ++i)
  996. {
  997. ModelVertex& vertex = vb->vertices_[vertexCache[i]];
  998. if (i >= VERTEX_CACHE_SIZE)
  999. vertex.cachePosition_ = -1;
  1000. else
  1001. vertex.cachePosition_ = i;
  1002. CalculateScore(vertex);
  1003. }
  1004. // Finally erase the extra vertices
  1005. if (vertexCache.Size() > VERTEX_CACHE_SIZE)
  1006. vertexCache.Resize(VERTEX_CACHE_SIZE);
  1007. }
  1008. // Rewrite the index data now
  1009. unsigned i = subGeom->indexStart_;
  1010. for (unsigned j = 0; j < newTriangles.Size(); ++j)
  1011. {
  1012. ib->indices_[i++] = newTriangles[j].v0_;
  1013. ib->indices_[i++] = newTriangles[j].v1_;
  1014. ib->indices_[i++] = newTriangles[j].v2_;
  1015. }
  1016. }
  1017. void CalculateScore(ModelVertex& vertex)
  1018. {
  1019. // Linear-Speed Vertex Cache Optimisation by Tom Forsyth from
  1020. // http://home.comcast.net/~tom_forsyth/papers/fast_vert_cache_opt.html
  1021. const float cacheDecayPower = 1.5f;
  1022. const float lastTriScore = 0.75f;
  1023. const float valenceBoostScale = 2.0f;
  1024. const float valenceBoostPower = 0.5f;
  1025. if (vertex.useCount_ == 0)
  1026. {
  1027. // No tri needs this vertex!
  1028. vertex.score_ = -1.0f;
  1029. return;
  1030. }
  1031. float score = 0.0f;
  1032. int cachePosition = vertex.cachePosition_;
  1033. if (cachePosition < 0)
  1034. {
  1035. // Vertex is not in FIFO cache - no score.
  1036. }
  1037. else
  1038. {
  1039. if (cachePosition < 3)
  1040. {
  1041. // This vertex was used in the last triangle,
  1042. // so it has a fixed score, whichever of the three
  1043. // it's in. Otherwise, you can get very different
  1044. // answers depending on whether you add
  1045. // the triangle 1,2,3 or 3,1,2 - which is silly.
  1046. score = lastTriScore;
  1047. }
  1048. else
  1049. {
  1050. // Points for being high in the cache.
  1051. const float scaler = 1.0f / (VERTEX_CACHE_SIZE - 3);
  1052. score = 1.0f - (cachePosition - 3) * scaler;
  1053. score = powf(score, cacheDecayPower);
  1054. }
  1055. }
  1056. // Bonus points for having a low number of tris still to
  1057. // use the vert, so we get rid of lone verts quickly.
  1058. float valenceBoost = powf((float)vertex.useCount_, -valenceBoostPower);
  1059. score += valenceBoostScale * valenceBoost;
  1060. vertex.score_ = score;
  1061. }
  1062. String SanitateAssetName(const String& name)
  1063. {
  1064. String fixedName = name;
  1065. fixedName.Replace("<", "");
  1066. fixedName.Replace(">", "");
  1067. fixedName.Replace("?", "");
  1068. fixedName.Replace("*", "");
  1069. fixedName.Replace(":", "");
  1070. fixedName.Replace("\"", "");
  1071. fixedName.Replace("/", "");
  1072. fixedName.Replace("\\", "");
  1073. fixedName.Replace("|", "");
  1074. return fixedName;
  1075. }