OgreXmlSerializer.cpp 29 KB

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