OgreXmlSerializer.cpp 31 KB

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