OgreXmlSerializer.cpp 27 KB

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