BVHLoader.cpp 20 KB

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