OgreSkeleton.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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) //will quit, if a Node is not a animationkey
  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. if(0==RotationAxis.x && 0==RotationAxis.y && 0==RotationAxis.z)//we have an invalid rotation axis
  193. {
  194. RotationAxis.x=1.0f;
  195. if(0!=RotationAngle)//if we don't rotate at all, the axis does not matter
  196. {
  197. DefaultLogger::get()->warn("Invalid Rotation Axis in Keyframe!");
  198. }
  199. }
  200. NewKeyframe.Rotation=aiQuaternion(RotationAxis, RotationAngle);
  201. }
  202. //Scaling:
  203. else if(string("scale")==SkeletonFile->getNodeName())
  204. {
  205. NewKeyframe.Scaling.x=GetAttribute<float>(SkeletonFile, "x");
  206. NewKeyframe.Scaling.y=GetAttribute<float>(SkeletonFile, "y");
  207. NewKeyframe.Scaling.z=GetAttribute<float>(SkeletonFile, "z");
  208. }
  209. //we suppose, that we read all attributes and this is a new keyframe or the end of the animation
  210. else
  211. break;
  212. }
  213. NewTrack.Keyframes.push_back(NewKeyframe);
  214. }
  215. NewAnimation.Tracks.push_back(NewTrack);
  216. }
  217. Animations.push_back(NewAnimation);
  218. }
  219. }
  220. //_____________________________________________________________________________
  221. }
  222. void OgreImporter::CreateAssimpSkeleton(const std::vector<Bone> &Bones, const std::vector<Animation> &/*Animations*/)
  223. {
  224. if(!m_CurrentScene->mRootNode)
  225. throw DeadlyImportError("No root node exists!!");
  226. if(0!=m_CurrentScene->mRootNode->mNumChildren)
  227. throw DeadlyImportError("Root Node already has childnodes!");
  228. //Createt the assimp bone hierarchy
  229. vector<aiNode*> RootBoneNodes;
  230. BOOST_FOREACH(const Bone &theBone, Bones)
  231. {
  232. if(-1==theBone.ParentId) //the bone is a root bone
  233. {
  234. //which will recursily add all other nodes
  235. RootBoneNodes.push_back(CreateAiNodeFromBone(theBone.Id, Bones, m_CurrentScene->mRootNode));
  236. }
  237. }
  238. if(RootBoneNodes.size() > 0)
  239. {
  240. m_CurrentScene->mRootNode->mNumChildren=RootBoneNodes.size();
  241. m_CurrentScene->mRootNode->mChildren=new aiNode*[RootBoneNodes.size()];
  242. memcpy(m_CurrentScene->mRootNode->mChildren, &RootBoneNodes[0], sizeof(aiNode*)*RootBoneNodes.size());
  243. }
  244. }
  245. void OgreImporter::PutAnimationsInScene(const std::vector<Bone> &Bones, const std::vector<Animation> &Animations)
  246. {
  247. //-----------------Create the Assimp Animations --------------------
  248. 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
  249. {
  250. m_CurrentScene->mNumAnimations=Animations.size();
  251. m_CurrentScene->mAnimations=new aiAnimation*[Animations.size()];
  252. for(unsigned int i=0; i<Animations.size(); ++i)//create all animations
  253. {
  254. aiAnimation* NewAnimation=new aiAnimation();
  255. NewAnimation->mName=Animations[i].Name;
  256. NewAnimation->mDuration=Animations[i].Length;
  257. NewAnimation->mTicksPerSecond=1.0f;
  258. //Create all tracks in this animation
  259. NewAnimation->mNumChannels=Animations[i].Tracks.size();
  260. NewAnimation->mChannels=new aiNodeAnim*[Animations[i].Tracks.size()];
  261. for(unsigned int j=0; j<Animations[i].Tracks.size(); ++j)
  262. {
  263. aiNodeAnim* NewNodeAnim=new aiNodeAnim();
  264. NewNodeAnim->mNodeName=Animations[i].Tracks[j].BoneName;
  265. //we need this, to acces the bones default pose, which we need to make keys absolute to the default bone pose
  266. vector<Bone>::const_iterator CurBone=find(Bones.begin(), Bones.end(), NewNodeAnim->mNodeName);
  267. aiMatrix4x4 t0, t1;
  268. aiMatrix4x4 DefBonePose=aiMatrix4x4::Translation(CurBone->Position, t1)
  269. * aiMatrix4x4::Rotation(CurBone->RotationAngle, CurBone->RotationAxis, t0);
  270. //Create the keyframe arrays...
  271. unsigned int KeyframeCount=Animations[i].Tracks[j].Keyframes.size();
  272. NewNodeAnim->mNumPositionKeys=KeyframeCount;
  273. NewNodeAnim->mNumRotationKeys=KeyframeCount;
  274. NewNodeAnim->mNumScalingKeys =KeyframeCount;
  275. NewNodeAnim->mPositionKeys=new aiVectorKey[KeyframeCount];
  276. NewNodeAnim->mRotationKeys=new aiQuatKey[KeyframeCount];
  277. NewNodeAnim->mScalingKeys =new aiVectorKey[KeyframeCount];
  278. //...and fill them
  279. for(unsigned int k=0; k<KeyframeCount; ++k)
  280. {
  281. aiMatrix4x4 t2, t3;
  282. //Create a matrix to transfrom a vector from the bones default pose to the bone bones in this animation key
  283. aiMatrix4x4 PoseToKey=
  284. aiMatrix4x4::Translation(Animations[i].Tracks[j].Keyframes[k].Position, t3) //pos
  285. * aiMatrix4x4(Animations[i].Tracks[j].Keyframes[k].Rotation.GetMatrix()) //rot
  286. * aiMatrix4x4::Scaling(Animations[i].Tracks[j].Keyframes[k].Scaling, t2); //scale
  287. //calculate the complete transformation from world space to bone space
  288. aiMatrix4x4 CompleteTransform=DefBonePose * PoseToKey;
  289. aiVector3D Pos;
  290. aiQuaternion Rot;
  291. aiVector3D Scale;
  292. CompleteTransform.Decompose(Scale, Rot, Pos);
  293. double Time=Animations[i].Tracks[j].Keyframes[k].Time;
  294. NewNodeAnim->mPositionKeys[k].mTime=Time;
  295. NewNodeAnim->mPositionKeys[k].mValue=Pos;
  296. NewNodeAnim->mRotationKeys[k].mTime=Time;
  297. NewNodeAnim->mRotationKeys[k].mValue=Rot;
  298. NewNodeAnim->mScalingKeys[k].mTime=Time;
  299. NewNodeAnim->mScalingKeys[k].mValue=Scale;
  300. }
  301. NewAnimation->mChannels[j]=NewNodeAnim;
  302. }
  303. m_CurrentScene->mAnimations[i]=NewAnimation;
  304. }
  305. }
  306. //TODO: Auf nicht vorhandene Animationskeys achten!
  307. //#pragma warning (s.o.)
  308. //__________________________________________________________________
  309. }
  310. aiNode* OgreImporter::CreateAiNodeFromBone(int BoneId, const std::vector<Bone> &Bones, aiNode* ParentNode)
  311. {
  312. //----Create the node for this bone and set its values-----
  313. aiNode* NewNode=new aiNode(Bones[BoneId].Name);
  314. NewNode->mParent=ParentNode;
  315. aiMatrix4x4 t0,t1;
  316. NewNode->mTransformation=
  317. aiMatrix4x4::Translation(Bones[BoneId].Position, t0)
  318. *aiMatrix4x4::Rotation(Bones[BoneId].RotationAngle, Bones[BoneId].RotationAxis, t1)
  319. ;
  320. //__________________________________________________________
  321. //---------- recursivly create all children Nodes: ----------
  322. NewNode->mNumChildren=Bones[BoneId].Children.size();
  323. NewNode->mChildren=new aiNode*[Bones[BoneId].Children.size()];
  324. for(unsigned int i=0; i<Bones[BoneId].Children.size(); ++i)
  325. {
  326. NewNode->mChildren[i]=CreateAiNodeFromBone(Bones[BoneId].Children[i], Bones, NewNode);
  327. }
  328. //____________________________________________________
  329. return NewNode;
  330. }
  331. void Bone::CalculateBoneToWorldSpaceMatrix(vector<Bone> &Bones)
  332. {
  333. //Calculate the matrix for this bone:
  334. aiMatrix4x4 t0,t1;
  335. aiMatrix4x4 Transf= aiMatrix4x4::Rotation(-RotationAngle, RotationAxis, t1)
  336. * aiMatrix4x4::Translation(-Position, t0);
  337. if(-1==ParentId)
  338. {
  339. BoneToWorldSpace=Transf;
  340. }
  341. else
  342. {
  343. BoneToWorldSpace=Transf*Bones[ParentId].BoneToWorldSpace;
  344. }
  345. //and recursivly for all children:
  346. BOOST_FOREACH(int theChildren, Children)
  347. {
  348. Bones[theChildren].CalculateBoneToWorldSpaceMatrix(Bones);
  349. }
  350. }
  351. }//namespace Ogre
  352. }//namespace Assimp
  353. #endif // !! ASSIMP_BUILD_NO_OGRE_IMPORTER