OgreSkeleton.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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.hpp"
  36. #include "TinyFormatter.h"
  37. using namespace std;
  38. namespace Assimp
  39. {
  40. namespace Ogre
  41. {
  42. void OgreImporter::LoadSkeleton(std::string FileName, vector<Bone> &Bones, vector<Animation> &Animations) const
  43. {
  44. const aiScene* const m_CurrentScene=this->m_CurrentScene;//make sure, that we can access but not change the scene
  45. (void)m_CurrentScene;
  46. //most likely the skeleton file will only end with .skeleton
  47. //But this is a xml reader, so we need: .skeleton.xml
  48. FileName+=".xml";
  49. DefaultLogger::get()->debug(string("Loading Skeleton: ")+FileName);
  50. //Open the File:
  51. boost::scoped_ptr<IOStream> File(m_CurrentIOHandler->Open(FileName));
  52. if(NULL==File.get())
  53. throw DeadlyImportError("Failed to open skeleton file "+FileName+".");
  54. //Read the Mesh File:
  55. boost::scoped_ptr<CIrrXML_IOStreamReader> mIOWrapper(new CIrrXML_IOStreamReader(File.get()));
  56. XmlReader* SkeletonFile = irr::io::createIrrXMLReader(mIOWrapper.get());
  57. if(!SkeletonFile)
  58. throw DeadlyImportError(string("Failed to create XML Reader for ")+FileName);
  59. //Quick note: Whoever read this should know this one thing: irrXml fucking sucks!!!
  60. XmlRead(SkeletonFile);
  61. if(string("skeleton")!=SkeletonFile->getNodeName())
  62. throw DeadlyImportError("No <skeleton> node in SkeletonFile: "+FileName);
  63. //------------------------------------load bones-----------------------------------------
  64. XmlRead(SkeletonFile);
  65. if(string("bones")!=SkeletonFile->getNodeName())
  66. throw DeadlyImportError("No bones node in skeleton "+FileName);
  67. XmlRead(SkeletonFile);
  68. while(string("bone")==SkeletonFile->getNodeName())
  69. {
  70. //TODO: Maybe we can have bone ids for the errrors, but normaly, they should never appear, so what....
  71. //read a new bone:
  72. Bone NewBone;
  73. NewBone.Id=GetAttribute<int>(SkeletonFile, "id");
  74. NewBone.Name=GetAttribute<string>(SkeletonFile, "name");
  75. //load the position:
  76. XmlRead(SkeletonFile);
  77. if(string("position")!=SkeletonFile->getNodeName())
  78. throw DeadlyImportError("Position is not first node in Bone!");
  79. NewBone.Position.x=GetAttribute<float>(SkeletonFile, "x");
  80. NewBone.Position.y=GetAttribute<float>(SkeletonFile, "y");
  81. NewBone.Position.z=GetAttribute<float>(SkeletonFile, "z");
  82. //Rotation:
  83. XmlRead(SkeletonFile);
  84. if(string("rotation")!=SkeletonFile->getNodeName())
  85. throw DeadlyImportError("Rotation is not the second node in Bone!");
  86. NewBone.RotationAngle=GetAttribute<float>(SkeletonFile, "angle");
  87. XmlRead(SkeletonFile);
  88. if(string("axis")!=SkeletonFile->getNodeName())
  89. throw DeadlyImportError("No axis specified for bone rotation!");
  90. NewBone.RotationAxis.x=GetAttribute<float>(SkeletonFile, "x");
  91. NewBone.RotationAxis.y=GetAttribute<float>(SkeletonFile, "y");
  92. NewBone.RotationAxis.z=GetAttribute<float>(SkeletonFile, "z");
  93. //append the newly loaded bone to the bone list
  94. Bones.push_back(NewBone);
  95. //Proceed to the next bone:
  96. XmlRead(SkeletonFile);
  97. }
  98. //The bones in the file a not neccesarly ordered by there id's so we do it now:
  99. std::sort(Bones.begin(), Bones.end());
  100. //now the id of each bone should be equal to its position in the vector:
  101. //so we do a simple check:
  102. {
  103. bool IdsOk=true;
  104. for(int i=0; i<static_cast<signed int>(Bones.size()); ++i)//i is signed, because all Id's are also signed!
  105. {
  106. if(Bones[i].Id!=i)
  107. IdsOk=false;
  108. }
  109. if(!IdsOk)
  110. throw DeadlyImportError("Bone Ids are not valid!"+FileName);
  111. }
  112. DefaultLogger::get()->debug((Formatter::format(),"Number of bones: ",Bones.size()));
  113. //________________________________________________________________________________
  114. //----------------------------load bonehierarchy--------------------------------
  115. if(string("bonehierarchy")!=SkeletonFile->getNodeName())
  116. throw DeadlyImportError("no bonehierarchy node in "+FileName);
  117. DefaultLogger::get()->debug("loading bonehierarchy...");
  118. XmlRead(SkeletonFile);
  119. while(string("boneparent")==SkeletonFile->getNodeName())
  120. {
  121. string Child, Parent;
  122. Child=GetAttribute<string>(SkeletonFile, "bone");
  123. Parent=GetAttribute<string>(SkeletonFile, "parent");
  124. unsigned int ChildId, ParentId;
  125. ChildId=find(Bones.begin(), Bones.end(), Child)->Id;
  126. ParentId=find(Bones.begin(), Bones.end(), Parent)->Id;
  127. Bones[ChildId].ParentId=ParentId;
  128. Bones[ParentId].Children.push_back(ChildId);
  129. XmlRead(SkeletonFile);//i once forget this line, which led to an endless loop, did i mentioned, that irrxml sucks??
  130. }
  131. //_____________________________________________________________________________
  132. //--------- Calculate the WorldToBoneSpace Matrix recursivly for all bones: ------------------
  133. BOOST_FOREACH(Bone theBone, Bones)
  134. {
  135. if(-1==theBone.ParentId) //the bone is a root bone
  136. {
  137. theBone.CalculateBoneToWorldSpaceMatrix(Bones);
  138. }
  139. }
  140. //_______________________________________________________________________
  141. //---------------------------load animations-----------------------------
  142. if(string("animations")==SkeletonFile->getNodeName())//animations are optional values
  143. {
  144. DefaultLogger::get()->debug("Loading Animations");
  145. XmlRead(SkeletonFile);
  146. while(string("animation")==SkeletonFile->getNodeName())
  147. {
  148. Animation NewAnimation;
  149. NewAnimation.Name=GetAttribute<string>(SkeletonFile, "name");
  150. NewAnimation.Length=GetAttribute<float>(SkeletonFile, "length");
  151. //Load all Tracks
  152. XmlRead(SkeletonFile);
  153. if(string("tracks")!=SkeletonFile->getNodeName())
  154. throw DeadlyImportError("no tracks node in animation");
  155. XmlRead(SkeletonFile);
  156. while(string("track")==SkeletonFile->getNodeName())
  157. {
  158. Track NewTrack;
  159. NewTrack.BoneName=GetAttribute<string>(SkeletonFile, "bone");
  160. //Load all keyframes;
  161. XmlRead(SkeletonFile);
  162. if(string("keyframes")!=SkeletonFile->getNodeName())
  163. throw DeadlyImportError("no keyframes node!");
  164. XmlRead(SkeletonFile);
  165. while(string("keyframe")==SkeletonFile->getNodeName())
  166. {
  167. Keyframe NewKeyframe;
  168. NewKeyframe.Time=GetAttribute<float>(SkeletonFile, "time");
  169. //loop over the attributes:
  170. while(true)
  171. {
  172. XmlRead(SkeletonFile);
  173. //If any property doesn't show up, it will keep its initialization value
  174. //Position:
  175. if(string("translate")==SkeletonFile->getNodeName())
  176. {
  177. NewKeyframe.Position.x=GetAttribute<float>(SkeletonFile, "x");
  178. NewKeyframe.Position.y=GetAttribute<float>(SkeletonFile, "y");
  179. NewKeyframe.Position.z=GetAttribute<float>(SkeletonFile, "z");
  180. }
  181. //Rotation:
  182. else if(string("rotate")!=SkeletonFile->getNodeName())
  183. {
  184. float RotationAngle=GetAttribute<float>(SkeletonFile, "angle");
  185. aiVector3D RotationAxis;
  186. XmlRead(SkeletonFile);
  187. if(string("axis")!=SkeletonFile->getNodeName())
  188. throw DeadlyImportError("No axis for keyframe rotation!");
  189. RotationAxis.x=GetAttribute<float>(SkeletonFile, "x");
  190. RotationAxis.y=GetAttribute<float>(SkeletonFile, "y");
  191. RotationAxis.z=GetAttribute<float>(SkeletonFile, "z");
  192. NewKeyframe.Rotation=aiQuaternion(RotationAxis, RotationAngle);
  193. }
  194. //Scaling:
  195. else if(string("scale")==SkeletonFile->getNodeName())
  196. {
  197. NewKeyframe.Scaling.x=GetAttribute<float>(SkeletonFile, "x");
  198. NewKeyframe.Scaling.y=GetAttribute<float>(SkeletonFile, "y");
  199. NewKeyframe.Scaling.z=GetAttribute<float>(SkeletonFile, "z");
  200. }
  201. //we suppose, that we read all attributes and this is a new keyframe or the end of the animation
  202. else
  203. break;
  204. }
  205. NewTrack.Keyframes.push_back(NewKeyframe);
  206. XmlRead(SkeletonFile);
  207. }
  208. NewAnimation.Tracks.push_back(NewTrack);
  209. }
  210. Animations.push_back(NewAnimation);
  211. }
  212. }
  213. //_____________________________________________________________________________
  214. }
  215. void OgreImporter::CreateAssimpSkeleton(const std::vector<Bone> &Bones, const std::vector<Animation> &/*Animations*/)
  216. {
  217. if(!m_CurrentScene->mRootNode)
  218. throw DeadlyImportError("No root node exists!!");
  219. if(0!=m_CurrentScene->mRootNode->mNumChildren)
  220. throw DeadlyImportError("Root Node already has childnodes!");
  221. //Createt the assimp bone hierarchy
  222. DefaultLogger::get()->debug("Root Bones");
  223. vector<aiNode*> RootBoneNodes;
  224. BOOST_FOREACH(Bone theBone, Bones)
  225. {
  226. if(-1==theBone.ParentId) //the bone is a root bone
  227. {
  228. DefaultLogger::get()->debug(theBone.Name);
  229. RootBoneNodes.push_back(CreateAiNodeFromBone(theBone.Id, Bones, m_CurrentScene->mRootNode));//which will recursily add all other nodes
  230. }
  231. }
  232. if (RootBoneNodes.size()) {
  233. m_CurrentScene->mRootNode->mNumChildren=RootBoneNodes.size();
  234. m_CurrentScene->mRootNode->mChildren=new aiNode*[RootBoneNodes.size()];
  235. memcpy(m_CurrentScene->mRootNode->mChildren, &RootBoneNodes[0], sizeof(aiNode*)*RootBoneNodes.size());
  236. }
  237. }
  238. void OgreImporter::PutAnimationsInScene(const std::vector<Bone> &Bones, const std::vector<Animation> &Animations)
  239. {
  240. //-----------------Create the Assimp Animations --------------------
  241. 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
  242. {
  243. m_CurrentScene->mNumAnimations=Animations.size();
  244. m_CurrentScene->mAnimations=new aiAnimation*[Animations.size()];
  245. for(unsigned int i=0; i<Animations.size(); ++i)//create all animations
  246. {
  247. aiAnimation* NewAnimation=new aiAnimation();
  248. NewAnimation->mName=Animations[i].Name;
  249. NewAnimation->mDuration=Animations[i].Length;
  250. NewAnimation->mTicksPerSecond=1.0f;
  251. //Create all tracks in this animation
  252. NewAnimation->mNumChannels=Animations[i].Tracks.size();
  253. NewAnimation->mChannels=new aiNodeAnim*[Animations[i].Tracks.size()];
  254. for(unsigned int j=0; j<Animations[i].Tracks.size(); ++j)
  255. {
  256. aiNodeAnim* NewNodeAnim=new aiNodeAnim();
  257. NewNodeAnim->mNodeName=Animations[i].Tracks[j].BoneName;
  258. //we need this, to acces the bones default pose, which we need to make keys absolute
  259. vector<Bone>::const_iterator CurBone=find(Bones.begin(), Bones.end(), NewNodeAnim->mNodeName);
  260. aiMatrix4x4 t0, t1;
  261. aiMatrix4x4 DefBonePose=//The default bone pose doesnt have a scaling value
  262. aiMatrix4x4::Rotation(CurBone->RotationAngle, CurBone->RotationAxis, t0)
  263. * aiMatrix4x4::Translation(CurBone->Position, t1);
  264. //Create the keyframe arrays...
  265. unsigned int KeyframeCount=Animations[i].Tracks[j].Keyframes.size();
  266. NewNodeAnim->mNumPositionKeys=KeyframeCount;
  267. NewNodeAnim->mPositionKeys=new aiVectorKey[KeyframeCount];
  268. NewNodeAnim->mNumRotationKeys=KeyframeCount;
  269. NewNodeAnim->mRotationKeys=new aiQuatKey[KeyframeCount];
  270. NewNodeAnim->mNumScalingKeys=KeyframeCount;
  271. NewNodeAnim->mScalingKeys=new aiVectorKey[KeyframeCount];
  272. //...and fill them
  273. for(unsigned int k=0; k<KeyframeCount; ++k)
  274. {
  275. aiMatrix4x4 t2, t3;
  276. //Create a matrix to transfrom a vector from the bones default pose to the bone bones in this animation key
  277. aiMatrix4x4 PoseToKey=aiMatrix4x4::Scaling(Animations[i].Tracks[j].Keyframes[k].Scaling, t2) //scale
  278. * aiMatrix4x4(Animations[i].Tracks[j].Keyframes[k].Rotation.GetMatrix()) //rot
  279. * aiMatrix4x4::Translation(Animations[i].Tracks[j].Keyframes[k].Position, t3); //pos
  280. //calculate the complete transformation from world space to bone space
  281. aiMatrix4x4 CompleteTransform=DefBonePose * PoseToKey;
  282. aiVector3D Pos;
  283. aiQuaternion Rot;
  284. aiVector3D Scale;
  285. CompleteTransform.Decompose(Scale, Rot, Pos);
  286. NewNodeAnim->mPositionKeys[k].mTime=Animations[i].Tracks[j].Keyframes[k].Time;
  287. NewNodeAnim->mPositionKeys[k].mValue=Pos;
  288. NewNodeAnim->mRotationKeys[k].mTime=Animations[i].Tracks[j].Keyframes[k].Time;
  289. NewNodeAnim->mRotationKeys[k].mValue=Rot;
  290. NewNodeAnim->mScalingKeys[k].mTime=Animations[i].Tracks[j].Keyframes[k].Time;
  291. NewNodeAnim->mScalingKeys[k].mValue=Scale;
  292. }
  293. NewAnimation->mChannels[j]=NewNodeAnim;
  294. }
  295. m_CurrentScene->mAnimations[i]=NewAnimation;
  296. }
  297. }
  298. //TODO: Auf nicht vorhandene Animationskeys achten!
  299. //#pragma warning (s.o.)
  300. //__________________________________________________________________
  301. }
  302. aiNode* OgreImporter::CreateAiNodeFromBone(int BoneId, const std::vector<Bone> &Bones, aiNode* ParentNode)
  303. {
  304. //----Create the node for this bone and set its values-----
  305. aiNode* NewNode=new aiNode(Bones[BoneId].Name);
  306. NewNode->mParent=ParentNode;
  307. aiMatrix4x4 t0,t1;
  308. //create a matrix from the transformation values of the ogre bone
  309. NewNode->mTransformation=aiMatrix4x4::Rotation(Bones[BoneId].RotationAngle, Bones[BoneId].RotationAxis, t1)
  310. * aiMatrix4x4::Translation(Bones[BoneId].Position, t0)
  311. ;
  312. //__________________________________________________________
  313. //---------- recursivly create all children Nodes: ----------
  314. NewNode->mNumChildren=Bones[BoneId].Children.size();
  315. NewNode->mChildren=new aiNode*[Bones[BoneId].Children.size()];
  316. for(unsigned int i=0; i<Bones[BoneId].Children.size(); ++i)
  317. {
  318. NewNode->mChildren[i]=CreateAiNodeFromBone(Bones[BoneId].Children[i], Bones, NewNode);
  319. }
  320. //____________________________________________________
  321. return NewNode;
  322. }
  323. void Bone::CalculateBoneToWorldSpaceMatrix(vector<Bone> &Bones)
  324. {
  325. //Calculate the matrix for this bone:
  326. aiMatrix4x4 t0,t1;
  327. aiMatrix4x4 Transf=aiMatrix4x4::Translation(-Position, t0)
  328. * aiMatrix4x4::Rotation(-RotationAngle, RotationAxis, t1)
  329. ;
  330. if(-1==ParentId)
  331. {
  332. BoneToWorldSpace=Transf;
  333. }
  334. else
  335. {
  336. BoneToWorldSpace=Transf*Bones[ParentId].BoneToWorldSpace;
  337. }
  338. //and recursivly for all children:
  339. BOOST_FOREACH(int theChildren, Children)
  340. {
  341. Bones[theChildren].CalculateBoneToWorldSpaceMatrix(Bones);
  342. }
  343. }
  344. }//namespace Ogre
  345. }//namespace Assimp
  346. #endif // !! ASSIMP_BUILD_NO_OGRE_IMPORTER