BVHLoader.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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. std::string siteToken;
  166. while( 1)
  167. {
  168. std::string token = GetNextToken();
  169. // node offset to parent node
  170. if( token == "OFFSET")
  171. ReadNodeOffset( node);
  172. else if( token == "CHANNELS")
  173. ReadNodeChannels( internNode);
  174. else if( token == "JOINT")
  175. {
  176. // child node follows
  177. aiNode* child = ReadNode();
  178. child->mParent = node;
  179. childNodes.push_back( child);
  180. }
  181. else if( token == "End")
  182. {
  183. // The real symbol is "End Site". Second part comes in a separate token
  184. siteToken.clear();
  185. siteToken = GetNextToken();
  186. if( siteToken != "Site")
  187. ThrowException( format() << "Expected \"End Site\" keyword, but found \"" << token << " " << siteToken << "\"." );
  188. aiNode* child = ReadEndSite( nodeName);
  189. child->mParent = node;
  190. childNodes.push_back( child);
  191. }
  192. else if( token == "}")
  193. {
  194. // we're done with that part of the hierarchy
  195. break;
  196. } else
  197. {
  198. // everything else is a parse error
  199. ThrowException( format() << "Unknown keyword \"" << token << "\"." );
  200. }
  201. }
  202. // add the child nodes if there are any
  203. if( childNodes.size() > 0)
  204. {
  205. node->mNumChildren = static_cast<unsigned int>(childNodes.size());
  206. node->mChildren = new aiNode*[node->mNumChildren];
  207. std::copy( childNodes.begin(), childNodes.end(), node->mChildren);
  208. }
  209. // and return the sub-hierarchy we built here
  210. return node;
  211. }
  212. // ------------------------------------------------------------------------------------------------
  213. // Reads an end node and returns the created node.
  214. aiNode* BVHLoader::ReadEndSite( const std::string& pParentName)
  215. {
  216. // check opening brace
  217. std::string openBrace = GetNextToken();
  218. if( openBrace != "{")
  219. ThrowException( format() << "Expected opening brace \"{\", but found \"" << openBrace << "\".");
  220. // Create a node
  221. aiNode* node = new aiNode( "EndSite_" + pParentName);
  222. // now read the node's contents. Only possible entry is "OFFSET"
  223. std::string token;
  224. while( 1) {
  225. token.clear();
  226. token = GetNextToken();
  227. // end node's offset
  228. if( token == "OFFSET") {
  229. ReadNodeOffset( node);
  230. } else if( token == "}") {
  231. // we're done with the end node
  232. break;
  233. } else {
  234. // everything else is a parse error
  235. ThrowException( format() << "Unknown keyword \"" << token << "\"." );
  236. }
  237. }
  238. // and return the sub-hierarchy we built here
  239. return node;
  240. }
  241. // ------------------------------------------------------------------------------------------------
  242. // Reads a node offset for the given node
  243. void BVHLoader::ReadNodeOffset( aiNode* pNode)
  244. {
  245. // Offset consists of three floats to read
  246. aiVector3D offset;
  247. offset.x = GetNextTokenAsFloat();
  248. offset.y = GetNextTokenAsFloat();
  249. offset.z = GetNextTokenAsFloat();
  250. // build a transformation matrix from it
  251. pNode->mTransformation = aiMatrix4x4( 1.0f, 0.0f, 0.0f, offset.x,
  252. 0.0f, 1.0f, 0.0f, offset.y,
  253. 0.0f, 0.0f, 1.0f, offset.z,
  254. 0.0f, 0.0f, 0.0f, 1.0f);
  255. }
  256. // ------------------------------------------------------------------------------------------------
  257. // Reads the animation channels for the given node
  258. void BVHLoader::ReadNodeChannels( BVHLoader::Node& pNode)
  259. {
  260. // number of channels. Use the float reader because we're lazy
  261. float numChannelsFloat = GetNextTokenAsFloat();
  262. unsigned int numChannels = (unsigned int) numChannelsFloat;
  263. for( unsigned int a = 0; a < numChannels; a++)
  264. {
  265. std::string channelToken = GetNextToken();
  266. if( channelToken == "Xposition")
  267. pNode.mChannels.push_back( Channel_PositionX);
  268. else if( channelToken == "Yposition")
  269. pNode.mChannels.push_back( Channel_PositionY);
  270. else if( channelToken == "Zposition")
  271. pNode.mChannels.push_back( Channel_PositionZ);
  272. else if( channelToken == "Xrotation")
  273. pNode.mChannels.push_back( Channel_RotationX);
  274. else if( channelToken == "Yrotation")
  275. pNode.mChannels.push_back( Channel_RotationY);
  276. else if( channelToken == "Zrotation")
  277. pNode.mChannels.push_back( Channel_RotationZ);
  278. else
  279. ThrowException( format() << "Invalid channel specifier \"" << channelToken << "\"." );
  280. }
  281. }
  282. // ------------------------------------------------------------------------------------------------
  283. // Reads the motion data
  284. void BVHLoader::ReadMotion( aiScene* /*pScene*/)
  285. {
  286. // Read number of frames
  287. std::string tokenFrames = GetNextToken();
  288. if( tokenFrames != "Frames:")
  289. ThrowException( format() << "Expected frame count \"Frames:\", but found \"" << tokenFrames << "\".");
  290. float numFramesFloat = GetNextTokenAsFloat();
  291. mAnimNumFrames = (unsigned int) numFramesFloat;
  292. // Read frame duration
  293. std::string tokenDuration1 = GetNextToken();
  294. std::string tokenDuration2 = GetNextToken();
  295. if( tokenDuration1 != "Frame" || tokenDuration2 != "Time:")
  296. ThrowException( format() << "Expected frame duration \"Frame Time:\", but found \"" << tokenDuration1 << " " << tokenDuration2 << "\"." );
  297. mAnimTickDuration = GetNextTokenAsFloat();
  298. // resize value vectors for each node
  299. for( std::vector<Node>::iterator it = mNodes.begin(); it != mNodes.end(); ++it)
  300. it->mChannelValues.reserve( it->mChannels.size() * mAnimNumFrames);
  301. // now read all the data and store it in the corresponding node's value vector
  302. for( unsigned int frame = 0; frame < mAnimNumFrames; ++frame)
  303. {
  304. // on each line read the values for all nodes
  305. for( std::vector<Node>::iterator it = mNodes.begin(); it != mNodes.end(); ++it)
  306. {
  307. // get as many values as the node has channels
  308. for( unsigned int c = 0; c < it->mChannels.size(); ++c)
  309. it->mChannelValues.push_back( GetNextTokenAsFloat());
  310. }
  311. // after one frame worth of values for all nodes there should be a newline, but we better don't rely on it
  312. }
  313. }
  314. // ------------------------------------------------------------------------------------------------
  315. // Retrieves the next token
  316. std::string BVHLoader::GetNextToken()
  317. {
  318. // skip any preceding whitespace
  319. while( mReader != mBuffer.end())
  320. {
  321. if( !isspace( *mReader))
  322. break;
  323. // count lines
  324. if( *mReader == '\n')
  325. mLine++;
  326. ++mReader;
  327. }
  328. // collect all chars till the next whitespace. BVH is easy in respect to that.
  329. std::string token;
  330. while( mReader != mBuffer.end())
  331. {
  332. if( isspace( *mReader))
  333. break;
  334. token.push_back( *mReader);
  335. ++mReader;
  336. // little extra logic to make sure braces are counted correctly
  337. if( token == "{" || token == "}")
  338. break;
  339. }
  340. // empty token means end of file, which is just fine
  341. return token;
  342. }
  343. // ------------------------------------------------------------------------------------------------
  344. // Reads the next token as a float
  345. float BVHLoader::GetNextTokenAsFloat()
  346. {
  347. std::string token = GetNextToken();
  348. if( token.empty())
  349. ThrowException( "Unexpected end of file while trying to read a float");
  350. // check if the float is valid by testing if the atof() function consumed every char of the token
  351. const char* ctoken = token.c_str();
  352. float result = 0.0f;
  353. ctoken = fast_atoreal_move<float>( ctoken, result);
  354. if( ctoken != token.c_str() + token.length())
  355. ThrowException( format() << "Expected a floating point number, but found \"" << token << "\"." );
  356. return result;
  357. }
  358. // ------------------------------------------------------------------------------------------------
  359. // Aborts the file reading with an exception
  360. AI_WONT_RETURN void BVHLoader::ThrowException( const std::string& pError)
  361. {
  362. throw DeadlyImportError( format() << mFileName << ":" << mLine << " - " << pError);
  363. }
  364. // ------------------------------------------------------------------------------------------------
  365. // Constructs an animation for the motion data and stores it in the given scene
  366. void BVHLoader::CreateAnimation( aiScene* pScene)
  367. {
  368. // create the animation
  369. pScene->mNumAnimations = 1;
  370. pScene->mAnimations = new aiAnimation*[1];
  371. aiAnimation* anim = new aiAnimation;
  372. pScene->mAnimations[0] = anim;
  373. // put down the basic parameters
  374. anim->mName.Set( "Motion");
  375. anim->mTicksPerSecond = 1.0 / double( mAnimTickDuration);
  376. anim->mDuration = double( mAnimNumFrames - 1);
  377. // now generate the tracks for all nodes
  378. anim->mNumChannels = static_cast<unsigned int>(mNodes.size());
  379. anim->mChannels = new aiNodeAnim*[anim->mNumChannels];
  380. // FIX: set the array elements to NULL to ensure proper deletion if an exception is thrown
  381. for (unsigned int i = 0; i < anim->mNumChannels;++i)
  382. anim->mChannels[i] = NULL;
  383. for( unsigned int a = 0; a < anim->mNumChannels; a++)
  384. {
  385. const Node& node = mNodes[a];
  386. const std::string nodeName = std::string( node.mNode->mName.data );
  387. aiNodeAnim* nodeAnim = new aiNodeAnim;
  388. anim->mChannels[a] = nodeAnim;
  389. nodeAnim->mNodeName.Set( nodeName);
  390. // translational part, if given
  391. if( node.mChannels.size() == 6)
  392. {
  393. nodeAnim->mNumPositionKeys = mAnimNumFrames;
  394. nodeAnim->mPositionKeys = new aiVectorKey[mAnimNumFrames];
  395. aiVectorKey* poskey = nodeAnim->mPositionKeys;
  396. for( unsigned int fr = 0; fr < mAnimNumFrames; ++fr)
  397. {
  398. poskey->mTime = double( fr);
  399. // Now compute all translations in the right order
  400. for( unsigned int channel = 0; channel < 3; ++channel)
  401. {
  402. switch( node.mChannels[channel])
  403. {
  404. case Channel_PositionX: poskey->mValue.x = node.mChannelValues[fr * node.mChannels.size() + channel]; break;
  405. case Channel_PositionY: poskey->mValue.y = node.mChannelValues[fr * node.mChannels.size() + channel]; break;
  406. case Channel_PositionZ: poskey->mValue.z = node.mChannelValues[fr * node.mChannels.size() + channel]; break;
  407. default: throw DeadlyImportError( "Unexpected animation channel setup at node " + nodeName );
  408. }
  409. }
  410. ++poskey;
  411. }
  412. } else
  413. {
  414. // if no translation part is given, put a default sequence
  415. aiVector3D nodePos( node.mNode->mTransformation.a4, node.mNode->mTransformation.b4, node.mNode->mTransformation.c4);
  416. nodeAnim->mNumPositionKeys = 1;
  417. nodeAnim->mPositionKeys = new aiVectorKey[1];
  418. nodeAnim->mPositionKeys[0].mTime = 0.0;
  419. nodeAnim->mPositionKeys[0].mValue = nodePos;
  420. }
  421. // rotation part. Always present. First find value offsets
  422. {
  423. unsigned int rotOffset = 0;
  424. if( node.mChannels.size() == 6)
  425. {
  426. // Offset all further calculations
  427. rotOffset = 3;
  428. }
  429. // Then create the number of rotation keys
  430. nodeAnim->mNumRotationKeys = mAnimNumFrames;
  431. nodeAnim->mRotationKeys = new aiQuatKey[mAnimNumFrames];
  432. aiQuatKey* rotkey = nodeAnim->mRotationKeys;
  433. for( unsigned int fr = 0; fr < mAnimNumFrames; ++fr)
  434. {
  435. aiMatrix4x4 temp;
  436. aiMatrix3x3 rotMatrix;
  437. for( unsigned int channel = 0; channel < 3; ++channel)
  438. {
  439. // translate ZXY euler angels into a quaternion
  440. const float angle = node.mChannelValues[fr * node.mChannels.size() + rotOffset + channel] * float( AI_MATH_PI) / 180.0f;
  441. // Compute rotation transformations in the right order
  442. switch (node.mChannels[rotOffset+channel])
  443. {
  444. case Channel_RotationX: aiMatrix4x4::RotationX( angle, temp); rotMatrix *= aiMatrix3x3( temp); break;
  445. case Channel_RotationY: aiMatrix4x4::RotationY( angle, temp); rotMatrix *= aiMatrix3x3( temp); break;
  446. case Channel_RotationZ: aiMatrix4x4::RotationZ( angle, temp); rotMatrix *= aiMatrix3x3( temp); break;
  447. default: throw DeadlyImportError( "Unexpected animation channel setup at node " + nodeName );
  448. }
  449. }
  450. rotkey->mTime = double( fr);
  451. rotkey->mValue = aiQuaternion( rotMatrix);
  452. ++rotkey;
  453. }
  454. }
  455. // scaling part. Always just a default track
  456. {
  457. nodeAnim->mNumScalingKeys = 1;
  458. nodeAnim->mScalingKeys = new aiVectorKey[1];
  459. nodeAnim->mScalingKeys[0].mTime = 0.0;
  460. nodeAnim->mScalingKeys[0].mValue.Set( 1.0f, 1.0f, 1.0f);
  461. }
  462. }
  463. }
  464. #endif // !! ASSIMP_BUILD_NO_BVH_IMPORTER