Debian Codegraph @

code/AssetLib/MD5/MD5Parser.cpp

raw
1 /*
2 ---------------------------------------------------------------------------
3 Open Asset Import Library (assimp)
4 ---------------------------------------------------------------------------
5
6 Copyright (c) 2006-2026, assimp team
7
8 All rights reserved.
9
10 Redistribution and use of this software in source and binary forms,
11 with or without modification, are permitted provided that the following
12 conditions are met:
13
14 * Redistributions of source code must retain the above
15 copyright notice, this list of conditions and the
16 following disclaimer.
17
18 * Redistributions in binary form must reproduce the above
19 copyright notice, this list of conditions and the
20 following disclaimer in the documentation and/or other
21 materials provided with the distribution.
22
23 * Neither the name of the assimp team, nor the names of its
24 contributors may be used to endorse or promote products
25 derived from this software without specific prior
26 written permission of the assimp team.
27
28 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 ---------------------------------------------------------------------------
40 */
41
42 /** @file MD5Parser.cpp
43 * @brief Implementation of the MD5 parser class
44 */
45
46 // internal headers
47 #include "MD5Loader.h"
48 #include "Material/MaterialSystem.h"
49
50 #include <assimp/ParsingUtils.h>
51 #include <assimp/StringComparison.h>
52 #include <assimp/fast_atof.h>
53 #include <assimp/mesh.h>
54 #include <assimp/DefaultLogger.hpp>
55
56 using namespace Assimp;
57 using namespace Assimp::MD5;
58
59 // ------------------------------------------------------------------------------------------------
60 // Parse the segment structure for an MD5 file
61 MD5Parser::MD5Parser(char *_buffer, unsigned int _fileSize) : buffer(_buffer), bufferEnd(nullptr), fileSize(_fileSize), lineNumber(0) {
62 ai_assert(nullptr != _buffer);
63 ai_assert(0 != _fileSize);
64
65 bufferEnd = buffer + fileSize;
66 ASSIMP_LOG_DEBUG("MD5Parser begin");
67
68 // parse the file header
69 ParseHeader();
70
71 // and read all sections until we're finished
72 bool running = true;
73 while (running) {
74 mSections.emplace_back();
75 Section &sec = mSections.back();
76 if (!ParseSection(sec)) {
77 break;
78 }
79 }
80
81 if (!DefaultLogger::isNullLogger()) {
82 char szBuffer[128]; // should be sufficiently large
83 ::ai_snprintf(szBuffer, 128, "MD5Parser end. Parsed %i sections", (int)mSections.size());
84 ASSIMP_LOG_DEBUG(szBuffer);
85 }
86 }
87
88 // ------------------------------------------------------------------------------------------------
89 // Report error to the log stream
90 AI_WONT_RETURN void MD5Parser::ReportError(const char *error, unsigned int line) {
91 char szBuffer[1024];
92 ::ai_snprintf(szBuffer, 1024, "[MD5] Line %u: %s", line, error);
93 throw DeadlyImportError(szBuffer);
94 }
95
96 // ------------------------------------------------------------------------------------------------
97 // Report warning to the log stream
98 void MD5Parser::ReportWarning(const char *warn, unsigned int line) {
99 char szBuffer[1024];
100 ::snprintf(szBuffer, sizeof(szBuffer), "[MD5] Line %u: %s", line, warn);
101 ASSIMP_LOG_WARN(szBuffer);
102 }
103
104 // ------------------------------------------------------------------------------------------------
105 // Parse and validate the MD5 header
106 void MD5Parser::ParseHeader() {
107 // parse and validate the file version
108 SkipSpaces();
109 if (!TokenMatch(buffer, "MD5Version", 10)) {
110 ReportError("Invalid MD5 file: MD5Version tag has not been found");
111 }
112 SkipSpaces();
113 unsigned int iVer = ::strtoul10(buffer, (const char **)&buffer);
114 if (10 != iVer) {
115 ReportError("MD5 version tag is unknown (10 is expected)");
116 }
117 SkipLine();
118
119 // print the command line options to the console
120 char *sz = buffer;
121 while (buffer < bufferEnd) {
122 if (IsLineEnd(*buffer++)) {
123 break;
124 }
125 }
126
127 if (buffer == bufferEnd) {
128 return;
129 }
130
131 ASSIMP_LOG_INFO(std::string(sz, std::min((uintptr_t)MAX_LOG_MESSAGE_LENGTH, (uintptr_t)(buffer - sz))));
132 SkipSpacesAndLineEnd();
133 }
134
135 // ------------------------------------------------------------------------------------------------
136 // Recursive MD5 parsing function
137 bool MD5Parser::ParseSection(Section &out) {
138 // store the current line number for use in error messages
139 out.iLineNumber = lineNumber;
140
141 // first parse the name of the section
142 char *sz = buffer;
143 while (!IsSpaceOrNewLine(*buffer)) {
144 ++buffer;
145 if (buffer == bufferEnd) {
146 return false;
147 }
148 }
149 out.mName = std::string(sz, (uintptr_t)(buffer - sz));
150 while (IsSpace(*buffer)) {
151 ++buffer;
152 if (buffer == bufferEnd) {
153 return false;
154 }
155 }
156
157 bool running = true;
158 while (running) {
159 if ('{' == *buffer) {
160 // it is a normal section so read all lines
161 ++buffer;
162 if (buffer == bufferEnd) {
163 return false;
164 }
165 bool run = true;
166 while (run) {
167 while (IsSpaceOrNewLine(*buffer)) {
168 ++buffer;
169 if (buffer == bufferEnd) {
170 return false;
171 }
172 }
173 if ('\0' == *buffer) {
174 return false; // seems this was the last section
175 }
176 if ('}' == *buffer) {
177 ++buffer;
178 break;
179 }
180
181 out.mElements.emplace_back();
182 Element &elem = out.mElements.back();
183
184 elem.iLineNumber = lineNumber;
185 elem.szStart = buffer;
186 elem.end = bufferEnd;
187
188 // terminate the line with zero
189 while (!IsLineEnd(*buffer)) {
190 ++buffer;
191 if (buffer == bufferEnd) {
192 return false;
193 }
194 }
195 if (*buffer) {
196 ++lineNumber;
197 *buffer++ = '\0';
198 if (buffer == bufferEnd) {
199 return false;
200 }
201 }
202 }
203 break;
204 } else if (!IsSpaceOrNewLine(*buffer)) {
205 // it is an element at global scope. Parse its value and go on
206 sz = buffer;
207 while (!IsSpaceOrNewLine(*buffer++)) {
208 if (buffer == bufferEnd) {
209 return false;
210 }
211 }
212 out.mGlobalValue = std::string(sz, (uintptr_t)(buffer - sz));
213 continue;
214 }
215 break;
216 }
217 if (buffer == bufferEnd) {
218 return false;
219 }
220 while (IsSpaceOrNewLine(*buffer)) {
221 if (buffer == bufferEnd) {
222 break;
223 }
224 ++buffer;
225 }
226 return '\0' != *buffer;
227 }
228
229 // skip all spaces ... handle EOL correctly
230 inline void AI_MD5_SKIP_SPACES(const char **sz, const char *bufferEnd, int linenumber) {
231 if (!SkipSpaces(sz, bufferEnd)) {
232 MD5Parser::ReportWarning("Unexpected end of line", linenumber);
233 }
234 }
235
236 // read a triple float in brackets: (1.0 1.0 1.0)
237 inline void AI_MD5_READ_TRIPLE(aiVector3D &vec, const char **sz, const char *bufferEnd, int linenumber) {
238 AI_MD5_SKIP_SPACES(sz, bufferEnd, linenumber);
239 if ('(' != **sz) {
240 MD5Parser::ReportWarning("Unexpected token: ( was expected", linenumber);
241 if (*sz == bufferEnd)
242 return;
243 ++*sz;
244 }
245 if (*sz == bufferEnd)
246 return;
247 ++*sz;
248 AI_MD5_SKIP_SPACES(sz, bufferEnd, linenumber);
249 *sz = fast_atoreal_move(*sz, vec.x);
250 AI_MD5_SKIP_SPACES(sz, bufferEnd, linenumber);
251 *sz = fast_atoreal_move(*sz, vec.y);
252 AI_MD5_SKIP_SPACES(sz, bufferEnd, linenumber);
253 *sz = fast_atoreal_move(*sz, vec.z);
254 AI_MD5_SKIP_SPACES(sz, bufferEnd, linenumber);
255 if (')' != **sz) {
256 MD5Parser::ReportWarning("Unexpected token: ) was expected", linenumber);
257 }
258 if (*sz == bufferEnd)
259 return;
260 ++*sz;
261 }
262
263 // parse a string, enclosed in quotation marks or not
264 inline bool AI_MD5_PARSE_STRING(const char **sz, const char *bufferEnd, aiString &out, int linenumber) {
265 bool bQuota = (**sz == '\"');
266 const char *szStart = *sz;
267 while (!IsSpaceOrNewLine(**sz)) {
268 ++*sz;
269 if (*sz == bufferEnd) break;
270 }
271 const char *szEnd = *sz;
272 if (bQuota) {
273 szStart++;
274 if ('\"' != *(szEnd -= 1)) {
275 MD5Parser::ReportWarning("Expected closing quotation marks in string", linenumber);
276 ++*sz;
277 }
278 }
279 out.length = (ai_uint32)(szEnd - szStart);
280 if (out.length >= AI_MAXLEN)
281 out.length = AI_MAXLEN - 1;
282 ::memcpy(out.data, szStart, out.length);
283 out.data[out.length] = '\0';
284
285 return true;
286 }
287
288 // parse a string, enclosed in quotation marks
289 inline void AI_MD5_PARSE_STRING_IN_QUOTATION(const char **sz, const char *bufferEnd, aiString &out) {
290 out.length = 0u;
291 while (('\"' != **sz && '\0' != **sz) && *sz != bufferEnd) {
292 ++*sz;
293 }
294 if ('\0' != **sz) {
295 const char *szStart = ++(*sz);
296
297 while (('\"' != **sz && '\0' != **sz) && *sz != bufferEnd) {
298 ++*sz;
299 }
300 if ('\0' != **sz) {
301 const char *szEnd = *sz;
302 ++*sz;
303 out.length = (ai_uint32)(szEnd - szStart);
304 if (out.length >= AI_MAXLEN)
305 out.length = AI_MAXLEN - 1;
306 ::memcpy(out.data, szStart, out.length);
307 }
308 }
309 out.data[out.length] = '\0';
310 }
311
312 // ------------------------------------------------------------------------------------------------
313 // .MD5MESH parsing function
314 MD5MeshParser::MD5MeshParser(SectionArray &mSections) {
315 ASSIMP_LOG_DEBUG("MD5MeshParser begin");
316
317 // now parse all sections
318 for (SectionArray::const_iterator iter = mSections.begin(), iterEnd = mSections.end(); iter != iterEnd; ++iter) {
319 if ((*iter).mName == "numMeshes") {
320 mMeshes.reserve(::strtoul10((*iter).mGlobalValue.c_str()));
321 } else if ((*iter).mName == "numJoints") {
322 mJoints.reserve(::strtoul10((*iter).mGlobalValue.c_str()));
323 } else if ((*iter).mName == "joints") {
324 // "origin" -1 ( -0.000000 0.016430 -0.006044 ) ( 0.707107 0.000000 0.707107 )
325 for (const auto &elem : (*iter).mElements) {
326 mJoints.emplace_back();
327 BoneDesc &desc = mJoints.back();
328
329 const char *sz = elem.szStart;
330 AI_MD5_PARSE_STRING_IN_QUOTATION(&sz, elem.end, desc.mName);
331
332 AI_MD5_SKIP_SPACES(&sz, elem.end, elem.iLineNumber);
333
334 // negative values, at least -1, is allowed here
335 desc.mParentIndex = (int)strtol10(sz, &sz);
336
337 AI_MD5_READ_TRIPLE(desc.mPositionXYZ, &sz, elem.end, elem.iLineNumber);
338 AI_MD5_READ_TRIPLE(desc.mRotationQuat, &sz, elem.end, elem.iLineNumber); // normalized quaternion, so w is not there
339 }
340 } else if ((*iter).mName == "mesh") {
341 mMeshes.emplace_back();
342 MeshDesc &desc = mMeshes.back();
343
344 for (const auto &elem : (*iter).mElements) {
345 const char *sz = elem.szStart;
346
347 // shader attribute
348 if (TokenMatch(sz, "shader", 6)) {
349 AI_MD5_SKIP_SPACES(&sz, elem.end, elem.iLineNumber);
350 AI_MD5_PARSE_STRING_IN_QUOTATION(&sz, elem.end, desc.mShader);
351 }
352 // numverts attribute
353 else if (TokenMatch(sz, "numverts", 8)) {
354 AI_MD5_SKIP_SPACES(&sz, elem.end, elem.iLineNumber);
355 desc.mVertices.resize(strtoul10(sz));
356 }
357 // numtris attribute
358 else if (TokenMatch(sz, "numtris", 7)) {
359 AI_MD5_SKIP_SPACES(&sz, elem.end, elem.iLineNumber);
360 desc.mFaces.resize(strtoul10(sz));
361 }
362 // numweights attribute
363 else if (TokenMatch(sz, "numweights", 10)) {
364 AI_MD5_SKIP_SPACES(&sz, elem.end, elem.iLineNumber);
365 desc.mWeights.resize(strtoul10(sz));
366 }
367 // vert attribute
368 // "vert 0 ( 0.394531 0.513672 ) 0 1"
369 else if (TokenMatch(sz, "vert", 4)) {
370 AI_MD5_SKIP_SPACES(&sz, elem.end, elem.iLineNumber);
371 const unsigned int idx = ::strtoul10(sz, &sz);
372 AI_MD5_SKIP_SPACES(&sz, elem.end, elem.iLineNumber);
373 if (idx >= desc.mVertices.size())
374 desc.mVertices.resize(idx + 1);
375
376 VertexDesc &vert = desc.mVertices[idx];
377 if ('(' != *sz++)
378 MD5Parser::ReportWarning("Unexpected token: ( was expected", elem.iLineNumber);
379 AI_MD5_SKIP_SPACES(&sz, elem.end, elem.iLineNumber);
380 sz = fast_atoreal_move(sz, vert.mUV.x);
381 AI_MD5_SKIP_SPACES(&sz, elem.end, elem.iLineNumber);
382 sz = fast_atoreal_move(sz, vert.mUV.y);
383 AI_MD5_SKIP_SPACES(&sz, elem.end, elem.iLineNumber);
384 if (')' != *sz++)
385 MD5Parser::ReportWarning("Unexpected token: ) was expected", elem.iLineNumber);
386 AI_MD5_SKIP_SPACES(&sz, elem.end, elem.iLineNumber);
387 vert.mFirstWeight = ::strtoul10(sz, &sz);
388 AI_MD5_SKIP_SPACES(&sz, elem.end, elem.iLineNumber);
389 vert.mNumWeights = ::strtoul10(sz, &sz);
390 }
391 // tri attribute
392 // "tri 0 15 13 12"
393 else if (TokenMatch(sz, "tri", 3)) {
394 AI_MD5_SKIP_SPACES(&sz, elem.end, elem.iLineNumber);
395 const unsigned int idx = strtoul10(sz, &sz);
396 if (idx >= desc.mFaces.size()) {
397 desc.mFaces.resize(idx + 1);
398 }
399
400 aiFace &face = desc.mFaces[idx];
401 if (face.mNumIndices != 3) {
402 delete [] face.mIndices;
403 face.mIndices = new unsigned int[face.mNumIndices = 3];
404 }
405 for (unsigned int i = 0; i < 3; ++i) {
406 AI_MD5_SKIP_SPACES(&sz, elem.end, elem.iLineNumber);
407 face.mIndices[i] = strtoul10(sz, &sz);
408 }
409 }
410 // weight attribute
411 // "weight 362 5 0.500000 ( -3.553583 11.893474 9.719339 )"
412 else if (TokenMatch(sz, "weight", 6)) {
413 AI_MD5_SKIP_SPACES(&sz, elem.end, elem.iLineNumber);
414 const unsigned int idx = strtoul10(sz, &sz);
415 AI_MD5_SKIP_SPACES(&sz, elem.end, elem.iLineNumber);
416 if (idx >= desc.mWeights.size())
417 desc.mWeights.resize(idx + 1);
418
419 WeightDesc &weight = desc.mWeights[idx];
420 weight.mBone = strtoul10(sz, &sz);
421 AI_MD5_SKIP_SPACES(&sz, elem.end, elem.iLineNumber);
422 sz = fast_atoreal_move(sz, weight.mWeight);
423 AI_MD5_READ_TRIPLE(weight.vOffsetPosition, &sz, elem.end, elem.iLineNumber);
424 }
425 }
426 }
427 }
428 ASSIMP_LOG_DEBUG("MD5MeshParser end");
429 }
430
431 // ------------------------------------------------------------------------------------------------
432 // .MD5ANIM parsing function
433 MD5AnimParser::MD5AnimParser(SectionArray &mSections) {
434 ASSIMP_LOG_DEBUG("MD5AnimParser begin");
435
436 fFrameRate = 24.0f;
437 mNumAnimatedComponents = UINT_MAX;
438 for (SectionArray::const_iterator iter = mSections.begin(), iterEnd = mSections.end(); iter != iterEnd; ++iter) {
439 if ((*iter).mName == "hierarchy") {
440 // "sheath" 0 63 6
441 for (const auto &elem : (*iter).mElements) {
442 mAnimatedBones.emplace_back();
443 AnimBoneDesc &desc = mAnimatedBones.back();
444
445 const char *sz = elem.szStart;
446 AI_MD5_PARSE_STRING_IN_QUOTATION(&sz, elem.end, desc.mName);
447 AI_MD5_SKIP_SPACES(&sz, elem.end, elem.iLineNumber);
448
449 // parent index - negative values are allowed (at least -1)
450 desc.mParentIndex = ::strtol10(sz, &sz);
451
452 // flags (highest is 2^6-1)
453 AI_MD5_SKIP_SPACES(&sz, elem.end, elem.iLineNumber);
454 if (63 < (desc.iFlags = ::strtoul10(sz, &sz))) {
455 MD5Parser::ReportWarning("Invalid flag combination in hierarchy section", elem.iLineNumber);
456 }
457 AI_MD5_SKIP_SPACES(& sz, elem.end, elem.iLineNumber);
458
459 // index of the first animation keyframe component for this joint
460 desc.iFirstKeyIndex = ::strtoul10(sz, &sz);
461 }
462 } else if ((*iter).mName == "baseframe") {
463 // ( -0.000000 0.016430 -0.006044 ) ( 0.707107 0.000242 0.707107 )
464 for (const auto &elem : (*iter).mElements) {
465 const char *sz = elem.szStart;
466
467 mBaseFrames.emplace_back();
468 BaseFrameDesc &desc = mBaseFrames.back();
469
470 AI_MD5_READ_TRIPLE(desc.vPositionXYZ, &sz, elem.end, elem.iLineNumber);
471 AI_MD5_READ_TRIPLE(desc.vRotationQuat, &sz, elem.end, elem.iLineNumber);
472 }
473 } else if ((*iter).mName == "frame") {
474 if (!(*iter).mGlobalValue.length()) {
475 MD5Parser::ReportWarning("A frame section must have a frame index", (*iter).iLineNumber);
476 continue;
477 }
478
479 mFrames.emplace_back();
480 FrameDesc &desc = mFrames.back();
481 desc.iIndex = strtoul10((*iter).mGlobalValue.c_str());
482
483 // we do already know how much storage we will presumably need
484 if (UINT_MAX != mNumAnimatedComponents) {
485 desc.mValues.reserve(mNumAnimatedComponents);
486 }
487
488 // now read all elements (continuous list of floats)
489 for (const auto &elem : (*iter).mElements) {
490 const char *sz = elem.szStart;
491 while (SkipSpacesAndLineEnd(&sz, elem.end)) {
492 float f;
493 sz = fast_atoreal_move(sz, f);
494 desc.mValues.push_back(f);
495 }
496 }
497 } else if ((*iter).mName == "numFrames") {
498 mFrames.reserve(strtoul10((*iter).mGlobalValue.c_str()));
499 } else if ((*iter).mName == "numJoints") {
500 const unsigned int num = strtoul10((*iter).mGlobalValue.c_str());
501 mAnimatedBones.reserve(num);
502
503 // try to guess the number of animated components if that element is not given
504 if (UINT_MAX == mNumAnimatedComponents) {
505 mNumAnimatedComponents = num * 6;
506 }
507 } else if ((*iter).mName == "numAnimatedComponents") {
508 mAnimatedBones.reserve(strtoul10((*iter).mGlobalValue.c_str()));
509 } else if ((*iter).mName == "frameRate") {
510 fast_atoreal_move((*iter).mGlobalValue.c_str(), fFrameRate);
511 }
512 }
513 ASSIMP_LOG_DEBUG("MD5AnimParser end");
514 }
515
516 // ------------------------------------------------------------------------------------------------
517 // .MD5CAMERA parsing function
518 MD5CameraParser::MD5CameraParser(SectionArray &mSections) {
519 ASSIMP_LOG_DEBUG("MD5CameraParser begin");
520 fFrameRate = 24.0f;
521
522 for (SectionArray::const_iterator iter = mSections.begin(), iterEnd = mSections.end(); iter != iterEnd; ++iter) {
523 if ((*iter).mName == "numFrames") {
524 frames.reserve(strtoul10((*iter).mGlobalValue.c_str()));
525 } else if ((*iter).mName == "frameRate") {
526 fFrameRate = fast_atof((*iter).mGlobalValue.c_str());
527 } else if ((*iter).mName == "numCuts") {
528 cuts.reserve(strtoul10((*iter).mGlobalValue.c_str()));
529 } else if ((*iter).mName == "cuts") {
530 for (const auto &elem : (*iter).mElements) {
531 cuts.push_back(strtoul10(elem.szStart) + 1);
532 }
533 } else if ((*iter).mName == "camera") {
534 for (const auto &elem : (*iter).mElements) {
535 const char *sz = elem.szStart;
536
537 frames.emplace_back();
538 CameraAnimFrameDesc &cur = frames.back();
539 AI_MD5_READ_TRIPLE(cur.vPositionXYZ, &sz, elem.end, elem.iLineNumber);
540 AI_MD5_READ_TRIPLE(cur.vRotationQuat, &sz, elem.end, elem.iLineNumber);
541 AI_MD5_SKIP_SPACES(&sz, elem.end, elem.iLineNumber);
542 cur.fFOV = fast_atof(sz);
543 }
544 }
545 }
546 ASSIMP_LOG_DEBUG("MD5CameraParser end");
547 }