BVHLoader.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. /** Implementation of the BVH loader */
  2. /*
  3. ---------------------------------------------------------------------------
  4. Open Asset Import Library (ASSIMP)
  5. ---------------------------------------------------------------------------
  6. Copyright (c) 2006-2010, ASSIMP Development Team
  7. All rights reserved.
  8. Redistribution and use of this software in source and binary forms,
  9. with or without modification, are permitted provided that the following
  10. conditions are met:
  11. * Redistributions of source code must retain the above
  12. copyright notice, this list of conditions and the
  13. following disclaimer.
  14. * Redistributions in binary form must reproduce the above
  15. copyright notice, this list of conditions and the
  16. following disclaimer in the documentation and/or other
  17. materials provided with the distribution.
  18. * Neither the name of the ASSIMP team, nor the names of its
  19. contributors may be used to endorse or promote products
  20. derived from this software without specific prior
  21. written permission of the ASSIMP Development Team.
  22. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  23. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  24. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  25. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  26. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  27. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  28. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  29. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  30. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  31. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  32. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  33. ---------------------------------------------------------------------------
  34. */
  35. #include "AssimpPCH.h"
  36. #ifndef ASSIMP_BUILD_NO_BVH_IMPORTER
  37. #include "BVHLoader.h"
  38. #include "fast_atof.h"
  39. #include "SkeletonMeshBuilder.h"
  40. using namespace Assimp;
  41. // ------------------------------------------------------------------------------------------------
  42. // Constructor to be privately used by Importer
  43. BVHLoader::BVHLoader()
  44. {}
  45. // ------------------------------------------------------------------------------------------------
  46. // Destructor, private as well
  47. BVHLoader::~BVHLoader()
  48. {}
  49. // ------------------------------------------------------------------------------------------------
  50. // Returns whether the class can handle the format of the given file.
  51. bool BVHLoader::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool cs) const
  52. {
  53. // check file extension
  54. const std::string extension = GetExtension(pFile);
  55. if( extension == "bvh")
  56. return true;
  57. if ((!extension.length() || cs) && pIOHandler) {
  58. const char* tokens[] = {"HIERARCHY"};
  59. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
  60. }
  61. return false;
  62. }
  63. // ------------------------------------------------------------------------------------------------
  64. // Imports the given file into the given scene structure.
  65. void BVHLoader::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
  66. {
  67. mFileName = pFile;
  68. // read file into memory
  69. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile));
  70. if( file.get() == NULL)
  71. throw DeadlyImportError( "Failed to open file " + pFile + ".");
  72. size_t fileSize = file->FileSize();
  73. if( fileSize == 0)
  74. throw DeadlyImportError( "File is too small.");
  75. mBuffer.resize( fileSize);
  76. file->Read( &mBuffer.front(), 1, fileSize);
  77. // start reading
  78. mReader = mBuffer.begin();
  79. mLine = 1;
  80. ReadStructure( pScene);
  81. // build a dummy mesh for the skeleton so that we see something at least
  82. SkeletonMeshBuilder meshBuilder( pScene);
  83. // construct an animation from all the motion data we read
  84. CreateAnimation( pScene);
  85. }
  86. // ------------------------------------------------------------------------------------------------
  87. // Reads the file
  88. void BVHLoader::ReadStructure( aiScene* pScene)
  89. {
  90. // first comes hierarchy
  91. std::string header = GetNextToken();
  92. if( header != "HIERARCHY")
  93. ThrowException( "Expected header string \"HIERARCHY\".");
  94. ReadHierarchy( pScene);
  95. // then comes the motion data
  96. std::string motion = GetNextToken();
  97. if( motion != "MOTION")
  98. ThrowException( "Expected beginning of motion data \"MOTION\".");
  99. ReadMotion( pScene);
  100. }
  101. // ------------------------------------------------------------------------------------------------
  102. // Reads the hierarchy
  103. void BVHLoader::ReadHierarchy( aiScene* pScene)
  104. {
  105. std::string root = GetNextToken();
  106. if( root != "ROOT")
  107. ThrowException( "Expected root node \"ROOT\".");
  108. // Go read the hierarchy from here
  109. pScene->mRootNode = ReadNode();
  110. }
  111. // ------------------------------------------------------------------------------------------------
  112. // Reads a node and recursively its childs and returns the created node;
  113. aiNode* BVHLoader::ReadNode()
  114. {
  115. // first token is name
  116. std::string nodeName = GetNextToken();
  117. if( nodeName.empty() || nodeName == "{")
  118. ThrowException( boost::str( boost::format( "Expected node name, but found \"%s\".") % nodeName));
  119. // then an opening brace should follow
  120. std::string openBrace = GetNextToken();
  121. if( openBrace != "{")
  122. ThrowException( boost::str( boost::format( "Expected opening brace \"{\", but found \"%s\".") % openBrace));
  123. // Create a node
  124. aiNode* node = new aiNode( nodeName);
  125. std::vector<aiNode*> childNodes;
  126. // and create an bone entry for it
  127. mNodes.push_back( Node( node));
  128. Node& internNode = mNodes.back();
  129. // now read the node's contents
  130. while( 1)
  131. {
  132. std::string token = GetNextToken();
  133. // node offset to parent node
  134. if( token == "OFFSET")
  135. ReadNodeOffset( node);
  136. else if( token == "CHANNELS")
  137. ReadNodeChannels( internNode);
  138. else if( token == "JOINT")
  139. {
  140. // child node follows
  141. aiNode* child = ReadNode();
  142. child->mParent = node;
  143. childNodes.push_back( child);
  144. }
  145. else if( token == "End")
  146. {
  147. // The real symbol is "End Site". Second part comes in a separate token
  148. std::string siteToken = GetNextToken();
  149. if( siteToken != "Site")
  150. ThrowException( boost::str( boost::format( "Expected \"End Site\" keyword, but found \"%s %s\".") % token % siteToken));
  151. aiNode* child = ReadEndSite( nodeName);
  152. child->mParent = node;
  153. childNodes.push_back( child);
  154. }
  155. else if( token == "}")
  156. {
  157. // we're done with that part of the hierarchy
  158. break;
  159. } else
  160. {
  161. // everything else is a parse error
  162. ThrowException( boost::str( boost::format( "Unknown keyword \"%s\".") % token));
  163. }
  164. }
  165. // add the child nodes if there are any
  166. if( childNodes.size() > 0)
  167. {
  168. node->mNumChildren = childNodes.size();
  169. node->mChildren = new aiNode*[node->mNumChildren];
  170. std::copy( childNodes.begin(), childNodes.end(), node->mChildren);
  171. }
  172. // and return the sub-hierarchy we built here
  173. return node;
  174. }
  175. // ------------------------------------------------------------------------------------------------
  176. // Reads an end node and returns the created node.
  177. aiNode* BVHLoader::ReadEndSite( const std::string& pParentName)
  178. {
  179. // check opening brace
  180. std::string openBrace = GetNextToken();
  181. if( openBrace != "{")
  182. ThrowException( boost::str( boost::format( "Expected opening brace \"{\", but found \"%s\".") % openBrace));
  183. // Create a node
  184. aiNode* node = new aiNode( "EndSite_" + pParentName);
  185. // now read the node's contents. Only possible entry is "OFFSET"
  186. while( 1)
  187. {
  188. std::string token = GetNextToken();
  189. // end node's offset
  190. if( token == "OFFSET")
  191. {
  192. ReadNodeOffset( node);
  193. }
  194. else if( token == "}")
  195. {
  196. // we're done with the end node
  197. break;
  198. } else
  199. {
  200. // everything else is a parse error
  201. ThrowException( boost::str( boost::format( "Unknown keyword \"%s\".") % token));
  202. }
  203. }
  204. // and return the sub-hierarchy we built here
  205. return node;
  206. }
  207. // ------------------------------------------------------------------------------------------------
  208. // Reads a node offset for the given node
  209. void BVHLoader::ReadNodeOffset( aiNode* pNode)
  210. {
  211. // Offset consists of three floats to read
  212. aiVector3D offset;
  213. offset.x = GetNextTokenAsFloat();
  214. offset.y = GetNextTokenAsFloat();
  215. offset.z = GetNextTokenAsFloat();
  216. // build a transformation matrix from it
  217. pNode->mTransformation = aiMatrix4x4( 1.0f, 0.0f, 0.0f, offset.x, 0.0f, 1.0f, 0.0f, offset.y,
  218. 0.0f, 0.0f, 1.0f, offset.z, 0.0f, 0.0f, 0.0f, 1.0f);
  219. }
  220. // ------------------------------------------------------------------------------------------------
  221. // Reads the animation channels for the given node
  222. void BVHLoader::ReadNodeChannels( BVHLoader::Node& pNode)
  223. {
  224. // number of channels. Use the float reader because we're lazy
  225. float numChannelsFloat = GetNextTokenAsFloat();
  226. unsigned int numChannels = (unsigned int) numChannelsFloat;
  227. for( unsigned int a = 0; a < numChannels; a++)
  228. {
  229. std::string channelToken = GetNextToken();
  230. if( channelToken == "Xposition")
  231. pNode.mChannels.push_back( Channel_PositionX);
  232. else if( channelToken == "Yposition")
  233. pNode.mChannels.push_back( Channel_PositionY);
  234. else if( channelToken == "Zposition")
  235. pNode.mChannels.push_back( Channel_PositionZ);
  236. else if( channelToken == "Xrotation")
  237. pNode.mChannels.push_back( Channel_RotationX);
  238. else if( channelToken == "Yrotation")
  239. pNode.mChannels.push_back( Channel_RotationY);
  240. else if( channelToken == "Zrotation")
  241. pNode.mChannels.push_back( Channel_RotationZ);
  242. else
  243. ThrowException( boost::str( boost::format( "Invalid channel specifier \"%s\".") % channelToken));
  244. }
  245. }
  246. // ------------------------------------------------------------------------------------------------
  247. // Reads the motion data
  248. void BVHLoader::ReadMotion( aiScene* /*pScene*/)
  249. {
  250. // Read number of frames
  251. std::string tokenFrames = GetNextToken();
  252. if( tokenFrames != "Frames:")
  253. ThrowException( boost::str( boost::format( "Expected frame count \"Frames:\", but found \"%s\".") % tokenFrames));
  254. float numFramesFloat = GetNextTokenAsFloat();
  255. mAnimNumFrames = (unsigned int) numFramesFloat;
  256. // Read frame duration
  257. std::string tokenDuration1 = GetNextToken();
  258. std::string tokenDuration2 = GetNextToken();
  259. if( tokenDuration1 != "Frame" || tokenDuration2 != "Time:")
  260. ThrowException( boost::str( boost::format( "Expected frame duration \"Frame Time:\", but found \"%s %s\".") % tokenDuration1 % tokenDuration2));
  261. mAnimTickDuration = GetNextTokenAsFloat();
  262. // resize value vectors for each node
  263. for( std::vector<Node>::iterator it = mNodes.begin(); it != mNodes.end(); ++it)
  264. it->mChannelValues.reserve( it->mChannels.size() * mAnimNumFrames);
  265. // now read all the data and store it in the corresponding node's value vector
  266. for( unsigned int frame = 0; frame < mAnimNumFrames; ++frame)
  267. {
  268. // on each line read the values for all nodes
  269. for( std::vector<Node>::iterator it = mNodes.begin(); it != mNodes.end(); ++it)
  270. {
  271. // get as many values as the node has channels
  272. for( unsigned int c = 0; c < it->mChannels.size(); ++c)
  273. it->mChannelValues.push_back( GetNextTokenAsFloat());
  274. }
  275. // after one frame worth of values for all nodes there should be a newline, but we better don't rely on it
  276. }
  277. }
  278. // ------------------------------------------------------------------------------------------------
  279. // Retrieves the next token
  280. std::string BVHLoader::GetNextToken()
  281. {
  282. // skip any preceeding whitespace
  283. while( mReader != mBuffer.end())
  284. {
  285. if( !isspace( *mReader))
  286. break;
  287. // count lines
  288. if( *mReader == '\n')
  289. mLine++;
  290. ++mReader;
  291. }
  292. // collect all chars till the next whitespace. BVH is easy in respect to that.
  293. std::string token;
  294. while( mReader != mBuffer.end())
  295. {
  296. if( isspace( *mReader))
  297. break;
  298. token.push_back( *mReader);
  299. ++mReader;
  300. // little extra logic to make sure braces are counted correctly
  301. if( token == "{" || token == "}")
  302. break;
  303. }
  304. // empty token means end of file, which is just fine
  305. return token;
  306. }
  307. // ------------------------------------------------------------------------------------------------
  308. // Reads the next token as a float
  309. float BVHLoader::GetNextTokenAsFloat()
  310. {
  311. std::string token = GetNextToken();
  312. if( token.empty())
  313. ThrowException( "Unexpected end of file while trying to read a float");
  314. // check if the float is valid by testing if the atof() function consumed every char of the token
  315. const char* ctoken = token.c_str();
  316. float result = 0.0f;
  317. ctoken = fast_atof_move( ctoken, result);
  318. if( ctoken != token.c_str() + token.length())
  319. ThrowException( boost::str( boost::format( "Expected a floating point number, but found \"%s\".") % token));
  320. return result;
  321. }
  322. // ------------------------------------------------------------------------------------------------
  323. // Aborts the file reading with an exception
  324. void BVHLoader::ThrowException( const std::string& pError)
  325. {
  326. throw DeadlyImportError( boost::str( boost::format( "%s:%d - %s") % mFileName % mLine % pError));
  327. }
  328. // ------------------------------------------------------------------------------------------------
  329. // Constructs an animation for the motion data and stores it in the given scene
  330. void BVHLoader::CreateAnimation( aiScene* pScene)
  331. {
  332. // create the animation
  333. pScene->mNumAnimations = 1;
  334. pScene->mAnimations = new aiAnimation*[1];
  335. aiAnimation* anim = new aiAnimation;
  336. pScene->mAnimations[0] = anim;
  337. // put down the basic parameters
  338. anim->mName.Set( "Motion");
  339. anim->mTicksPerSecond = 1.0 / double( mAnimTickDuration);
  340. anim->mDuration = double( mAnimNumFrames - 1);
  341. // now generate the tracks for all nodes
  342. anim->mNumChannels = mNodes.size();
  343. anim->mChannels = new aiNodeAnim*[anim->mNumChannels];
  344. // FIX: set the array elements to NULL to ensure proper deletion if an exception is thrown
  345. for (unsigned int i = 0; i < anim->mNumChannels;++i)
  346. anim->mChannels[i] = NULL;
  347. for( unsigned int a = 0; a < anim->mNumChannels; a++)
  348. {
  349. const Node& node = mNodes[a];
  350. const std::string nodeName = std::string( node.mNode->mName.data );
  351. aiNodeAnim* nodeAnim = new aiNodeAnim;
  352. anim->mChannels[a] = nodeAnim;
  353. nodeAnim->mNodeName.Set( nodeName);
  354. // translational part, if given
  355. if( node.mChannels.size() == 6)
  356. {
  357. nodeAnim->mNumPositionKeys = mAnimNumFrames;
  358. nodeAnim->mPositionKeys = new aiVectorKey[mAnimNumFrames];
  359. aiVectorKey* poskey = nodeAnim->mPositionKeys;
  360. for( unsigned int fr = 0; fr < mAnimNumFrames; ++fr)
  361. {
  362. poskey->mTime = double( fr);
  363. // Now compute all translations in the right order
  364. for( unsigned int channel = 0; channel < 3; ++channel)
  365. {
  366. switch( node.mChannels[channel])
  367. {
  368. case Channel_PositionX: poskey->mValue.x = node.mChannelValues[fr * node.mChannels.size() + channel]; break;
  369. case Channel_PositionY: poskey->mValue.y = node.mChannelValues[fr * node.mChannels.size() + channel]; break;
  370. case Channel_PositionZ: poskey->mValue.z = node.mChannelValues[fr * node.mChannels.size() + channel]; break;
  371. default: throw DeadlyImportError( "Unexpected animation channel setup at node " + nodeName );
  372. }
  373. }
  374. ++poskey;
  375. }
  376. } else
  377. {
  378. // if no translation part is given, put a default sequence
  379. aiVector3D nodePos( node.mNode->mTransformation.a4, node.mNode->mTransformation.b4, node.mNode->mTransformation.c4);
  380. nodeAnim->mNumPositionKeys = 1;
  381. nodeAnim->mPositionKeys = new aiVectorKey[1];
  382. nodeAnim->mPositionKeys[0].mTime = 0.0;
  383. nodeAnim->mPositionKeys[0].mValue = nodePos;
  384. }
  385. // rotation part. Always present. First find value offsets
  386. {
  387. unsigned int rotOffset = 0;
  388. if( node.mChannels.size() == 6)
  389. {
  390. // Offset all further calculations
  391. rotOffset = 3;
  392. }
  393. // Then create the number of rotation keys
  394. nodeAnim->mNumRotationKeys = mAnimNumFrames;
  395. nodeAnim->mRotationKeys = new aiQuatKey[mAnimNumFrames];
  396. aiQuatKey* rotkey = nodeAnim->mRotationKeys;
  397. for( unsigned int fr = 0; fr < mAnimNumFrames; ++fr)
  398. {
  399. aiMatrix4x4 temp;
  400. aiMatrix3x3 rotMatrix;
  401. for( unsigned int channel = 0; channel < 3; ++channel)
  402. {
  403. // translate ZXY euler angels into a quaternion
  404. const float angle = node.mChannelValues[fr * node.mChannels.size() + rotOffset + channel] * float( AI_MATH_PI) / 180.0f;
  405. // Compute rotation transformations in the right order
  406. switch (node.mChannels[rotOffset+channel])
  407. {
  408. case Channel_RotationX: aiMatrix4x4::RotationX( angle, temp); rotMatrix *= aiMatrix3x3( temp); break;
  409. case Channel_RotationY: aiMatrix4x4::RotationY( angle, temp); rotMatrix *= aiMatrix3x3( temp); break;
  410. case Channel_RotationZ: aiMatrix4x4::RotationZ( angle, temp); rotMatrix *= aiMatrix3x3( temp); break;
  411. default: throw DeadlyImportError( "Unexpected animation channel setup at node " + nodeName );
  412. }
  413. }
  414. rotkey->mTime = double( fr);
  415. rotkey->mValue = aiQuaternion( rotMatrix);
  416. ++rotkey;
  417. }
  418. }
  419. // scaling part. Always just a default track
  420. {
  421. nodeAnim->mNumScalingKeys = 1;
  422. nodeAnim->mScalingKeys = new aiVectorKey[1];
  423. nodeAnim->mScalingKeys[0].mTime = 0.0;
  424. nodeAnim->mScalingKeys[0].mValue.Set( 1.0f, 1.0f, 1.0f);
  425. }
  426. }
  427. }
  428. #endif // !! ASSIMP_BUILD_NO_BVH_IMPORTER