OgreXmlSerializer.cpp 33 KB

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