MD5Parser.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2022, 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 MD5Parser.cpp
  35. * @brief Implementation of the MD5 parser class
  36. */
  37. // internal headers
  38. #include "AssetLib/MD5/MD5Loader.h"
  39. #include "Material/MaterialSystem.h"
  40. #include <assimp/ParsingUtils.h>
  41. #include <assimp/StringComparison.h>
  42. #include <assimp/fast_atof.h>
  43. #include <assimp/mesh.h>
  44. #include <assimp/DefaultLogger.hpp>
  45. using namespace Assimp;
  46. using namespace Assimp::MD5;
  47. // ------------------------------------------------------------------------------------------------
  48. // Parse the segment structure for an MD5 file
  49. MD5Parser::MD5Parser(char *_buffer, unsigned int _fileSize) : buffer(_buffer), bufferEnd(nullptr), fileSize(_fileSize), lineNumber(0) {
  50. ai_assert(nullptr != _buffer);
  51. ai_assert(0 != _fileSize);
  52. bufferEnd = buffer + fileSize;
  53. ASSIMP_LOG_DEBUG("MD5Parser begin");
  54. // parse the file header
  55. ParseHeader();
  56. // and read all sections until we're finished
  57. bool running = true;
  58. while (running) {
  59. mSections.emplace_back();
  60. Section &sec = mSections.back();
  61. if (!ParseSection(sec)) {
  62. break;
  63. }
  64. }
  65. if (!DefaultLogger::isNullLogger()) {
  66. char szBuffer[128]; // should be sufficiently large
  67. ::ai_snprintf(szBuffer, 128, "MD5Parser end. Parsed %i sections", (int)mSections.size());
  68. ASSIMP_LOG_DEBUG(szBuffer);
  69. }
  70. }
  71. // ------------------------------------------------------------------------------------------------
  72. // Report error to the log stream
  73. /*static*/ AI_WONT_RETURN void MD5Parser::ReportError(const char *error, unsigned int line) {
  74. char szBuffer[1024];
  75. ::ai_snprintf(szBuffer, 1024, "[MD5] Line %u: %s", line, error);
  76. throw DeadlyImportError(szBuffer);
  77. }
  78. // ------------------------------------------------------------------------------------------------
  79. // Report warning to the log stream
  80. /*static*/ void MD5Parser::ReportWarning(const char *warn, unsigned int line) {
  81. char szBuffer[1024];
  82. ::sprintf(szBuffer, "[MD5] Line %u: %s", line, warn);
  83. ASSIMP_LOG_WARN(szBuffer);
  84. }
  85. // ------------------------------------------------------------------------------------------------
  86. // Parse and validate the MD5 header
  87. void MD5Parser::ParseHeader() {
  88. // parse and validate the file version
  89. SkipSpaces();
  90. if (!TokenMatch(buffer, "MD5Version", 10)) {
  91. ReportError("Invalid MD5 file: MD5Version tag has not been found");
  92. }
  93. SkipSpaces();
  94. unsigned int iVer = ::strtoul10(buffer, (const char **)&buffer);
  95. if (10 != iVer) {
  96. ReportError("MD5 version tag is unknown (10 is expected)");
  97. }
  98. SkipLine();
  99. // print the command line options to the console
  100. // FIX: can break the log length limit, so we need to be careful
  101. char *sz = buffer;
  102. while (!IsLineEnd(*buffer++))
  103. ;
  104. ASSIMP_LOG_INFO(std::string(sz, std::min((uintptr_t)MAX_LOG_MESSAGE_LENGTH, (uintptr_t)(buffer - sz))));
  105. SkipSpacesAndLineEnd();
  106. }
  107. // ------------------------------------------------------------------------------------------------
  108. // Recursive MD5 parsing function
  109. bool MD5Parser::ParseSection(Section &out) {
  110. // store the current line number for use in error messages
  111. out.iLineNumber = lineNumber;
  112. // first parse the name of the section
  113. char *sz = buffer;
  114. while (!IsSpaceOrNewLine(*buffer))
  115. buffer++;
  116. out.mName = std::string(sz, (uintptr_t)(buffer - sz));
  117. SkipSpaces();
  118. bool running = true;
  119. while (running) {
  120. if ('{' == *buffer) {
  121. // it is a normal section so read all lines
  122. buffer++;
  123. bool run = true;
  124. while (run) {
  125. if (!SkipSpacesAndLineEnd()) {
  126. return false; // seems this was the last section
  127. }
  128. if ('}' == *buffer) {
  129. buffer++;
  130. break;
  131. }
  132. out.mElements.emplace_back();
  133. Element &elem = out.mElements.back();
  134. elem.iLineNumber = lineNumber;
  135. elem.szStart = buffer;
  136. // terminate the line with zero
  137. while (!IsLineEnd(*buffer))
  138. buffer++;
  139. if (*buffer) {
  140. ++lineNumber;
  141. *buffer++ = '\0';
  142. }
  143. }
  144. break;
  145. } else if (!IsSpaceOrNewLine(*buffer)) {
  146. // it is an element at global scope. Parse its value and go on
  147. sz = buffer;
  148. while (!IsSpaceOrNewLine(*buffer++))
  149. ;
  150. out.mGlobalValue = std::string(sz, (uintptr_t)(buffer - sz));
  151. continue;
  152. }
  153. break;
  154. }
  155. return SkipSpacesAndLineEnd();
  156. }
  157. // ------------------------------------------------------------------------------------------------
  158. // Some dirty macros just because they're so funny and easy to debug
  159. // skip all spaces ... handle EOL correctly
  160. #define AI_MD5_SKIP_SPACES() \
  161. if (!SkipSpaces(&sz)) \
  162. MD5Parser::ReportWarning("Unexpected end of line", elem.iLineNumber);
  163. // read a triple float in brackets: (1.0 1.0 1.0)
  164. #define AI_MD5_READ_TRIPLE(vec) \
  165. AI_MD5_SKIP_SPACES(); \
  166. if ('(' != *sz++) \
  167. MD5Parser::ReportWarning("Unexpected token: ( was expected", elem.iLineNumber); \
  168. AI_MD5_SKIP_SPACES(); \
  169. sz = fast_atoreal_move<float>(sz, (float &)vec.x); \
  170. AI_MD5_SKIP_SPACES(); \
  171. sz = fast_atoreal_move<float>(sz, (float &)vec.y); \
  172. AI_MD5_SKIP_SPACES(); \
  173. sz = fast_atoreal_move<float>(sz, (float &)vec.z); \
  174. AI_MD5_SKIP_SPACES(); \
  175. if (')' != *sz++) \
  176. MD5Parser::ReportWarning("Unexpected token: ) was expected", elem.iLineNumber);
  177. // parse a string, enclosed in quotation marks or not
  178. #define AI_MD5_PARSE_STRING(out) \
  179. bool bQuota = (*sz == '\"'); \
  180. const char *szStart = sz; \
  181. while (!IsSpaceOrNewLine(*sz)) \
  182. ++sz; \
  183. const char *szEnd = sz; \
  184. if (bQuota) { \
  185. szStart++; \
  186. if ('\"' != *(szEnd -= 1)) { \
  187. MD5Parser::ReportWarning("Expected closing quotation marks in string", \
  188. elem.iLineNumber); \
  189. continue; \
  190. } \
  191. } \
  192. out.length = (size_t)(szEnd - szStart); \
  193. ::memcpy(out.data, szStart, out.length); \
  194. out.data[out.length] = '\0';
  195. // parse a string, enclosed in quotation marks
  196. #define AI_MD5_PARSE_STRING_IN_QUOTATION(out) \
  197. while ('\"' != *sz) \
  198. ++sz; \
  199. const char *szStart = ++sz; \
  200. while ('\"' != *sz) \
  201. ++sz; \
  202. const char *szEnd = (sz++); \
  203. out.length = (ai_uint32)(szEnd - szStart); \
  204. ::memcpy(out.data, szStart, out.length); \
  205. out.data[out.length] = '\0';
  206. // ------------------------------------------------------------------------------------------------
  207. // .MD5MESH parsing function
  208. MD5MeshParser::MD5MeshParser(SectionList &mSections) {
  209. ASSIMP_LOG_DEBUG("MD5MeshParser begin");
  210. // now parse all sections
  211. for (SectionList::const_iterator iter = mSections.begin(), iterEnd = mSections.end(); iter != iterEnd; ++iter) {
  212. if ((*iter).mName == "numMeshes") {
  213. mMeshes.reserve(::strtoul10((*iter).mGlobalValue.c_str()));
  214. } else if ((*iter).mName == "numJoints") {
  215. mJoints.reserve(::strtoul10((*iter).mGlobalValue.c_str()));
  216. } else if ((*iter).mName == "joints") {
  217. // "origin" -1 ( -0.000000 0.016430 -0.006044 ) ( 0.707107 0.000000 0.707107 )
  218. for (const auto &elem : (*iter).mElements) {
  219. mJoints.emplace_back();
  220. BoneDesc &desc = mJoints.back();
  221. const char *sz = elem.szStart;
  222. AI_MD5_PARSE_STRING_IN_QUOTATION(desc.mName);
  223. AI_MD5_SKIP_SPACES();
  224. // negative values, at least -1, is allowed here
  225. desc.mParentIndex = (int)strtol10(sz, &sz);
  226. AI_MD5_READ_TRIPLE(desc.mPositionXYZ);
  227. AI_MD5_READ_TRIPLE(desc.mRotationQuat); // normalized quaternion, so w is not there
  228. }
  229. } else if ((*iter).mName == "mesh") {
  230. mMeshes.emplace_back();
  231. MeshDesc &desc = mMeshes.back();
  232. for (const auto &elem : (*iter).mElements) {
  233. const char *sz = elem.szStart;
  234. // shader attribute
  235. if (TokenMatch(sz, "shader", 6)) {
  236. AI_MD5_SKIP_SPACES();
  237. AI_MD5_PARSE_STRING_IN_QUOTATION(desc.mShader);
  238. }
  239. // numverts attribute
  240. else if (TokenMatch(sz, "numverts", 8)) {
  241. AI_MD5_SKIP_SPACES();
  242. desc.mVertices.resize(strtoul10(sz));
  243. }
  244. // numtris attribute
  245. else if (TokenMatch(sz, "numtris", 7)) {
  246. AI_MD5_SKIP_SPACES();
  247. desc.mFaces.resize(strtoul10(sz));
  248. }
  249. // numweights attribute
  250. else if (TokenMatch(sz, "numweights", 10)) {
  251. AI_MD5_SKIP_SPACES();
  252. desc.mWeights.resize(strtoul10(sz));
  253. }
  254. // vert attribute
  255. // "vert 0 ( 0.394531 0.513672 ) 0 1"
  256. else if (TokenMatch(sz, "vert", 4)) {
  257. AI_MD5_SKIP_SPACES();
  258. const unsigned int idx = ::strtoul10(sz, &sz);
  259. AI_MD5_SKIP_SPACES();
  260. if (idx >= desc.mVertices.size())
  261. desc.mVertices.resize(idx + 1);
  262. VertexDesc &vert = desc.mVertices[idx];
  263. if ('(' != *sz++)
  264. MD5Parser::ReportWarning("Unexpected token: ( was expected", elem.iLineNumber);
  265. AI_MD5_SKIP_SPACES();
  266. sz = fast_atoreal_move<float>(sz, (float &)vert.mUV.x);
  267. AI_MD5_SKIP_SPACES();
  268. sz = fast_atoreal_move<float>(sz, (float &)vert.mUV.y);
  269. AI_MD5_SKIP_SPACES();
  270. if (')' != *sz++)
  271. MD5Parser::ReportWarning("Unexpected token: ) was expected", elem.iLineNumber);
  272. AI_MD5_SKIP_SPACES();
  273. vert.mFirstWeight = ::strtoul10(sz, &sz);
  274. AI_MD5_SKIP_SPACES();
  275. vert.mNumWeights = ::strtoul10(sz, &sz);
  276. }
  277. // tri attribute
  278. // "tri 0 15 13 12"
  279. else if (TokenMatch(sz, "tri", 3)) {
  280. AI_MD5_SKIP_SPACES();
  281. const unsigned int idx = strtoul10(sz, &sz);
  282. if (idx >= desc.mFaces.size())
  283. desc.mFaces.resize(idx + 1);
  284. aiFace &face = desc.mFaces[idx];
  285. face.mIndices = new unsigned int[face.mNumIndices = 3];
  286. for (unsigned int i = 0; i < 3; ++i) {
  287. AI_MD5_SKIP_SPACES();
  288. face.mIndices[i] = strtoul10(sz, &sz);
  289. }
  290. }
  291. // weight attribute
  292. // "weight 362 5 0.500000 ( -3.553583 11.893474 9.719339 )"
  293. else if (TokenMatch(sz, "weight", 6)) {
  294. AI_MD5_SKIP_SPACES();
  295. const unsigned int idx = strtoul10(sz, &sz);
  296. AI_MD5_SKIP_SPACES();
  297. if (idx >= desc.mWeights.size())
  298. desc.mWeights.resize(idx + 1);
  299. WeightDesc &weight = desc.mWeights[idx];
  300. weight.mBone = strtoul10(sz, &sz);
  301. AI_MD5_SKIP_SPACES();
  302. sz = fast_atoreal_move<float>(sz, weight.mWeight);
  303. AI_MD5_READ_TRIPLE(weight.vOffsetPosition);
  304. }
  305. }
  306. }
  307. }
  308. ASSIMP_LOG_DEBUG("MD5MeshParser end");
  309. }
  310. // ------------------------------------------------------------------------------------------------
  311. // .MD5ANIM parsing function
  312. MD5AnimParser::MD5AnimParser(SectionList &mSections) {
  313. ASSIMP_LOG_DEBUG("MD5AnimParser begin");
  314. fFrameRate = 24.0f;
  315. mNumAnimatedComponents = UINT_MAX;
  316. for (SectionList::const_iterator iter = mSections.begin(), iterEnd = mSections.end(); iter != iterEnd; ++iter) {
  317. if ((*iter).mName == "hierarchy") {
  318. // "sheath" 0 63 6
  319. for (const auto &elem : (*iter).mElements) {
  320. mAnimatedBones.emplace_back();
  321. AnimBoneDesc &desc = mAnimatedBones.back();
  322. const char *sz = elem.szStart;
  323. AI_MD5_PARSE_STRING_IN_QUOTATION(desc.mName);
  324. AI_MD5_SKIP_SPACES();
  325. // parent index - negative values are allowed (at least -1)
  326. desc.mParentIndex = ::strtol10(sz, &sz);
  327. // flags (highest is 2^6-1)
  328. AI_MD5_SKIP_SPACES();
  329. if (63 < (desc.iFlags = ::strtoul10(sz, &sz))) {
  330. MD5Parser::ReportWarning("Invalid flag combination in hierarchy section", elem.iLineNumber);
  331. }
  332. AI_MD5_SKIP_SPACES();
  333. // index of the first animation keyframe component for this joint
  334. desc.iFirstKeyIndex = ::strtoul10(sz, &sz);
  335. }
  336. } else if ((*iter).mName == "baseframe") {
  337. // ( -0.000000 0.016430 -0.006044 ) ( 0.707107 0.000242 0.707107 )
  338. for (const auto &elem : (*iter).mElements) {
  339. const char *sz = elem.szStart;
  340. mBaseFrames.emplace_back();
  341. BaseFrameDesc &desc = mBaseFrames.back();
  342. AI_MD5_READ_TRIPLE(desc.vPositionXYZ);
  343. AI_MD5_READ_TRIPLE(desc.vRotationQuat);
  344. }
  345. } else if ((*iter).mName == "frame") {
  346. if (!(*iter).mGlobalValue.length()) {
  347. MD5Parser::ReportWarning("A frame section must have a frame index", (*iter).iLineNumber);
  348. continue;
  349. }
  350. mFrames.emplace_back();
  351. FrameDesc &desc = mFrames.back();
  352. desc.iIndex = strtoul10((*iter).mGlobalValue.c_str());
  353. // we do already know how much storage we will presumably need
  354. if (UINT_MAX != mNumAnimatedComponents) {
  355. desc.mValues.reserve(mNumAnimatedComponents);
  356. }
  357. // now read all elements (continuous list of floats)
  358. for (const auto &elem : (*iter).mElements) {
  359. const char *sz = elem.szStart;
  360. while (SkipSpacesAndLineEnd(&sz)) {
  361. float f;
  362. sz = fast_atoreal_move<float>(sz, f);
  363. desc.mValues.push_back(f);
  364. }
  365. }
  366. } else if ((*iter).mName == "numFrames") {
  367. mFrames.reserve(strtoul10((*iter).mGlobalValue.c_str()));
  368. } else if ((*iter).mName == "numJoints") {
  369. const unsigned int num = strtoul10((*iter).mGlobalValue.c_str());
  370. mAnimatedBones.reserve(num);
  371. // try to guess the number of animated components if that element is not given
  372. if (UINT_MAX == mNumAnimatedComponents) {
  373. mNumAnimatedComponents = num * 6;
  374. }
  375. } else if ((*iter).mName == "numAnimatedComponents") {
  376. mAnimatedBones.reserve(strtoul10((*iter).mGlobalValue.c_str()));
  377. } else if ((*iter).mName == "frameRate") {
  378. fast_atoreal_move<float>((*iter).mGlobalValue.c_str(), fFrameRate);
  379. }
  380. }
  381. ASSIMP_LOG_DEBUG("MD5AnimParser end");
  382. }
  383. // ------------------------------------------------------------------------------------------------
  384. // .MD5CAMERA parsing function
  385. MD5CameraParser::MD5CameraParser(SectionList &mSections) {
  386. ASSIMP_LOG_DEBUG("MD5CameraParser begin");
  387. fFrameRate = 24.0f;
  388. for (SectionList::const_iterator iter = mSections.begin(), iterEnd = mSections.end(); iter != iterEnd; ++iter) {
  389. if ((*iter).mName == "numFrames") {
  390. frames.reserve(strtoul10((*iter).mGlobalValue.c_str()));
  391. } else if ((*iter).mName == "frameRate") {
  392. fFrameRate = fast_atof((*iter).mGlobalValue.c_str());
  393. } else if ((*iter).mName == "numCuts") {
  394. cuts.reserve(strtoul10((*iter).mGlobalValue.c_str()));
  395. } else if ((*iter).mName == "cuts") {
  396. for (const auto &elem : (*iter).mElements) {
  397. cuts.push_back(strtoul10(elem.szStart) + 1);
  398. }
  399. } else if ((*iter).mName == "camera") {
  400. for (const auto &elem : (*iter).mElements) {
  401. const char *sz = elem.szStart;
  402. frames.emplace_back();
  403. CameraAnimFrameDesc &cur = frames.back();
  404. AI_MD5_READ_TRIPLE(cur.vPositionXYZ);
  405. AI_MD5_READ_TRIPLE(cur.vRotationQuat);
  406. AI_MD5_SKIP_SPACES();
  407. cur.fFOV = fast_atof(sz);
  408. }
  409. }
  410. }
  411. ASSIMP_LOG_DEBUG("MD5CameraParser end");
  412. }