BVHLoader.cpp 19 KB

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