OgreSkeleton.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2012, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. #include "AssimpPCH.h"
  34. #ifndef ASSIMP_BUILD_NO_OGRE_IMPORTER
  35. #include "OgreImporter.h"
  36. #include "TinyFormatter.h"
  37. using namespace std;
  38. namespace Assimp
  39. {
  40. namespace Ogre
  41. {
  42. void OgreImporter::ReadSkeleton(const std::string &pFile, Assimp::IOSystem *pIOHandler, const aiScene *pScene,
  43. const std::string &skeletonFile, vector<Bone> &Bones, vector<Animation> &Animations) const
  44. {
  45. string filename = skeletonFile;
  46. if (EndsWith(filename, ".skeleton"))
  47. {
  48. DefaultLogger::get()->warn("Mesh is referencing a Ogre binary skeleton. Parsing binary Ogre assets is not supported at the moment. Trying to find .skeleton.xml file instead.");
  49. filename += ".xml";
  50. }
  51. if (!pIOHandler->Exists(filename))
  52. {
  53. DefaultLogger::get()->error("Failed to find skeleton file '" + filename + "', skeleton will be missing.");
  54. return;
  55. }
  56. boost::scoped_ptr<IOStream> file(pIOHandler->Open(filename));
  57. if (!file.get())
  58. throw DeadlyImportError("Failed to open skeleton file " + filename);
  59. boost::scoped_ptr<CIrrXML_IOStreamReader> stream(new CIrrXML_IOStreamReader(file.get()));
  60. XmlReader* reader = irr::io::createIrrXMLReader(stream.get());
  61. if (!reader)
  62. throw DeadlyImportError("Failed to create XML reader for skeleton file " + filename);
  63. DefaultLogger::get()->debug("Reading skeleton '" + filename + "'");
  64. // Root
  65. NextNode(reader);
  66. if (!CurrentNodeNameEquals(reader, "skeleton"))
  67. throw DeadlyImportError("Root node is not <skeleton> but <" + string(reader->getNodeName()) + "> in " + filename);
  68. // Bones
  69. NextNode(reader);
  70. if (!CurrentNodeNameEquals(reader, "bones"))
  71. throw DeadlyImportError("No <bones> node in skeleton " + skeletonFile);
  72. NextNode(reader);
  73. while(CurrentNodeNameEquals(reader, "bone"))
  74. {
  75. //TODO: Maybe we can have bone ids for the errrors, but normaly, they should never appear, so what....
  76. /// @todo What does the above mean?
  77. Bone bone;
  78. bone.Id = GetAttribute<int>(reader, "id");
  79. bone.Name = GetAttribute<string>(reader, "name");
  80. NextNode(reader);
  81. if (!CurrentNodeNameEquals(reader, "position"))
  82. throw DeadlyImportError("Position is not first node in Bone!");
  83. bone.Position.x = GetAttribute<float>(reader, "x");
  84. bone.Position.y = GetAttribute<float>(reader, "y");
  85. bone.Position.z = GetAttribute<float>(reader, "z");
  86. NextNode(reader);
  87. if (!CurrentNodeNameEquals(reader, "rotation"))
  88. throw DeadlyImportError("Rotation is not the second node in Bone!");
  89. bone.RotationAngle = GetAttribute<float>(reader, "angle");
  90. NextNode(reader);
  91. if (!CurrentNodeNameEquals(reader, "axis"))
  92. throw DeadlyImportError("No axis specified for bone rotation!");
  93. bone.RotationAxis.x = GetAttribute<float>(reader, "x");
  94. bone.RotationAxis.y = GetAttribute<float>(reader, "y");
  95. bone.RotationAxis.z = GetAttribute<float>(reader, "z");
  96. Bones.push_back(bone);
  97. NextNode(reader);
  98. }
  99. // Order bones by Id
  100. std::sort(Bones.begin(), Bones.end());
  101. // Validate that bone indexes are not skipped.
  102. /** @note Left this from original authors code, but not sure if this is strictly necessary
  103. as per the Ogre skeleton spec. It might be more that other (later) code in this imported does not break. */
  104. for (size_t i=0, len=Bones.size(); i<len; ++i)
  105. if (static_cast<int>(Bones[i].Id) != static_cast<int>(i))
  106. throw DeadlyImportError("Bone Ids are not in sequence in " + skeletonFile);
  107. DefaultLogger::get()->debug(Formatter::format() << " - Bones " << Bones.size());
  108. // Bone hierarchy
  109. if (!CurrentNodeNameEquals(reader, "bonehierarchy"))
  110. throw DeadlyImportError("No <bonehierarchy> node found after <bones> in " + skeletonFile);
  111. NextNode(reader);
  112. while(CurrentNodeNameEquals(reader, "boneparent"))
  113. {
  114. string childName = GetAttribute<string>(reader, "bone");
  115. string parentName = GetAttribute<string>(reader, "parent");
  116. vector<Bone>::iterator iterChild = find(Bones.begin(), Bones.end(), childName);
  117. vector<Bone>::iterator iterParent = find(Bones.begin(), Bones.end(), parentName);
  118. if (iterChild != Bones.end() && iterParent != Bones.end())
  119. {
  120. iterChild->ParentId = iterParent->Id;
  121. iterParent->Children.push_back(iterChild->Id);
  122. }
  123. else
  124. DefaultLogger::get()->warn("Failed to find bones for parenting: Child " + childName + " Parent " + parentName);
  125. NextNode(reader);
  126. }
  127. // Calculate bone matrices for root bones. Recursively does their children.
  128. BOOST_FOREACH(Bone &theBone, Bones)
  129. {
  130. if (!theBone.IsParented())
  131. theBone.CalculateBoneToWorldSpaceMatrix(Bones);
  132. }
  133. aiVector3D zeroVec(0.f, 0.f, 0.f);
  134. // Animations
  135. if (CurrentNodeNameEquals(reader, "animations"))
  136. {
  137. DefaultLogger::get()->debug(" - Animations");
  138. NextNode(reader);
  139. while(CurrentNodeNameEquals(reader, "animation"))
  140. {
  141. Animation animation;
  142. animation.Name = GetAttribute<string>(reader, "name");
  143. animation.Length = GetAttribute<float>(reader, "length");
  144. // Tracks
  145. NextNode(reader);
  146. if (!CurrentNodeNameEquals(reader, "tracks"))
  147. throw DeadlyImportError("No <tracks> node found in animation '" + animation.Name + "' in " + skeletonFile);
  148. NextNode(reader);
  149. while(CurrentNodeNameEquals(reader, "track"))
  150. {
  151. Track track;
  152. track.BoneName = GetAttribute<string>(reader, "bone");
  153. // Keyframes
  154. NextNode(reader);
  155. if (!CurrentNodeNameEquals(reader, "keyframes"))
  156. throw DeadlyImportError("No <keyframes> node found in a track in animation '" + animation.Name + "' in " + skeletonFile);
  157. NextNode(reader);
  158. while(CurrentNodeNameEquals(reader, "keyframe"))
  159. {
  160. KeyFrame keyFrame;
  161. keyFrame.Time = GetAttribute<float>(reader, "time");
  162. NextNode(reader);
  163. while(CurrentNodeNameEquals(reader, "translate") || CurrentNodeNameEquals(reader, "rotate") || CurrentNodeNameEquals(reader, "scale"))
  164. {
  165. if (CurrentNodeNameEquals(reader, "translate"))
  166. {
  167. keyFrame.Position.x = GetAttribute<float>(reader, "x");
  168. keyFrame.Position.y = GetAttribute<float>(reader, "y");
  169. keyFrame.Position.z = GetAttribute<float>(reader, "z");
  170. }
  171. else if (CurrentNodeNameEquals(reader, "rotate"))
  172. {
  173. float angle = GetAttribute<float>(reader, "angle");
  174. NextNode(reader);
  175. if(string("axis")!=reader->getNodeName())
  176. throw DeadlyImportError("No axis for keyframe rotation!");
  177. aiVector3D axis;
  178. axis.x = GetAttribute<float>(reader, "x");
  179. axis.y = GetAttribute<float>(reader, "y");
  180. axis.z = GetAttribute<float>(reader, "z");
  181. if (axis.Equal(zeroVec))
  182. {
  183. axis.x = 1.0f;
  184. if (angle != 0)
  185. DefaultLogger::get()->warn("Found invalid a key frame with a zero rotation axis in animation '" + animation.Name + "'");
  186. }
  187. keyFrame.Rotation = aiQuaternion(axis, angle);
  188. }
  189. else if (CurrentNodeNameEquals(reader, "scale"))
  190. {
  191. keyFrame.Scaling.x = GetAttribute<float>(reader, "x");
  192. keyFrame.Scaling.y = GetAttribute<float>(reader, "y");
  193. keyFrame.Scaling.z = GetAttribute<float>(reader, "z");
  194. }
  195. NextNode(reader);
  196. }
  197. track.Keyframes.push_back(keyFrame);
  198. }
  199. animation.Tracks.push_back(track);
  200. }
  201. Animations.push_back(animation);
  202. DefaultLogger::get()->debug(Formatter::format() << " " << animation.Name << " (" << animation.Length << " sec, " << animation.Tracks.size() << " tracks)");
  203. }
  204. }
  205. }
  206. void OgreImporter::CreateAssimpSkeleton(aiScene *pScene, const std::vector<Bone> &Bones, const std::vector<Animation> &/*Animations*/)
  207. {
  208. if(!pScene->mRootNode)
  209. throw DeadlyImportError("No root node exists!!");
  210. if(0!=pScene->mRootNode->mNumChildren)
  211. throw DeadlyImportError("Root Node already has childnodes!");
  212. //Createt the assimp bone hierarchy
  213. vector<aiNode*> RootBoneNodes;
  214. BOOST_FOREACH(const Bone &theBone, Bones)
  215. {
  216. if(-1==theBone.ParentId) //the bone is a root bone
  217. {
  218. //which will recursily add all other nodes
  219. RootBoneNodes.push_back(CreateAiNodeFromBone(theBone.Id, Bones, pScene->mRootNode));
  220. }
  221. }
  222. if(RootBoneNodes.size() > 0)
  223. {
  224. pScene->mRootNode->mNumChildren=RootBoneNodes.size();
  225. pScene->mRootNode->mChildren=new aiNode*[RootBoneNodes.size()];
  226. memcpy(pScene->mRootNode->mChildren, &RootBoneNodes[0], sizeof(aiNode*)*RootBoneNodes.size());
  227. }
  228. }
  229. void OgreImporter::PutAnimationsInScene(aiScene *pScene, const std::vector<Bone> &Bones, const std::vector<Animation> &Animations)
  230. {
  231. // TODO: Auf nicht vorhandene Animationskeys achten!
  232. // @todo Pay attention to non-existing animation Keys (google translated from above german comment)
  233. if(Animations.size()>0)//Maybe the model had only a skeleton and no animations. (If it also has no skeleton, this function would'nt have been called
  234. {
  235. pScene->mNumAnimations=Animations.size();
  236. pScene->mAnimations=new aiAnimation*[Animations.size()];
  237. for(unsigned int i=0; i<Animations.size(); ++i)//create all animations
  238. {
  239. aiAnimation* NewAnimation=new aiAnimation();
  240. NewAnimation->mName=Animations[i].Name;
  241. NewAnimation->mDuration=Animations[i].Length;
  242. NewAnimation->mTicksPerSecond=1.0f;
  243. //Create all tracks in this animation
  244. NewAnimation->mNumChannels=Animations[i].Tracks.size();
  245. NewAnimation->mChannels=new aiNodeAnim*[Animations[i].Tracks.size()];
  246. for(unsigned int j=0; j<Animations[i].Tracks.size(); ++j)
  247. {
  248. aiNodeAnim* NewNodeAnim=new aiNodeAnim();
  249. NewNodeAnim->mNodeName=Animations[i].Tracks[j].BoneName;
  250. //we need this, to acces the bones default pose, which we need to make keys absolute to the default bone pose
  251. vector<Bone>::const_iterator CurBone=find(Bones.begin(), Bones.end(), NewNodeAnim->mNodeName);
  252. aiMatrix4x4 t0, t1;
  253. aiMatrix4x4 DefBonePose=aiMatrix4x4::Translation(CurBone->Position, t1)
  254. * aiMatrix4x4::Rotation(CurBone->RotationAngle, CurBone->RotationAxis, t0);
  255. //Create the keyframe arrays...
  256. unsigned int KeyframeCount=Animations[i].Tracks[j].Keyframes.size();
  257. NewNodeAnim->mNumPositionKeys=KeyframeCount;
  258. NewNodeAnim->mNumRotationKeys=KeyframeCount;
  259. NewNodeAnim->mNumScalingKeys =KeyframeCount;
  260. NewNodeAnim->mPositionKeys=new aiVectorKey[KeyframeCount];
  261. NewNodeAnim->mRotationKeys=new aiQuatKey[KeyframeCount];
  262. NewNodeAnim->mScalingKeys =new aiVectorKey[KeyframeCount];
  263. //...and fill them
  264. for(unsigned int k=0; k<KeyframeCount; ++k)
  265. {
  266. aiMatrix4x4 t2, t3;
  267. //Create a matrix to transfrom a vector from the bones default pose to the bone bones in this animation key
  268. aiMatrix4x4 PoseToKey=
  269. aiMatrix4x4::Translation(Animations[i].Tracks[j].Keyframes[k].Position, t3) //pos
  270. * aiMatrix4x4(Animations[i].Tracks[j].Keyframes[k].Rotation.GetMatrix()) //rot
  271. * aiMatrix4x4::Scaling(Animations[i].Tracks[j].Keyframes[k].Scaling, t2); //scale
  272. //calculate the complete transformation from world space to bone space
  273. aiMatrix4x4 CompleteTransform=DefBonePose * PoseToKey;
  274. aiVector3D Pos;
  275. aiQuaternion Rot;
  276. aiVector3D Scale;
  277. CompleteTransform.Decompose(Scale, Rot, Pos);
  278. double Time=Animations[i].Tracks[j].Keyframes[k].Time;
  279. NewNodeAnim->mPositionKeys[k].mTime=Time;
  280. NewNodeAnim->mPositionKeys[k].mValue=Pos;
  281. NewNodeAnim->mRotationKeys[k].mTime=Time;
  282. NewNodeAnim->mRotationKeys[k].mValue=Rot;
  283. NewNodeAnim->mScalingKeys[k].mTime=Time;
  284. NewNodeAnim->mScalingKeys[k].mValue=Scale;
  285. }
  286. NewAnimation->mChannels[j]=NewNodeAnim;
  287. }
  288. pScene->mAnimations[i]=NewAnimation;
  289. }
  290. }
  291. }
  292. aiNode* OgreImporter::CreateAiNodeFromBone(int BoneId, const std::vector<Bone> &Bones, aiNode* ParentNode)
  293. {
  294. //----Create the node for this bone and set its values-----
  295. aiNode* NewNode=new aiNode(Bones[BoneId].Name);
  296. NewNode->mParent=ParentNode;
  297. aiMatrix4x4 t0,t1;
  298. NewNode->mTransformation=
  299. aiMatrix4x4::Translation(Bones[BoneId].Position, t0)
  300. *aiMatrix4x4::Rotation(Bones[BoneId].RotationAngle, Bones[BoneId].RotationAxis, t1)
  301. ;
  302. //__________________________________________________________
  303. //---------- recursivly create all children Nodes: ----------
  304. NewNode->mNumChildren=Bones[BoneId].Children.size();
  305. NewNode->mChildren=new aiNode*[Bones[BoneId].Children.size()];
  306. for(unsigned int i=0; i<Bones[BoneId].Children.size(); ++i)
  307. {
  308. NewNode->mChildren[i]=CreateAiNodeFromBone(Bones[BoneId].Children[i], Bones, NewNode);
  309. }
  310. //____________________________________________________
  311. return NewNode;
  312. }
  313. void Bone::CalculateBoneToWorldSpaceMatrix(vector<Bone> &Bones)
  314. {
  315. aiMatrix4x4 t0, t1;
  316. aiMatrix4x4 transform = aiMatrix4x4::Rotation(-RotationAngle, RotationAxis, t1) * aiMatrix4x4::Translation(-Position, t0);
  317. if (!IsParented())
  318. BoneToWorldSpace = transform;
  319. else
  320. BoneToWorldSpace = transform * Bones[ParentId].BoneToWorldSpace;
  321. // Recursively for all children now that the parent matrix has been calculated.
  322. BOOST_FOREACH(int childId, Children)
  323. {
  324. Bones[childId].CalculateBoneToWorldSpaceMatrix(Bones);
  325. }
  326. }
  327. } // Ogre
  328. } // Assimp
  329. #endif // ASSIMP_BUILD_NO_OGRE_IMPORTER