BVHLoader.cpp 19 KB

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