CSMLoader.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2020, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file CSMLoader.cpp
  35. * Implementation of the CSM importer class.
  36. */
  37. #ifndef ASSIMP_BUILD_NO_CSM_IMPORTER
  38. #include "CSMLoader.h"
  39. #include <assimp/SkeletonMeshBuilder.h>
  40. #include <assimp/ParsingUtils.h>
  41. #include <assimp/fast_atof.h>
  42. #include <assimp/Importer.hpp>
  43. #include <memory>
  44. #include <assimp/IOSystem.hpp>
  45. #include <assimp/anim.h>
  46. #include <assimp/DefaultLogger.hpp>
  47. #include <assimp/scene.h>
  48. #include <assimp/importerdesc.h>
  49. using namespace Assimp;
  50. static const aiImporterDesc desc = {
  51. "CharacterStudio Motion Importer (MoCap)",
  52. "",
  53. "",
  54. "",
  55. aiImporterFlags_SupportTextFlavour,
  56. 0,
  57. 0,
  58. 0,
  59. 0,
  60. "csm"
  61. };
  62. // ------------------------------------------------------------------------------------------------
  63. // Constructor to be privately used by Importer
  64. CSMImporter::CSMImporter()
  65. : noSkeletonMesh()
  66. {}
  67. // ------------------------------------------------------------------------------------------------
  68. // Destructor, private as well
  69. CSMImporter::~CSMImporter()
  70. {}
  71. // ------------------------------------------------------------------------------------------------
  72. // Returns whether the class can handle the format of the given file.
  73. bool CSMImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  74. {
  75. // check file extension
  76. const std::string extension = GetExtension(pFile);
  77. if( extension == "csm")
  78. return true;
  79. if ((checkSig || !extension.length()) && pIOHandler) {
  80. const char* tokens[] = {"$Filename"};
  81. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
  82. }
  83. return false;
  84. }
  85. // ------------------------------------------------------------------------------------------------
  86. // Build a string of all file extensions supported
  87. const aiImporterDesc* CSMImporter::GetInfo () const
  88. {
  89. return &desc;
  90. }
  91. // ------------------------------------------------------------------------------------------------
  92. // Setup configuration properties for the loader
  93. void CSMImporter::SetupProperties(const Importer* pImp)
  94. {
  95. noSkeletonMesh = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_NO_SKELETON_MESHES,0) != 0;
  96. }
  97. // ------------------------------------------------------------------------------------------------
  98. // Imports the given file into the given scene structure.
  99. void CSMImporter::InternReadFile( const std::string& pFile,
  100. aiScene* pScene, IOSystem* pIOHandler)
  101. {
  102. std::unique_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  103. // Check whether we can read from the file
  104. if( file.get() == NULL) {
  105. throw DeadlyImportError( "Failed to open CSM file " + pFile + ".");
  106. }
  107. // allocate storage and copy the contents of the file to a memory buffer
  108. std::vector<char> mBuffer2;
  109. TextFileToBuffer(file.get(),mBuffer2);
  110. const char* buffer = &mBuffer2[0];
  111. std::unique_ptr<aiAnimation> anim(new aiAnimation());
  112. int first = 0, last = 0x00ffffff;
  113. // now process the file and look out for '$' sections
  114. while (1) {
  115. SkipSpaces(&buffer);
  116. if ('\0' == *buffer)
  117. break;
  118. if ('$' == *buffer) {
  119. ++buffer;
  120. if (TokenMatchI(buffer,"firstframe",10)) {
  121. SkipSpaces(&buffer);
  122. first = strtol10(buffer,&buffer);
  123. }
  124. else if (TokenMatchI(buffer,"lastframe",9)) {
  125. SkipSpaces(&buffer);
  126. last = strtol10(buffer,&buffer);
  127. }
  128. else if (TokenMatchI(buffer,"rate",4)) {
  129. SkipSpaces(&buffer);
  130. float d;
  131. buffer = fast_atoreal_move<float>(buffer,d);
  132. anim->mTicksPerSecond = d;
  133. }
  134. else if (TokenMatchI(buffer,"order",5)) {
  135. std::vector< aiNodeAnim* > anims_temp;
  136. anims_temp.reserve(30);
  137. while (1) {
  138. SkipSpaces(&buffer);
  139. if (IsLineEnd(*buffer) && SkipSpacesAndLineEnd(&buffer) && *buffer == '$')
  140. break; // next section
  141. // Construct a new node animation channel and setup its name
  142. anims_temp.push_back(new aiNodeAnim());
  143. aiNodeAnim* nda = anims_temp.back();
  144. char* ot = nda->mNodeName.data;
  145. while (!IsSpaceOrNewLine(*buffer))
  146. *ot++ = *buffer++;
  147. *ot = '\0';
  148. nda->mNodeName.length = static_cast<ai_uint32>(ot-nda->mNodeName.data);
  149. }
  150. anim->mNumChannels = static_cast<unsigned int>(anims_temp.size());
  151. if (!anim->mNumChannels)
  152. throw DeadlyImportError("CSM: Empty $order section");
  153. // copy over to the output animation
  154. anim->mChannels = new aiNodeAnim*[anim->mNumChannels];
  155. ::memcpy(anim->mChannels,&anims_temp[0],sizeof(aiNodeAnim*)*anim->mNumChannels);
  156. }
  157. else if (TokenMatchI(buffer,"points",6)) {
  158. if (!anim->mNumChannels)
  159. throw DeadlyImportError("CSM: \'$order\' section is required to appear prior to \'$points\'");
  160. // If we know how many frames we'll read, we can preallocate some storage
  161. unsigned int alloc = 100;
  162. if (last != 0x00ffffff)
  163. {
  164. alloc = last-first;
  165. alloc += alloc>>2u; // + 25%
  166. for (unsigned int i = 0; i < anim->mNumChannels;++i)
  167. anim->mChannels[i]->mPositionKeys = new aiVectorKey[alloc];
  168. }
  169. unsigned int filled = 0;
  170. // Now read all point data.
  171. while (1) {
  172. SkipSpaces(&buffer);
  173. if (IsLineEnd(*buffer) && (!SkipSpacesAndLineEnd(&buffer) || *buffer == '$')) {
  174. break; // next section
  175. }
  176. // read frame
  177. const int frame = ::strtoul10(buffer,&buffer);
  178. last = std::max(frame,last);
  179. first = std::min(frame,last);
  180. for (unsigned int i = 0; i < anim->mNumChannels;++i) {
  181. aiNodeAnim* s = anim->mChannels[i];
  182. if (s->mNumPositionKeys == alloc) { /* need to reallocate? */
  183. aiVectorKey* old = s->mPositionKeys;
  184. s->mPositionKeys = new aiVectorKey[s->mNumPositionKeys = alloc*2];
  185. ::memcpy(s->mPositionKeys,old,sizeof(aiVectorKey)*alloc);
  186. delete[] old;
  187. }
  188. // read x,y,z
  189. if(!SkipSpacesAndLineEnd(&buffer))
  190. throw DeadlyImportError("CSM: Unexpected EOF occurred reading sample x coord");
  191. if (TokenMatchI(buffer, "DROPOUT", 7)) {
  192. // seems this is invalid marker data; at least the doc says it's possible
  193. ASSIMP_LOG_WARN("CSM: Encountered invalid marker data (DROPOUT)");
  194. }
  195. else {
  196. aiVectorKey* sub = s->mPositionKeys + s->mNumPositionKeys;
  197. sub->mTime = (double)frame;
  198. buffer = fast_atoreal_move<float>(buffer, (float&)sub->mValue.x);
  199. if(!SkipSpacesAndLineEnd(&buffer))
  200. throw DeadlyImportError("CSM: Unexpected EOF occurred reading sample y coord");
  201. buffer = fast_atoreal_move<float>(buffer, (float&)sub->mValue.y);
  202. if(!SkipSpacesAndLineEnd(&buffer))
  203. throw DeadlyImportError("CSM: Unexpected EOF occurred reading sample z coord");
  204. buffer = fast_atoreal_move<float>(buffer, (float&)sub->mValue.z);
  205. ++s->mNumPositionKeys;
  206. }
  207. }
  208. // update allocation granularity
  209. if (filled == alloc)
  210. alloc *= 2;
  211. ++filled;
  212. }
  213. // all channels must be complete in order to continue safely.
  214. for (unsigned int i = 0; i < anim->mNumChannels;++i) {
  215. if (!anim->mChannels[i]->mNumPositionKeys)
  216. throw DeadlyImportError("CSM: Invalid marker track");
  217. }
  218. }
  219. }
  220. else {
  221. // advance to the next line
  222. SkipLine(&buffer);
  223. }
  224. }
  225. // Setup a proper animation duration
  226. anim->mDuration = last - std::min( first, 0 );
  227. // build a dummy root node with the tiny markers as children
  228. pScene->mRootNode = new aiNode();
  229. pScene->mRootNode->mName.Set("$CSM_DummyRoot");
  230. pScene->mRootNode->mNumChildren = anim->mNumChannels;
  231. pScene->mRootNode->mChildren = new aiNode* [anim->mNumChannels];
  232. for (unsigned int i = 0; i < anim->mNumChannels;++i) {
  233. aiNodeAnim* na = anim->mChannels[i];
  234. aiNode* nd = pScene->mRootNode->mChildren[i] = new aiNode();
  235. nd->mName = anim->mChannels[i]->mNodeName;
  236. nd->mParent = pScene->mRootNode;
  237. aiMatrix4x4::Translation(na->mPositionKeys[0].mValue, nd->mTransformation);
  238. }
  239. // Store the one and only animation in the scene
  240. pScene->mAnimations = new aiAnimation*[pScene->mNumAnimations=1];
  241. anim->mName.Set("$CSM_MasterAnim");
  242. pScene->mAnimations[0] = anim.release();
  243. // mark the scene as incomplete and run SkeletonMeshBuilder on it
  244. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  245. if (!noSkeletonMesh) {
  246. SkeletonMeshBuilder maker(pScene,pScene->mRootNode,true);
  247. }
  248. }
  249. #endif // !! ASSIMP_BUILD_NO_CSM_IMPORTER