OgreXmlSerializer.cpp 31 KB

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