BVHLoader.cpp 20 KB

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