MD5Parser.cpp 16 KB

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