You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1004 lines
29 KiB

  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2012, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. #include "OgreXmlSerializer.h"
  34. #include "OgreBinarySerializer.h"
  35. #include "OgreParsingUtils.h"
  36. #include "TinyFormatter.h"
  37. #ifndef ASSIMP_BUILD_NO_OGRE_IMPORTER
  38. // Define as 1 to get verbose logging.
  39. #define OGRE_XML_SERIALIZER_DEBUG 0
  40. namespace Assimp
  41. {
  42. namespace Ogre
  43. {
  44. void ThrowAttibuteError(const XmlReader* reader, const std::string &name, const std::string &error = "")
  45. {
  46. if (!error.empty())
  47. {
  48. throw DeadlyImportError(error + " in node '" + std::string(reader->getNodeName()) + "' and attribute '" + name + "'");
  49. }
  50. else
  51. {
  52. throw DeadlyImportError("Attribute '" + name + "' does not exist in node '" + std::string(reader->getNodeName()) + "'");
  53. }
  54. }
  55. template<>
  56. int32_t OgreXmlSerializer::ReadAttribute<int32_t>(const std::string &name) const
  57. {
  58. if (HasAttribute(name.c_str()))
  59. {
  60. return static_cast<int32_t>(m_reader->getAttributeValueAsInt(name.c_str()));
  61. }
  62. else
  63. {
  64. ThrowAttibuteError(m_reader, name);
  65. return 0;
  66. }
  67. }
  68. template<>
  69. uint32_t OgreXmlSerializer::ReadAttribute<uint32_t>(const std::string &name) const
  70. {
  71. if (HasAttribute(name.c_str()))
  72. {
  73. /** @note This is hackish. But we are never expecting unsigned values that go outside the
  74. int32_t range. Just monitor for negative numbers and kill the import. */
  75. int32_t temp = ReadAttribute<int32_t>(name);
  76. if (temp >= 0)
  77. {
  78. return static_cast<uint32_t>(temp);
  79. }
  80. else
  81. {
  82. ThrowAttibuteError(m_reader, name, "Found a negative number value where expecting a uint32_t value");
  83. }
  84. }
  85. else
  86. {
  87. ThrowAttibuteError(m_reader, name);
  88. }
  89. return 0;
  90. }
  91. template<>
  92. uint16_t OgreXmlSerializer::ReadAttribute<uint16_t>(const std::string &name) const
  93. {
  94. if (HasAttribute(name.c_str()))
  95. {
  96. return static_cast<uint16_t>(ReadAttribute<uint32_t>(name));
  97. }
  98. else
  99. {
  100. ThrowAttibuteError(m_reader, name);
  101. }
  102. return 0;
  103. }
  104. template<>
  105. float OgreXmlSerializer::ReadAttribute<float>(const std::string &name) const
  106. {
  107. if (HasAttribute(name.c_str()))
  108. {
  109. return m_reader->getAttributeValueAsFloat(name.c_str());
  110. }
  111. else
  112. {
  113. ThrowAttibuteError(m_reader, name);
  114. return 0;
  115. }
  116. }
  117. template<>
  118. std::string OgreXmlSerializer::ReadAttribute<std::string>(const std::string &name) const
  119. {
  120. const char* value = m_reader->getAttributeValue(name.c_str());
  121. if (value)
  122. {
  123. return std::string(value);
  124. }
  125. else
  126. {
  127. ThrowAttibuteError(m_reader, name);
  128. return "";
  129. }
  130. }
  131. template<>
  132. bool OgreXmlSerializer::ReadAttribute<bool>(const std::string &name) const
  133. {
  134. std::string value = Ogre::ToLower(ReadAttribute<std::string>(name));
  135. if (ASSIMP_stricmp(value, "true") == 0)
  136. {
  137. return true;
  138. }
  139. else if (ASSIMP_stricmp(value, "false") == 0)
  140. {
  141. return false;
  142. }
  143. else
  144. {
  145. ThrowAttibuteError(m_reader, name, "Boolean value is expected to be 'true' or 'false', encountered '" + value + "'");
  146. return false;
  147. }
  148. }
  149. bool OgreXmlSerializer::HasAttribute(const std::string &name) const
  150. {
  151. return (m_reader->getAttributeValue(name.c_str()) != 0);
  152. }
  153. std::string &OgreXmlSerializer::NextNode()
  154. {
  155. do
  156. {
  157. if (!m_reader->read())
  158. {
  159. m_currentNodeName = "";
  160. return m_currentNodeName;
  161. }
  162. }
  163. while(m_reader->getNodeType() != irr::io::EXN_ELEMENT);
  164. CurrentNodeName(true);
  165. #if (OGRE_XML_SERIALIZER_DEBUG == 1)
  166. DefaultLogger::get()->debug("<" + m_currentNodeName + ">");
  167. #endif
  168. return m_currentNodeName;
  169. }
  170. bool OgreXmlSerializer::CurrentNodeNameEquals(const std::string &name) const
  171. {
  172. return (ASSIMP_stricmp(m_currentNodeName, name) == 0);
  173. }
  174. std::string OgreXmlSerializer::CurrentNodeName(bool forceRead)
  175. {
  176. if (forceRead)
  177. m_currentNodeName = std::string(m_reader->getNodeName());
  178. return m_currentNodeName;
  179. }
  180. std::string &OgreXmlSerializer::SkipCurrentNode()
  181. {
  182. #if (OGRE_XML_SERIALIZER_DEBUG == 1)
  183. DefaultLogger::get()->debug("Skipping node <" + m_currentNodeName + ">");
  184. #endif
  185. for(;;)
  186. {
  187. if (!m_reader->read())
  188. {
  189. m_currentNodeName = "";
  190. return m_currentNodeName;
  191. }
  192. if (m_reader->getNodeType() != irr::io::EXN_ELEMENT_END)
  193. continue;
  194. else if (std::string(m_reader->getNodeName()) == m_currentNodeName)
  195. break;
  196. }
  197. return NextNode();
  198. }
  199. // Mesh XML constants
  200. // <mesh>
  201. const std::string nnMesh = "mesh";
  202. const std::string nnSharedGeometry = "sharedgeometry";
  203. const std::string nnSubMeshes = "submeshes";
  204. const std::string nnSubMesh = "submesh";
  205. const std::string nnSubMeshNames = "submeshnames";
  206. const std::string nnSkeletonLink = "skeletonlink";
  207. const std::string nnLOD = "levelofdetail";
  208. const std::string nnExtremes = "extremes";
  209. const std::string nnPoses = "poses";
  210. const std::string nnAnimations = "animations";
  211. // <submesh>
  212. const std::string nnFaces = "faces";
  213. const std::string nnFace = "face";
  214. const std::string nnGeometry = "geometry";
  215. const std::string nnTextures = "textures";
  216. // <mesh/submesh>
  217. const std::string nnBoneAssignments = "boneassignments";
  218. // <sharedgeometry/geometry>
  219. const std::string nnVertexBuffer = "vertexbuffer";
  220. // <vertexbuffer>
  221. const std::string nnVertex = "vertex";
  222. const std::string nnPosition = "position";
  223. const std::string nnNormal = "normal";
  224. const std::string nnTangent = "tangent";
  225. const std::string nnBinormal = "binormal";
  226. const std::string nnTexCoord = "texcoord";
  227. const std::string nnColorDiffuse = "colour_diffuse";
  228. const std::string nnColorSpecular = "colour_specular";
  229. // <boneassignments>
  230. const std::string nnVertexBoneAssignment = "vertexboneassignment";
  231. // Skeleton XML constants
  232. // <skeleton>
  233. const std::string nnSkeleton = "skeleton";
  234. const std::string nnBones = "bones";
  235. const std::string nnBoneHierarchy = "bonehierarchy";
  236. const std::string nnAnimationLinks = "animationlinks";
  237. // <bones>
  238. const std::string nnBone = "bone";
  239. const std::string nnRotation = "rotation";
  240. const std::string nnAxis = "axis";
  241. const std::string nnScale = "scale";
  242. // <bonehierarchy>
  243. const std::string nnBoneParent = "boneparent";
  244. // <animations>
  245. const std::string nnAnimation = "animation";
  246. const std::string nnTracks = "tracks";
  247. // <tracks>
  248. const std::string nnTrack = "track";
  249. const std::string nnKeyFrames = "keyframes";
  250. const std::string nnKeyFrame = "keyframe";
  251. const std::string nnTranslate = "translate";
  252. const std::string nnRotate = "rotate";
  253. // Common XML constants
  254. const std::string anX = "x";
  255. const std::string anY = "y";
  256. const std::string anZ = "z";
  257. // Mesh
  258. MeshXml *OgreXmlSerializer::ImportMesh(XmlReader *reader)
  259. {
  260. OgreXmlSerializer serializer(reader);
  261. MeshXml *mesh = new MeshXml();
  262. serializer.ReadMesh(mesh);
  263. return mesh;
  264. }
  265. void OgreXmlSerializer::ReadMesh(MeshXml *mesh)
  266. {
  267. if (NextNode() != nnMesh) {
  268. throw DeadlyImportError("Root node is <" + m_currentNodeName + "> expecting <mesh>");
  269. }
  270. DefaultLogger::get()->debug("Reading Mesh");
  271. NextNode();
  272. // Root level nodes
  273. while(m_currentNodeName == nnSharedGeometry ||
  274. m_currentNodeName == nnSubMeshes ||
  275. m_currentNodeName == nnSkeletonLink ||
  276. m_currentNodeName == nnBoneAssignments ||
  277. m_currentNodeName == nnLOD ||
  278. m_currentNodeName == nnSubMeshNames ||
  279. m_currentNodeName == nnExtremes ||
  280. m_currentNodeName == nnPoses ||
  281. m_currentNodeName == nnAnimations)
  282. {
  283. if (m_currentNodeName == nnSharedGeometry)
  284. {
  285. mesh->sharedVertexData = new VertexDataXml();
  286. ReadGeometry(mesh->sharedVertexData);
  287. }
  288. else if (m_currentNodeName == nnSubMeshes)
  289. {
  290. NextNode();
  291. while(m_currentNodeName == nnSubMesh) {
  292. ReadSubMesh(mesh);
  293. }
  294. }
  295. else if (m_currentNodeName == nnBoneAssignments)
  296. {
  297. ReadBoneAssignments(mesh->sharedVertexData);
  298. }
  299. else if (m_currentNodeName == nnSkeletonLink)
  300. {
  301. mesh->skeletonRef = ReadAttribute<std::string>("name");
  302. DefaultLogger::get()->debug("Read skeleton link " + mesh->skeletonRef);
  303. NextNode();
  304. }
  305. // Assimp incompatible/ignored nodes
  306. else
  307. SkipCurrentNode();
  308. }
  309. }
  310. void OgreXmlSerializer::ReadGeometry(VertexDataXml *dest)
  311. {
  312. dest->count = ReadAttribute<uint32_t>("vertexcount");
  313. DefaultLogger::get()->debug(Formatter::format() << " - Reading geometry of " << dest->count << " vertices");
  314. NextNode();
  315. while(m_currentNodeName == nnVertexBuffer) {
  316. ReadGeometryVertexBuffer(dest);
  317. }
  318. }
  319. void OgreXmlSerializer::ReadGeometryVertexBuffer(VertexDataXml *dest)
  320. {
  321. bool positions = (HasAttribute("positions") && ReadAttribute<bool>("positions"));
  322. bool normals = (HasAttribute("normals") && ReadAttribute<bool>("normals"));
  323. bool tangents = (HasAttribute("tangents") && ReadAttribute<bool>("tangents"));
  324. uint32_t uvs = (HasAttribute("texture_coords") ? ReadAttribute<uint32_t>("texture_coords") : 0);
  325. // Not having positions is a error only if a previous vertex buffer did not have them.
  326. if (!positions && !dest->HasPositions()) {
  327. throw DeadlyImportError("Vertex buffer does not contain positions!");
  328. }
  329. if (positions)
  330. {
  331. DefaultLogger::get()->debug(" - Contains positions");
  332. dest->positions.reserve(dest->count);
  333. }
  334. if (normals)
  335. {
  336. DefaultLogger::get()->debug(" - Contains normals");
  337. dest->normals.reserve(dest->count);
  338. }
  339. if (tangents)
  340. {
  341. DefaultLogger::get()->debug(" - Contains tangents");
  342. dest->tangents.reserve(dest->count);
  343. }
  344. if (uvs > 0)
  345. {
  346. DefaultLogger::get()->debug(Formatter::format() << " - Contains " << uvs << " texture coords");
  347. dest->uvs.resize(uvs);
  348. for(size_t i=0, len=dest->uvs.size(); i<len; ++i) {
  349. dest->uvs[i].reserve(dest->count);
  350. }
  351. }
  352. bool warnBinormal = true;
  353. bool warnColorDiffuse = true;
  354. bool warnColorSpecular = true;
  355. NextNode();
  356. while(m_currentNodeName == nnVertex ||
  357. m_currentNodeName == nnPosition ||
  358. m_currentNodeName == nnNormal ||
  359. m_currentNodeName == nnTangent ||
  360. m_currentNodeName == nnBinormal ||
  361. m_currentNodeName == nnTexCoord ||
  362. m_currentNodeName == nnColorDiffuse ||
  363. m_currentNodeName == nnColorSpecular)
  364. {
  365. if (m_currentNodeName == nnVertex) {
  366. NextNode();
  367. }
  368. /// @todo Implement nnBinormal, nnColorDiffuse and nnColorSpecular
  369. if (positions && m_currentNodeName == nnPosition)
  370. {
  371. aiVector3D pos;
  372. pos.x = ReadAttribute<float>(anX);
  373. pos.y = ReadAttribute<float>(anY);
  374. pos.z = ReadAttribute<float>(anZ);
  375. dest->positions.push_back(pos);
  376. }
  377. else if (normals && m_currentNodeName == nnNormal)
  378. {
  379. aiVector3D normal;
  380. normal.x = ReadAttribute<float>(anX);
  381. normal.y = ReadAttribute<float>(anY);
  382. normal.z = ReadAttribute<float>(anZ);
  383. dest->normals.push_back(normal);
  384. }
  385. else if (tangents && m_currentNodeName == nnTangent)
  386. {
  387. aiVector3D tangent;
  388. tangent.x = ReadAttribute<float>(anX);
  389. tangent.y = ReadAttribute<float>(anY);
  390. tangent.z = ReadAttribute<float>(anZ);
  391. dest->tangents.push_back(tangent);
  392. }
  393. else if (uvs > 0 && m_currentNodeName == nnTexCoord)
  394. {
  395. for(size_t i=0, len=dest->uvs.size(); i<len; ++i)
  396. {
  397. if (m_currentNodeName != nnTexCoord) {
  398. throw DeadlyImportError("Vertex buffer declared more UVs than can be found in a vertex");
  399. }
  400. aiVector3D uv;
  401. uv.x = ReadAttribute<float>("u");
  402. uv.y = (ReadAttribute<float>("v") * -1) + 1; // Flip UV from Ogre to Assimp form
  403. dest->uvs[i].push_back(uv);
  404. NextNode();
  405. }
  406. // Continue main loop as above already read next node
  407. continue;
  408. }
  409. else
  410. {
  411. /// @todo Remove this stuff once implemented. We only want to log warnings once per element.
  412. bool warn = true;
  413. if (m_currentNodeName == nnBinormal)
  414. {
  415. if (warnBinormal)
  416. {
  417. warnBinormal = false;
  418. }
  419. else
  420. {
  421. warn = false;
  422. }
  423. }
  424. else if (m_currentNodeName == nnColorDiffuse)
  425. {
  426. if (warnColorDiffuse)
  427. {
  428. warnColorDiffuse = false;
  429. }
  430. else
  431. {
  432. warn = false;
  433. }
  434. }
  435. else if (m_currentNodeName == nnColorSpecular)
  436. {
  437. if (warnColorSpecular)
  438. {
  439. warnColorSpecular = false;
  440. }
  441. else
  442. {
  443. warn = false;
  444. }
  445. }
  446. if (warn) {
  447. DefaultLogger::get()->warn("Vertex buffer attribute read not implemented for element: " + m_currentNodeName);
  448. }
  449. }
  450. // Advance
  451. NextNode();
  452. }
  453. // Sanity checks
  454. if (dest->positions.size() != dest->count) {
  455. throw DeadlyImportError(Formatter::format() << "Read only " << dest->positions.size() << " positions when should have read " << dest->count);
  456. }
  457. if (normals && dest->normals.size() != dest->count) {
  458. throw DeadlyImportError(Formatter::format() << "Read only " << dest->normals.size() << " normals when should have read " << dest->count);
  459. }
  460. if (tangents && dest->tangents.size() != dest->count) {
  461. throw DeadlyImportError(Formatter::format() << "Read only " << dest->tangents.size() << " tangents when should have read " << dest->count);
  462. }
  463. for(unsigned int i=0; i<dest->uvs.size(); ++i)
  464. {
  465. if (dest->uvs[i].size() != dest->count) {
  466. throw DeadlyImportError(Formatter::format() << "Read only " << dest->uvs[i].size()
  467. << " uvs for uv index " << i << " when should have read " << dest->count);
  468. }
  469. }
  470. }
  471. void OgreXmlSerializer::ReadSubMesh(MeshXml *mesh)
  472. {
  473. static const std::string anMaterial = "material";
  474. static const std::string anUseSharedVertices = "usesharedvertices";
  475. static const std::string anCount = "count";
  476. static const std::string anV1 = "v1";
  477. static const std::string anV2 = "v2";
  478. static const std::string anV3 = "v3";
  479. static const std::string anV4 = "v4";
  480. SubMeshXml* submesh = new SubMeshXml();
  481. if (HasAttribute(anMaterial)) {
  482. submesh->materialRef = ReadAttribute<std::string>(anMaterial);
  483. }
  484. if (HasAttribute(anUseSharedVertices)) {
  485. submesh->usesSharedVertexData = ReadAttribute<bool>(anUseSharedVertices);
  486. }
  487. DefaultLogger::get()->debug(Formatter::format() << "Reading SubMesh " << mesh->subMeshes.size());
  488. DefaultLogger::get()->debug(Formatter::format() << " - Material: '" << submesh->materialRef << "'");
  489. DefaultLogger::get()->debug(Formatter::format() << " - Uses shared geometry: " << (submesh->usesSharedVertexData ? "true" : "false"));
  490. // TODO: maybe we have always just 1 faces and 1 geometry and always in this order. this loop will only work correct, when the order
  491. // of faces and geometry changed, and not if we have more than one of one
  492. /// @todo Fix above comment with better read logic below
  493. bool quadWarned = false;
  494. NextNode();
  495. while(m_currentNodeName == nnFaces ||
  496. m_currentNodeName == nnGeometry ||
  497. m_currentNodeName == nnTextures ||
  498. m_currentNodeName == nnBoneAssignments)
  499. {
  500. if (m_currentNodeName == nnFaces)
  501. {
  502. submesh->indexData->faceCount = ReadAttribute<uint32_t>(anCount);
  503. submesh->indexData->faces.reserve(submesh->indexData->faceCount);
  504. NextNode();
  505. while(m_currentNodeName == nnFace)
  506. {
  507. aiFace face;
  508. face.mNumIndices = 3;
  509. face.mIndices = new unsigned int[3];
  510. face.mIndices[0] = ReadAttribute<uint32_t>(anV1);
  511. face.mIndices[1] = ReadAttribute<uint32_t>(anV2);
  512. face.mIndices[2] = ReadAttribute<uint32_t>(anV3);
  513. /// @todo Support quads if Ogre even supports them in XML (I'm not sure but I doubt it)
  514. if (!quadWarned && HasAttribute(anV4)) {
  515. DefaultLogger::get()->warn("Submesh <face> has quads with <v4>, only triangles are supported at the moment!");
  516. quadWarned = true;
  517. }
  518. submesh->indexData->faces.push_back(face);
  519. // Advance
  520. NextNode();
  521. }
  522. if (submesh->indexData->faces.size() == submesh->indexData->faceCount)
  523. {
  524. DefaultLogger::get()->debug(Formatter::format() << " - Faces " << submesh->indexData->faceCount);
  525. }
  526. else
  527. {
  528. throw DeadlyImportError(Formatter::format() << "Read only " << submesh->indexData->faces.size() << " faces when should have read " << submesh->indexData->faceCount);
  529. }
  530. }
  531. else if (m_currentNodeName == nnGeometry)
  532. {
  533. if (submesh->usesSharedVertexData) {
  534. throw DeadlyImportError("Found <geometry> in <submesh> when use shared geometry is true. Invalid mesh file.");
  535. }
  536. submesh->vertexData = new VertexDataXml();
  537. ReadGeometry(submesh->vertexData);
  538. }
  539. else if (m_currentNodeName == nnBoneAssignments)
  540. {
  541. ReadBoneAssignments(submesh->vertexData);
  542. }
  543. // Assimp incompatible/ignored nodes
  544. else
  545. SkipCurrentNode();
  546. }
  547. submesh->index = mesh->subMeshes.size();
  548. mesh->subMeshes.push_back(submesh);
  549. }
  550. void OgreXmlSerializer::ReadBoneAssignments(VertexDataXml *dest)
  551. {
  552. if (!dest) {
  553. throw DeadlyImportError("Cannot read bone assignments, vertex data is null.");
  554. }
  555. static const std::string anVertexIndex = "vertexindex";
  556. static const std::string anBoneIndex = "boneindex";
  557. static const std::string anWeight = "weight";
  558. std::set<uint32_t> influencedVertices;
  559. NextNode();
  560. while(m_currentNodeName == nnVertexBoneAssignment)
  561. {
  562. VertexBoneAssignment ba;
  563. ba.vertexIndex = ReadAttribute<uint32_t>(anVertexIndex);
  564. ba.boneIndex = ReadAttribute<uint16_t>(anBoneIndex);
  565. ba.weight = ReadAttribute<float>(anWeight);
  566. dest->boneAssignments.push_back(ba);
  567. influencedVertices.insert(ba.vertexIndex);
  568. NextNode();
  569. }
  570. /** Normalize bone weights.
  571. Some exporters wont care if the sum of all bone weights
  572. for a single vertex equals 1 or not, so validate here. */
  573. const float epsilon = 0.05f;
  574. for(std::set<uint32_t>::const_iterator iter=influencedVertices.begin(), end=influencedVertices.end(); iter != end; ++iter)
  575. {
  576. const uint32_t vertexIndex = (*iter);
  577. float sum = 0.0f;
  578. for (VertexBoneAssignmentList::const_iterator baIter=dest->boneAssignments.begin(), baEnd=dest->boneAssignments.end(); baIter != baEnd; ++baIter)
  579. {
  580. if (baIter->vertexIndex == vertexIndex)
  581. sum += baIter->weight;
  582. }
  583. if ((sum < (1.0f - epsilon)) || (sum > (1.0f + epsilon)))
  584. {
  585. for (VertexBoneAssignmentList::iterator baIter=dest->boneAssignments.begin(), baEnd=dest->boneAssignments.end(); baIter != baEnd; ++baIter)
  586. {
  587. if (baIter->vertexIndex == vertexIndex)
  588. baIter->weight /= sum;
  589. }
  590. }
  591. }
  592. DefaultLogger::get()->debug(Formatter::format() << " - " << dest->boneAssignments.size() << " bone assignments");
  593. }
  594. // Skeleton
  595. bool OgreXmlSerializer::ImportSkeleton(Assimp::IOSystem *pIOHandler, MeshXml *mesh)
  596. {
  597. if (!mesh || mesh->skeletonRef.empty())
  598. return false;
  599. // Highly unusual to see in read world cases but support
  600. // XML mesh referencing a binary skeleton file.
  601. if (EndsWith(mesh->skeletonRef, ".skeleton", false))
  602. {
  603. if (OgreBinarySerializer::ImportSkeleton(pIOHandler, mesh))
  604. return true;
  605. /** Last fallback if .skeleton failed to be read. Try reading from
  606. .skeleton.xml even if the XML file referenced a binary skeleton.
  607. @note This logic was in the previous version and I don't want to break
  608. old code that might depends on it. */
  609. mesh->skeletonRef = mesh->skeletonRef + ".xml";
  610. }
  611. XmlReaderPtr reader = OpenReader(pIOHandler, mesh->skeletonRef);
  612. if (!reader.get())
  613. return false;
  614. Skeleton *skeleton = new Skeleton();
  615. OgreXmlSerializer serializer(reader.get());
  616. serializer.ReadSkeleton(skeleton);
  617. mesh->skeleton = skeleton;
  618. return true;
  619. }
  620. bool OgreXmlSerializer::ImportSkeleton(Assimp::IOSystem *pIOHandler, Mesh *mesh)
  621. {
  622. if (!mesh || mesh->skeletonRef.empty())
  623. return false;
  624. XmlReaderPtr reader = OpenReader(pIOHandler, mesh->skeletonRef);
  625. if (!reader.get())
  626. return false;
  627. Skeleton *skeleton = new Skeleton();
  628. OgreXmlSerializer serializer(reader.get());
  629. serializer.ReadSkeleton(skeleton);
  630. mesh->skeleton = skeleton;
  631. return true;
  632. }
  633. XmlReaderPtr OgreXmlSerializer::OpenReader(Assimp::IOSystem *pIOHandler, const std::string &filename)
  634. {
  635. if (!EndsWith(filename, ".skeleton.xml", false))
  636. {
  637. DefaultLogger::get()->error("Imported Mesh is referencing to unsupported '" + filename + "' skeleton file.");
  638. return XmlReaderPtr();
  639. }
  640. if (!pIOHandler->Exists(filename))
  641. {
  642. DefaultLogger::get()->error("Failed to find skeleton file '" + filename + "' that is referenced by imported Mesh.");
  643. return XmlReaderPtr();
  644. }
  645. boost::scoped_ptr<IOStream> file(pIOHandler->Open(filename));
  646. if (!file.get()) {
  647. throw DeadlyImportError("Failed to open skeleton file " + filename);
  648. }
  649. boost::scoped_ptr<CIrrXML_IOStreamReader> stream(new CIrrXML_IOStreamReader(file.get()));
  650. XmlReaderPtr reader = XmlReaderPtr(irr::io::createIrrXMLReader(stream.get()));
  651. if (!reader.get()) {
  652. throw DeadlyImportError("Failed to create XML reader for skeleton file " + filename);
  653. }
  654. return reader;
  655. }
  656. void OgreXmlSerializer::ReadSkeleton(Skeleton *skeleton)
  657. {
  658. if (NextNode() != nnSkeleton) {
  659. throw DeadlyImportError("Root node is <" + m_currentNodeName + "> expecting <skeleton>");
  660. }
  661. DefaultLogger::get()->debug("Reading Skeleton");
  662. // Optional blend mode from root node
  663. if (HasAttribute("blendmode")) {
  664. skeleton->blendMode = (ToLower(ReadAttribute<std::string>("blendmode")) == "cumulative"
  665. ? Skeleton::ANIMBLEND_CUMULATIVE : Skeleton::ANIMBLEND_AVERAGE);
  666. }
  667. NextNode();
  668. // Root level nodes
  669. while(m_currentNodeName == nnBones ||
  670. m_currentNodeName == nnBoneHierarchy ||
  671. m_currentNodeName == nnAnimations ||
  672. m_currentNodeName == nnAnimationLinks)
  673. {
  674. if (m_currentNodeName == nnBones)
  675. ReadBones(skeleton);
  676. else if (m_currentNodeName == nnBoneHierarchy)
  677. ReadBoneHierarchy(skeleton);
  678. else if (m_currentNodeName == nnAnimations)
  679. ReadAnimations(skeleton);
  680. else
  681. SkipCurrentNode();
  682. }
  683. }
  684. void OgreXmlSerializer::ReadAnimations(Skeleton *skeleton)
  685. {
  686. if (skeleton->bones.empty()) {
  687. throw DeadlyImportError("Cannot read <animations> for a Skeleton without bones");
  688. }
  689. DefaultLogger::get()->debug(" - Animations");
  690. NextNode();
  691. while(m_currentNodeName == nnAnimation)
  692. {
  693. Animation *anim = new Animation(skeleton);
  694. anim->name = ReadAttribute<std::string>("name");
  695. anim->length = ReadAttribute<float>("length");
  696. if (NextNode() != nnTracks) {
  697. throw DeadlyImportError(Formatter::format() << "No <tracks> found in <animation> " << anim->name);
  698. }
  699. ReadAnimationTracks(anim);
  700. skeleton->animations.push_back(anim);
  701. DefaultLogger::get()->debug(Formatter::format() << " " << anim->name << " (" << anim->length << " sec, " << anim->tracks.size() << " tracks)");
  702. }
  703. }
  704. void OgreXmlSerializer::ReadAnimationTracks(Animation *dest)
  705. {
  706. NextNode();
  707. while(m_currentNodeName == nnTrack)
  708. {
  709. VertexAnimationTrack track;
  710. track.type = VertexAnimationTrack::VAT_TRANSFORM;
  711. track.boneName = ReadAttribute<std::string>("bone");
  712. if (NextNode() != nnKeyFrames) {
  713. throw DeadlyImportError(Formatter::format() << "No <keyframes> found in <track> " << dest->name);
  714. }
  715. ReadAnimationKeyFrames(dest, &track);
  716. dest->tracks.push_back(track);
  717. }
  718. }
  719. void OgreXmlSerializer::ReadAnimationKeyFrames(Animation *anim, VertexAnimationTrack *dest)
  720. {
  721. const aiVector3D zeroVec(0.f, 0.f, 0.f);
  722. NextNode();
  723. while(m_currentNodeName == nnKeyFrame)
  724. {
  725. TransformKeyFrame keyframe;
  726. keyframe.timePos = ReadAttribute<float>("time");
  727. NextNode();
  728. while(m_currentNodeName == nnTranslate || m_currentNodeName == nnRotate || m_currentNodeName == nnScale)
  729. {
  730. if (m_currentNodeName == nnTranslate)
  731. {
  732. keyframe.position.x = ReadAttribute<float>(anX);
  733. keyframe.position.y = ReadAttribute<float>(anY);
  734. keyframe.position.z = ReadAttribute<float>(anZ);
  735. }
  736. else if (m_currentNodeName == nnRotate)
  737. {
  738. float angle = ReadAttribute<float>("angle");
  739. if (NextNode() != nnAxis) {
  740. throw DeadlyImportError("No axis specified for keyframe rotation in animation " + anim->name);
  741. }
  742. aiVector3D axis;
  743. axis.x = ReadAttribute<float>(anX);
  744. axis.y = ReadAttribute<float>(anY);
  745. axis.z = ReadAttribute<float>(anZ);
  746. if (axis.Equal(zeroVec))
  747. {
  748. axis.x = 1.0f;
  749. if (angle != 0) {
  750. DefaultLogger::get()->warn("Found invalid a key frame with a zero rotation axis in animation: " + anim->name);
  751. }
  752. }
  753. keyframe.rotation = aiQuaternion(axis, angle);
  754. }
  755. else if (m_currentNodeName == nnScale)
  756. {
  757. keyframe.scale.x = ReadAttribute<float>(anX);
  758. keyframe.scale.y = ReadAttribute<float>(anY);
  759. keyframe.scale.z = ReadAttribute<float>(anZ);
  760. }
  761. NextNode();
  762. }
  763. dest->transformKeyFrames.push_back(keyframe);
  764. }
  765. }
  766. void OgreXmlSerializer::ReadBoneHierarchy(Skeleton *skeleton)
  767. {
  768. if (skeleton->bones.empty()) {
  769. throw DeadlyImportError("Cannot read <bonehierarchy> for a Skeleton without bones");
  770. }
  771. while(NextNode() == nnBoneParent)
  772. {
  773. const std::string name = ReadAttribute<std::string>("bone");
  774. const std::string parentName = ReadAttribute<std::string>("parent");
  775. Bone *bone = skeleton->BoneByName(name);
  776. Bone *parent = skeleton->BoneByName(parentName);
  777. if (bone && parent)
  778. parent->AddChild(bone);
  779. else
  780. throw DeadlyImportError("Failed to find bones for parenting: Child " + name + " for parent " + parentName);
  781. }
  782. // Calculate bone matrices for root bones. Recursively calculates their children.
  783. for (size_t i=0, len=skeleton->bones.size(); i<len; ++i)
  784. {
  785. Bone *bone = skeleton->bones[i];
  786. if (!bone->IsParented())
  787. bone->CalculateWorldMatrixAndDefaultPose(skeleton);
  788. }
  789. }
  790. bool BoneCompare(Bone *a, Bone *b)
  791. {
  792. return (a->id < b->id);
  793. }
  794. void OgreXmlSerializer::ReadBones(Skeleton *skeleton)
  795. {
  796. DefaultLogger::get()->debug(" - Bones");
  797. NextNode();
  798. while(m_currentNodeName == nnBone)
  799. {
  800. Bone *bone = new Bone();
  801. bone->id = ReadAttribute<uint16_t>("id");
  802. bone->name = ReadAttribute<std::string>("name");
  803. NextNode();
  804. while(m_currentNodeName == nnPosition ||
  805. m_currentNodeName == nnRotation ||
  806. m_currentNodeName == nnScale)
  807. {
  808. if (m_currentNodeName == nnPosition)
  809. {
  810. bone->position.x = ReadAttribute<float>(anX);
  811. bone->position.y = ReadAttribute<float>(anY);
  812. bone->position.z = ReadAttribute<float>(anZ);
  813. }
  814. else if (m_currentNodeName == nnRotation)
  815. {
  816. float angle = ReadAttribute<float>("angle");
  817. if (NextNode() != nnAxis) {
  818. throw DeadlyImportError(Formatter::format() << "No axis specified for bone rotation in bone " << bone->id);
  819. }
  820. aiVector3D axis;
  821. axis.x = ReadAttribute<float>(anX);
  822. axis.y = ReadAttribute<float>(anY);
  823. axis.z = ReadAttribute<float>(anZ);
  824. bone->rotation = aiQuaternion(axis, angle);
  825. }
  826. else if (m_currentNodeName == nnScale)
  827. {
  828. /// @todo Implement taking scale into account in matrix/pose calculations!
  829. if (HasAttribute("factor"))
  830. {
  831. float factor = ReadAttribute<float>("factor");
  832. bone->scale.Set(factor, factor, factor);
  833. }
  834. else
  835. {
  836. if (HasAttribute(anX))
  837. bone->scale.x = ReadAttribute<float>(anX);
  838. if (HasAttribute(anY))
  839. bone->scale.y = ReadAttribute<float>(anY);
  840. if (HasAttribute(anZ))
  841. bone->scale.z = ReadAttribute<float>(anZ);
  842. }
  843. }
  844. NextNode();
  845. }
  846. skeleton->bones.push_back(bone);
  847. }
  848. // Order bones by Id
  849. std::sort(skeleton->bones.begin(), skeleton->bones.end(), BoneCompare);
  850. // Validate that bone indexes are not skipped.
  851. /** @note Left this from original authors code, but not sure if this is strictly necessary
  852. as per the Ogre skeleton spec. It might be more that other (later) code in this imported does not break. */
  853. for (size_t i=0, len=skeleton->bones.size(); i<len; ++i)
  854. {
  855. Bone *b = skeleton->bones[i];
  856. DefaultLogger::get()->debug(Formatter::format() << " " << b->id << " " << b->name);
  857. if (b->id != static_cast<uint16_t>(i)) {
  858. throw DeadlyImportError(Formatter::format() << "Bone ids are not in sequence starting from 0. Missing index " << i);
  859. }
  860. }
  861. }
  862. } // Ogre
  863. } // Assimp
  864. #endif // ASSIMP_BUILD_NO_OGRE_IMPORTER