BVHLoader.cpp 20 KB

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