FBXParser.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2025, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. /** @file FBXParser.cpp
  34. * @brief Implementation of the FBX parser and the rudimentary DOM that we use
  35. */
  36. #ifndef ASSIMP_BUILD_NO_FBX_IMPORTER
  37. #include "Common/Compression.h"
  38. #include "FBXTokenizer.h"
  39. #include "FBXParser.h"
  40. #include "FBXUtil.h"
  41. #include <assimp/ParsingUtils.h>
  42. #include <assimp/fast_atof.h>
  43. #include <assimp/ByteSwapper.h>
  44. #include <assimp/DefaultLogger.hpp>
  45. #include <iostream>
  46. using namespace Assimp;
  47. using namespace Assimp::FBX;
  48. namespace {
  49. // ------------------------------------------------------------------------------------------------
  50. // signal parse error, this is always unrecoverable. Throws DeadlyImportError.
  51. AI_WONT_RETURN void ParseError(const std::string& message, const Token& token) AI_WONT_RETURN_SUFFIX;
  52. AI_WONT_RETURN void ParseError(const std::string& message, const Token& token)
  53. {
  54. throw DeadlyImportError("FBX-Parser", Util::GetTokenText(&token), message);
  55. }
  56. // ------------------------------------------------------------------------------------------------
  57. AI_WONT_RETURN void ParseError(const std::string &message, const Element *element = nullptr) AI_WONT_RETURN_SUFFIX;
  58. AI_WONT_RETURN void ParseError(const std::string& message, const Element* element)
  59. {
  60. if(element) {
  61. ParseError(message,element->KeyToken());
  62. }
  63. throw DeadlyImportError("FBX-Parser ", message);
  64. }
  65. // ------------------------------------------------------------------------------------------------
  66. AI_WONT_RETURN void ParseError(const std::string& message, TokenPtr token) AI_WONT_RETURN_SUFFIX;
  67. void ParseError(const std::string& message, TokenPtr token)
  68. {
  69. if(token) {
  70. ParseError(message, *token);
  71. }
  72. ParseError(message);
  73. }
  74. // Initially, we did reinterpret_cast, breaking strict aliasing rules.
  75. // This actually caused trouble on Android, so let's be safe this time.
  76. // https://github.com/assimp/assimp/issues/24
  77. template <typename T>
  78. T SafeParse(const char* data, const char* end) {
  79. // Actual size validation happens during Tokenization so
  80. // this is valid as an assertion.
  81. (void)(end);
  82. ai_assert(static_cast<size_t>(end - data) >= sizeof(T));
  83. T result = static_cast<T>(0);
  84. ::memcpy(&result, data, sizeof(T));
  85. return result;
  86. }
  87. }
  88. namespace Assimp {
  89. namespace FBX {
  90. // ------------------------------------------------------------------------------------------------
  91. Element::Element(const Token& key_token, Parser& parser) :
  92. key_token(key_token), compound(nullptr)
  93. {
  94. TokenPtr n = nullptr;
  95. StackAllocator &allocator = parser.GetAllocator();
  96. do {
  97. n = parser.AdvanceToNextToken();
  98. if(!n) {
  99. ParseError("unexpected end of file, expected closing bracket",parser.LastToken());
  100. }
  101. if (n->Type() == TokenType_DATA) {
  102. tokens.push_back(n);
  103. TokenPtr prev = n;
  104. n = parser.AdvanceToNextToken();
  105. if(!n) {
  106. ParseError("unexpected end of file, expected bracket, comma or key",parser.LastToken());
  107. }
  108. const TokenType ty = n->Type();
  109. // some exporters are missing a comma on the next line
  110. if (ty == TokenType_DATA && prev->Type() == TokenType_DATA && (n->Line() == prev->Line() + 1)) {
  111. tokens.push_back(n);
  112. continue;
  113. }
  114. if (ty != TokenType_OPEN_BRACKET && ty != TokenType_CLOSE_BRACKET && ty != TokenType_COMMA && ty != TokenType_KEY) {
  115. ParseError("unexpected token; expected bracket, comma or key",n);
  116. }
  117. }
  118. if (n->Type() == TokenType_OPEN_BRACKET) {
  119. compound = new_Scope(parser);
  120. // current token should be a TOK_CLOSE_BRACKET
  121. n = parser.CurrentToken();
  122. ai_assert(n);
  123. if (n->Type() != TokenType_CLOSE_BRACKET) {
  124. ParseError("expected closing bracket",n);
  125. }
  126. parser.AdvanceToNextToken();
  127. return;
  128. }
  129. }
  130. while(n->Type() != TokenType_KEY && n->Type() != TokenType_CLOSE_BRACKET);
  131. }
  132. // ------------------------------------------------------------------------------------------------
  133. Element::~Element()
  134. {
  135. if (compound) {
  136. delete_Scope(compound);
  137. }
  138. // no need to delete tokens, they are owned by the parser
  139. }
  140. Scope::Scope(Parser& parser,bool topLevel)
  141. {
  142. if(!topLevel) {
  143. TokenPtr t = parser.CurrentToken();
  144. if (t->Type() != TokenType_OPEN_BRACKET) {
  145. ParseError("expected open bracket",t);
  146. }
  147. }
  148. StackAllocator &allocator = parser.GetAllocator();
  149. TokenPtr n = parser.AdvanceToNextToken();
  150. if (n == nullptr) {
  151. ParseError("unexpected end of file");
  152. }
  153. // note: empty scopes are allowed
  154. while(n->Type() != TokenType_CLOSE_BRACKET) {
  155. if (n->Type() != TokenType_KEY) {
  156. ParseError("unexpected token, expected TOK_KEY",n);
  157. }
  158. const std::string& str = n->StringContents();
  159. if (str.empty()) {
  160. ParseError("unexpected content: empty string.");
  161. }
  162. auto *element = new_Element(*n, parser);
  163. // Element() should stop at the next Key token (or right after a Close token)
  164. n = parser.CurrentToken();
  165. if (n == nullptr) {
  166. if (topLevel) {
  167. elements.insert(ElementMap::value_type(str, element));
  168. return;
  169. }
  170. delete_Element(element);
  171. ParseError("unexpected end of file",parser.LastToken());
  172. } else {
  173. elements.insert(ElementMap::value_type(str, element));
  174. }
  175. }
  176. }
  177. // ------------------------------------------------------------------------------------------------
  178. Scope::~Scope()
  179. {
  180. // This collection does not own the memory for the elements, but we need to call their d'tor:
  181. for (ElementMap::value_type &v : elements) {
  182. delete_Element(v.second);
  183. }
  184. }
  185. // ------------------------------------------------------------------------------------------------
  186. Parser::Parser(const TokenList &tokens, StackAllocator &allocator, bool is_binary) :
  187. tokens(tokens), allocator(allocator), last(), current(), cursor(tokens.begin()), is_binary(is_binary)
  188. {
  189. ASSIMP_LOG_DEBUG("Parsing FBX tokens");
  190. root = new_Scope(*this, true);
  191. }
  192. // ------------------------------------------------------------------------------------------------
  193. Parser::~Parser()
  194. {
  195. delete_Scope(root);
  196. }
  197. // ------------------------------------------------------------------------------------------------
  198. TokenPtr Parser::AdvanceToNextToken()
  199. {
  200. last = current;
  201. if (cursor == tokens.end()) {
  202. current = nullptr;
  203. } else {
  204. current = *cursor++;
  205. }
  206. return current;
  207. }
  208. // ------------------------------------------------------------------------------------------------
  209. TokenPtr Parser::CurrentToken() const
  210. {
  211. return current;
  212. }
  213. // ------------------------------------------------------------------------------------------------
  214. TokenPtr Parser::LastToken() const
  215. {
  216. return last;
  217. }
  218. // ------------------------------------------------------------------------------------------------
  219. uint64_t ParseTokenAsID(const Token& t, const char*& err_out)
  220. {
  221. err_out = nullptr;
  222. if (t.Type() != TokenType_DATA) {
  223. err_out = "expected TOK_DATA token";
  224. return 0L;
  225. }
  226. if(t.IsBinary())
  227. {
  228. const char* data = t.begin();
  229. if (data[0] != 'L') {
  230. err_out = "failed to parse ID, unexpected data type, expected L(ong) (binary)";
  231. return 0L;
  232. }
  233. BE_NCONST uint64_t id = SafeParse<uint64_t>(data+1, t.end());
  234. AI_SWAP8(id);
  235. return id;
  236. }
  237. // XXX: should use size_t here
  238. unsigned int length = static_cast<unsigned int>(t.end() - t.begin());
  239. ai_assert(length > 0);
  240. const char* out = nullptr;
  241. const uint64_t id = strtoul10_64(t.begin(),&out,&length);
  242. if (out > t.end()) {
  243. err_out = "failed to parse ID (text)";
  244. return 0L;
  245. }
  246. return id;
  247. }
  248. // ------------------------------------------------------------------------------------------------
  249. size_t ParseTokenAsDim(const Token& t, const char*& err_out)
  250. {
  251. // same as ID parsing, except there is a trailing asterisk
  252. err_out = nullptr;
  253. if (t.Type() != TokenType_DATA) {
  254. err_out = "expected TOK_DATA token";
  255. return 0;
  256. }
  257. if(t.IsBinary())
  258. {
  259. const char* data = t.begin();
  260. if (data[0] != 'L') {
  261. err_out = "failed to parse ID, unexpected data type, expected L(ong) (binary)";
  262. return 0;
  263. }
  264. BE_NCONST uint64_t id = SafeParse<uint64_t>(data+1, t.end());
  265. AI_SWAP8(id);
  266. return static_cast<size_t>(id);
  267. }
  268. if(*t.begin() != '*') {
  269. err_out = "expected asterisk before array dimension";
  270. return 0;
  271. }
  272. // XXX: should use size_t here
  273. unsigned int length = static_cast<unsigned int>(t.end() - t.begin());
  274. if(length == 0) {
  275. err_out = "expected valid integer number after asterisk";
  276. return 0;
  277. }
  278. const char* out = nullptr;
  279. const size_t id = static_cast<size_t>(strtoul10_64(t.begin() + 1,&out,&length));
  280. if (out > t.end()) {
  281. err_out = "failed to parse ID";
  282. return 0;
  283. }
  284. return id;
  285. }
  286. // ------------------------------------------------------------------------------------------------
  287. float ParseTokenAsFloat(const Token& t, const char*& err_out)
  288. {
  289. err_out = nullptr;
  290. if (t.Type() != TokenType_DATA) {
  291. err_out = "expected TOK_DATA token";
  292. return 0.0f;
  293. }
  294. if(t.IsBinary())
  295. {
  296. const char* data = t.begin();
  297. if (data[0] != 'F' && data[0] != 'D') {
  298. err_out = "failed to parse F(loat) or D(ouble), unexpected data type (binary)";
  299. return 0.0f;
  300. }
  301. if (data[0] == 'F') {
  302. return SafeParse<float>(data+1, t.end());
  303. }
  304. else {
  305. return static_cast<float>( SafeParse<double>(data+1, t.end()) );
  306. }
  307. }
  308. // need to copy the input string to a temporary buffer
  309. // first - next in the fbx token stream comes ',',
  310. // which fast_atof could interpret as decimal point.
  311. #define MAX_FLOAT_LENGTH 31
  312. const size_t length = static_cast<size_t>(t.end()-t.begin());
  313. if (length > MAX_FLOAT_LENGTH) {
  314. return 0.f;
  315. }
  316. char temp[MAX_FLOAT_LENGTH + 1];
  317. std::copy(t.begin(), t.end(), temp);
  318. temp[std::min(static_cast<size_t>(MAX_FLOAT_LENGTH),length)] = '\0';
  319. return fast_atof(temp);
  320. }
  321. // ------------------------------------------------------------------------------------------------
  322. int ParseTokenAsInt(const Token& t, const char*& err_out)
  323. {
  324. err_out = nullptr;
  325. if (t.Type() != TokenType_DATA) {
  326. err_out = "expected TOK_DATA token";
  327. return 0;
  328. }
  329. if(t.IsBinary())
  330. {
  331. const char* data = t.begin();
  332. if (data[0] != 'I') {
  333. err_out = "failed to parse I(nt), unexpected data type (binary)";
  334. return 0;
  335. }
  336. BE_NCONST int32_t ival = SafeParse<int32_t>(data+1, t.end());
  337. AI_SWAP4(ival);
  338. return static_cast<int>(ival);
  339. }
  340. ai_assert(static_cast<size_t>(t.end() - t.begin()) > 0);
  341. const char* out;
  342. const int intval = strtol10(t.begin(),&out);
  343. if (out != t.end()) {
  344. err_out = "failed to parse ID";
  345. return 0;
  346. }
  347. return intval;
  348. }
  349. // ------------------------------------------------------------------------------------------------
  350. int64_t ParseTokenAsInt64(const Token& t, const char*& err_out)
  351. {
  352. err_out = nullptr;
  353. if (t.Type() != TokenType_DATA) {
  354. err_out = "expected TOK_DATA token";
  355. return 0L;
  356. }
  357. if (t.IsBinary())
  358. {
  359. const char* data = t.begin();
  360. if (data[0] != 'L') {
  361. err_out = "failed to parse Int64, unexpected data type";
  362. return 0L;
  363. }
  364. BE_NCONST int64_t id = SafeParse<int64_t>(data + 1, t.end());
  365. AI_SWAP8(id);
  366. return id;
  367. }
  368. // XXX: should use size_t here
  369. unsigned int length = static_cast<unsigned int>(t.end() - t.begin());
  370. ai_assert(length > 0);
  371. const char* out = nullptr;
  372. const int64_t id = strtol10_64(t.begin(), &out, &length);
  373. if (out > t.end()) {
  374. err_out = "failed to parse Int64 (text)";
  375. return 0L;
  376. }
  377. return id;
  378. }
  379. // ------------------------------------------------------------------------------------------------
  380. std::string ParseTokenAsString(const Token& t, const char*& err_out)
  381. {
  382. err_out = nullptr;
  383. if (t.Type() != TokenType_DATA) {
  384. err_out = "expected TOK_DATA token";
  385. return std::string();
  386. }
  387. if(t.IsBinary())
  388. {
  389. const char* data = t.begin();
  390. if (data[0] != 'S') {
  391. err_out = "failed to parse S(tring), unexpected data type (binary)";
  392. return std::string();
  393. }
  394. // read string length
  395. BE_NCONST int32_t len = SafeParse<int32_t>(data+1, t.end());
  396. AI_SWAP4(len);
  397. ai_assert(t.end() - data == 5 + len);
  398. return std::string(data + 5, len);
  399. }
  400. const size_t length = static_cast<size_t>(t.end() - t.begin());
  401. if(length < 2) {
  402. err_out = "token is too short to hold a string";
  403. return std::string();
  404. }
  405. const char* s = t.begin(), *e = t.end() - 1;
  406. if (*s != '\"' || *e != '\"') {
  407. err_out = "expected double quoted string";
  408. return std::string();
  409. }
  410. return std::string(s+1,length-2);
  411. }
  412. namespace {
  413. // ------------------------------------------------------------------------------------------------
  414. // read the type code and element count of a binary data array and stop there
  415. void ReadBinaryDataArrayHead(const char*& data, const char* end, char& type, uint32_t& count,
  416. const Element& el)
  417. {
  418. if (static_cast<size_t>(end-data) < 5) {
  419. ParseError("binary data array is too short, need five (5) bytes for type signature and element count",&el);
  420. }
  421. // data type
  422. type = *data;
  423. // read number of elements
  424. BE_NCONST uint32_t len = SafeParse<uint32_t>(data+1, end);
  425. AI_SWAP4(len);
  426. count = len;
  427. data += 5;
  428. }
  429. // ------------------------------------------------------------------------------------------------
  430. // read binary data array, assume cursor points to the 'compression mode' field (i.e. behind the header)
  431. void ReadBinaryDataArray(char type, uint32_t count, const char*& data, const char* end,
  432. std::vector<char>& buff, const Element& /*el*/) {
  433. BE_NCONST uint32_t encmode = SafeParse<uint32_t>(data, end);
  434. AI_SWAP4(encmode);
  435. data += 4;
  436. // next comes the compressed length
  437. BE_NCONST uint32_t comp_len = SafeParse<uint32_t>(data, end);
  438. AI_SWAP4(comp_len);
  439. data += 4;
  440. ai_assert(data + comp_len == end);
  441. // determine the length of the uncompressed data by looking at the type signature
  442. uint32_t stride = 0;
  443. switch(type)
  444. {
  445. case 'f':
  446. case 'i':
  447. stride = 4;
  448. break;
  449. case 'd':
  450. case 'l':
  451. stride = 8;
  452. break;
  453. default:
  454. ai_assert(false);
  455. };
  456. const uint32_t full_length = stride * count;
  457. buff.resize(full_length);
  458. if(encmode == 0) {
  459. ai_assert(full_length == comp_len);
  460. // plain data, no compression
  461. std::copy(data, end, buff.begin());
  462. }
  463. else if(encmode == 1) {
  464. // zlib/deflate, next comes ZIP head (0x78 0x01)
  465. // see http://www.ietf.org/rfc/rfc1950.txt
  466. Compression compress;
  467. if (compress.open(Compression::Format::Binary, Compression::FlushMode::Finish, 0)) {
  468. compress.decompress(data, comp_len, buff);
  469. compress.close();
  470. }
  471. }
  472. #ifdef ASSIMP_BUILD_DEBUG
  473. else {
  474. // runtime check for this happens at tokenization stage
  475. ai_assert(false);
  476. }
  477. #endif
  478. data += comp_len;
  479. ai_assert(data == end);
  480. }
  481. } // !anon
  482. // ------------------------------------------------------------------------------------------------
  483. // read an array of float3 tuples
  484. void ParseVectorDataArray(std::vector<aiVector3D>& out, const Element& el)
  485. {
  486. out.resize( 0 );
  487. const TokenList& tok = el.Tokens();
  488. if(tok.empty()) {
  489. ParseError("unexpected empty element",&el);
  490. }
  491. if(tok[0]->IsBinary()) {
  492. const char* data = tok[0]->begin(), *end = tok[0]->end();
  493. char type;
  494. uint32_t count;
  495. ReadBinaryDataArrayHead(data, end, type, count, el);
  496. if(count % 3 != 0) {
  497. ParseError("number of floats is not a multiple of three (3) (binary)",&el);
  498. }
  499. if(!count) {
  500. return;
  501. }
  502. if (type != 'd' && type != 'f') {
  503. ParseError("expected float or double array (binary)",&el);
  504. }
  505. std::vector<char> buff;
  506. ReadBinaryDataArray(type, count, data, end, buff, el);
  507. ai_assert(data == end);
  508. uint64_t dataToRead = static_cast<uint64_t>(count) * (type == 'd' ? 8 : 4);
  509. if (dataToRead != buff.size()) {
  510. ParseError("Invalid read size (binary)",&el);
  511. }
  512. const uint32_t count3 = count / 3;
  513. out.reserve(count3);
  514. if (type == 'd') {
  515. const double* d = reinterpret_cast<const double*>(&buff[0]);
  516. for (unsigned int i = 0; i < count3; ++i, d += 3) {
  517. out.emplace_back(static_cast<ai_real>(d[0]),
  518. static_cast<ai_real>(d[1]),
  519. static_cast<ai_real>(d[2]));
  520. }
  521. // for debugging
  522. /*for ( size_t i = 0; i < out.size(); i++ ) {
  523. aiVector3D vec3( out[ i ] );
  524. std::stringstream stream;
  525. stream << " vec3.x = " << vec3.x << " vec3.y = " << vec3.y << " vec3.z = " << vec3.z << std::endl;
  526. DefaultLogger::get()->info( stream.str() );
  527. }*/
  528. }
  529. else if (type == 'f') {
  530. const float* f = reinterpret_cast<const float*>(&buff[0]);
  531. for (unsigned int i = 0; i < count3; ++i, f += 3) {
  532. out.emplace_back(f[0],f[1],f[2]);
  533. }
  534. }
  535. return;
  536. }
  537. const size_t dim = ParseTokenAsDim(*tok[0]);
  538. // may throw bad_alloc if the input is rubbish, but this need
  539. // not to be prevented - importing would fail but we wouldn't
  540. // crash since assimp handles this case properly.
  541. out.reserve(dim);
  542. const Scope& scope = GetRequiredScope(el);
  543. const Element& a = GetRequiredElement(scope,"a",&el);
  544. if (a.Tokens().size() % 3 != 0) {
  545. ParseError("number of floats is not a multiple of three (3)",&el);
  546. }
  547. for (TokenList::const_iterator it = a.Tokens().begin(), end = a.Tokens().end(); it != end; ) {
  548. aiVector3D v;
  549. v.x = ParseTokenAsFloat(**it++);
  550. v.y = ParseTokenAsFloat(**it++);
  551. v.z = ParseTokenAsFloat(**it++);
  552. out.push_back(v);
  553. }
  554. }
  555. // ------------------------------------------------------------------------------------------------
  556. // read an array of color4 tuples
  557. void ParseVectorDataArray(std::vector<aiColor4D>& out, const Element& el)
  558. {
  559. out.resize( 0 );
  560. const TokenList& tok = el.Tokens();
  561. if(tok.empty()) {
  562. ParseError("unexpected empty element",&el);
  563. }
  564. if(tok[0]->IsBinary()) {
  565. const char* data = tok[0]->begin(), *end = tok[0]->end();
  566. char type;
  567. uint32_t count;
  568. ReadBinaryDataArrayHead(data, end, type, count, el);
  569. if(count % 4 != 0) {
  570. ParseError("number of floats is not a multiple of four (4) (binary)",&el);
  571. }
  572. if(!count) {
  573. return;
  574. }
  575. if (type != 'd' && type != 'f') {
  576. ParseError("expected float or double array (binary)",&el);
  577. }
  578. std::vector<char> buff;
  579. ReadBinaryDataArray(type, count, data, end, buff, el);
  580. ai_assert(data == end);
  581. uint64_t dataToRead = static_cast<uint64_t>(count) * (type == 'd' ? 8 : 4);
  582. if (dataToRead != buff.size()) {
  583. ParseError("Invalid read size (binary)",&el);
  584. }
  585. const uint32_t count4 = count / 4;
  586. out.reserve(count4);
  587. if (type == 'd') {
  588. const double* d = reinterpret_cast<const double*>(&buff[0]);
  589. for (unsigned int i = 0; i < count4; ++i, d += 4) {
  590. out.emplace_back(static_cast<float>(d[0]),
  591. static_cast<float>(d[1]),
  592. static_cast<float>(d[2]),
  593. static_cast<float>(d[3]));
  594. }
  595. }
  596. else if (type == 'f') {
  597. const float* f = reinterpret_cast<const float*>(&buff[0]);
  598. for (unsigned int i = 0; i < count4; ++i, f += 4) {
  599. out.emplace_back(f[0],f[1],f[2],f[3]);
  600. }
  601. }
  602. return;
  603. }
  604. const size_t dim = ParseTokenAsDim(*tok[0]);
  605. // see notes in ParseVectorDataArray() above
  606. out.reserve(dim);
  607. const Scope& scope = GetRequiredScope(el);
  608. const Element& a = GetRequiredElement(scope,"a",&el);
  609. if (a.Tokens().size() % 4 != 0) {
  610. ParseError("number of floats is not a multiple of four (4)",&el);
  611. }
  612. for (TokenList::const_iterator it = a.Tokens().begin(), end = a.Tokens().end(); it != end; ) {
  613. aiColor4D v;
  614. v.r = ParseTokenAsFloat(**it++);
  615. v.g = ParseTokenAsFloat(**it++);
  616. v.b = ParseTokenAsFloat(**it++);
  617. v.a = ParseTokenAsFloat(**it++);
  618. out.push_back(v);
  619. }
  620. }
  621. // ------------------------------------------------------------------------------------------------
  622. // read an array of float2 tuples
  623. void ParseVectorDataArray(std::vector<aiVector2D>& out, const Element& el) {
  624. out.resize( 0 );
  625. const TokenList& tok = el.Tokens();
  626. if(tok.empty()) {
  627. ParseError("unexpected empty element",&el);
  628. }
  629. if(tok[0]->IsBinary()) {
  630. const char* data = tok[0]->begin(), *end = tok[0]->end();
  631. char type;
  632. uint32_t count;
  633. ReadBinaryDataArrayHead(data, end, type, count, el);
  634. if(count % 2 != 0) {
  635. ParseError("number of floats is not a multiple of two (2) (binary)",&el);
  636. }
  637. if(!count) {
  638. return;
  639. }
  640. if (type != 'd' && type != 'f') {
  641. ParseError("expected float or double array (binary)",&el);
  642. }
  643. std::vector<char> buff;
  644. ReadBinaryDataArray(type, count, data, end, buff, el);
  645. ai_assert(data == end);
  646. uint64_t dataToRead = static_cast<uint64_t>(count) * (type == 'd' ? 8 : 4);
  647. if (dataToRead != buff.size()) {
  648. ParseError("Invalid read size (binary)",&el);
  649. }
  650. const uint32_t count2 = count / 2;
  651. out.reserve(count2);
  652. if (type == 'd') {
  653. const double* d = reinterpret_cast<const double*>(&buff[0]);
  654. for (unsigned int i = 0; i < count2; ++i, d += 2) {
  655. out.emplace_back(static_cast<float>(d[0]),
  656. static_cast<float>(d[1]));
  657. }
  658. } else if (type == 'f') {
  659. const float* f = reinterpret_cast<const float*>(&buff[0]);
  660. for (unsigned int i = 0; i < count2; ++i, f += 2) {
  661. out.emplace_back(f[0],f[1]);
  662. }
  663. }
  664. return;
  665. }
  666. const size_t dim = ParseTokenAsDim(*tok[0]);
  667. // see notes in ParseVectorDataArray() above
  668. out.reserve(dim);
  669. const Scope& scope = GetRequiredScope(el);
  670. const Element& a = GetRequiredElement(scope,"a",&el);
  671. if (a.Tokens().size() % 2 != 0) {
  672. ParseError("number of floats is not a multiple of two (2)",&el);
  673. }
  674. for (TokenList::const_iterator it = a.Tokens().begin(), end = a.Tokens().end(); it != end; ) {
  675. aiVector2D v;
  676. v.x = ParseTokenAsFloat(**it++);
  677. v.y = ParseTokenAsFloat(**it++);
  678. out.push_back(v);
  679. }
  680. }
  681. // ------------------------------------------------------------------------------------------------
  682. // read an array of ints
  683. void ParseVectorDataArray(std::vector<int>& out, const Element& el) {
  684. out.resize( 0 );
  685. const TokenList& tok = el.Tokens();
  686. if(tok.empty()) {
  687. ParseError("unexpected empty element",&el);
  688. }
  689. if(tok[0]->IsBinary()) {
  690. const char* data = tok[0]->begin(), *end = tok[0]->end();
  691. char type;
  692. uint32_t count;
  693. ReadBinaryDataArrayHead(data, end, type, count, el);
  694. if(!count) {
  695. return;
  696. }
  697. if (type != 'i') {
  698. ParseError("expected int array (binary)",&el);
  699. }
  700. std::vector<char> buff;
  701. ReadBinaryDataArray(type, count, data, end, buff, el);
  702. ai_assert(data == end);
  703. uint64_t dataToRead = static_cast<uint64_t>(count) * 4;
  704. if (dataToRead != buff.size()) {
  705. ParseError("Invalid read size (binary)",&el);
  706. }
  707. out.reserve(count);
  708. const int32_t* ip = reinterpret_cast<const int32_t*>(&buff[0]);
  709. for (unsigned int i = 0; i < count; ++i, ++ip) {
  710. BE_NCONST int32_t val = *ip;
  711. AI_SWAP4(val);
  712. out.push_back(val);
  713. }
  714. return;
  715. }
  716. const size_t dim = ParseTokenAsDim(*tok[0]);
  717. // see notes in ParseVectorDataArray()
  718. out.reserve(dim);
  719. const Scope& scope = GetRequiredScope(el);
  720. const Element& a = GetRequiredElement(scope,"a",&el);
  721. for (TokenList::const_iterator it = a.Tokens().begin(), end = a.Tokens().end(); it != end; ) {
  722. const int ival = ParseTokenAsInt(**it++);
  723. out.push_back(ival);
  724. }
  725. }
  726. // ------------------------------------------------------------------------------------------------
  727. // read an array of floats
  728. void ParseVectorDataArray(std::vector<float>& out, const Element& el)
  729. {
  730. out.resize( 0 );
  731. const TokenList& tok = el.Tokens();
  732. if(tok.empty()) {
  733. ParseError("unexpected empty element",&el);
  734. }
  735. if(tok[0]->IsBinary()) {
  736. const char* data = tok[0]->begin(), *end = tok[0]->end();
  737. char type;
  738. uint32_t count;
  739. ReadBinaryDataArrayHead(data, end, type, count, el);
  740. if(!count) {
  741. return;
  742. }
  743. if (type != 'd' && type != 'f') {
  744. ParseError("expected float or double array (binary)",&el);
  745. }
  746. std::vector<char> buff;
  747. ReadBinaryDataArray(type, count, data, end, buff, el);
  748. ai_assert(data == end);
  749. uint64_t dataToRead = static_cast<uint64_t>(count) * (type == 'd' ? 8 : 4);
  750. if (dataToRead != buff.size()) {
  751. ParseError("Invalid read size (binary)",&el);
  752. }
  753. if (type == 'd') {
  754. const double* d = reinterpret_cast<const double*>(&buff[0]);
  755. for (unsigned int i = 0; i < count; ++i, ++d) {
  756. out.push_back(static_cast<float>(*d));
  757. }
  758. }
  759. else if (type == 'f') {
  760. const float* f = reinterpret_cast<const float*>(&buff[0]);
  761. for (unsigned int i = 0; i < count; ++i, ++f) {
  762. out.push_back(*f);
  763. }
  764. }
  765. return;
  766. }
  767. const size_t dim = ParseTokenAsDim(*tok[0]);
  768. // see notes in ParseVectorDataArray()
  769. out.reserve(dim);
  770. const Scope& scope = GetRequiredScope(el);
  771. const Element& a = GetRequiredElement(scope,"a",&el);
  772. for (TokenList::const_iterator it = a.Tokens().begin(), end = a.Tokens().end(); it != end; ) {
  773. const float ival = ParseTokenAsFloat(**it++);
  774. out.push_back(ival);
  775. }
  776. }
  777. // ------------------------------------------------------------------------------------------------
  778. // read an array of uints
  779. void ParseVectorDataArray(std::vector<unsigned int>& out, const Element& el) {
  780. out.resize( 0 );
  781. const TokenList& tok = el.Tokens();
  782. if(tok.empty()) {
  783. ParseError("unexpected empty element",&el);
  784. }
  785. if(tok[0]->IsBinary()) {
  786. const char* data = tok[0]->begin(), *end = tok[0]->end();
  787. char type;
  788. uint32_t count;
  789. ReadBinaryDataArrayHead(data, end, type, count, el);
  790. if(!count) {
  791. return;
  792. }
  793. if (type != 'i') {
  794. ParseError("expected (u)int array (binary)",&el);
  795. }
  796. std::vector<char> buff;
  797. ReadBinaryDataArray(type, count, data, end, buff, el);
  798. ai_assert(data == end);
  799. uint64_t dataToRead = static_cast<uint64_t>(count) * 4;
  800. if (dataToRead != buff.size()) {
  801. ParseError("Invalid read size (binary)",&el);
  802. }
  803. out.reserve(count);
  804. const int32_t* ip = reinterpret_cast<const int32_t*>(&buff[0]);
  805. for (unsigned int i = 0; i < count; ++i, ++ip) {
  806. BE_NCONST int32_t val = *ip;
  807. if(val < 0) {
  808. ParseError("encountered negative integer index (binary)");
  809. }
  810. AI_SWAP4(val);
  811. out.push_back(val);
  812. }
  813. return;
  814. }
  815. const size_t dim = ParseTokenAsDim(*tok[0]);
  816. // see notes in ParseVectorDataArray()
  817. out.reserve(dim);
  818. const Scope& scope = GetRequiredScope(el);
  819. const Element& a = GetRequiredElement(scope,"a",&el);
  820. for (TokenList::const_iterator it = a.Tokens().begin(), end = a.Tokens().end(); it != end; ) {
  821. const int ival = ParseTokenAsInt(**it++);
  822. if(ival < 0) {
  823. ParseError("encountered negative integer index");
  824. }
  825. out.push_back(static_cast<unsigned int>(ival));
  826. }
  827. }
  828. // ------------------------------------------------------------------------------------------------
  829. // read an array of uint64_ts
  830. void ParseVectorDataArray(std::vector<uint64_t>& out, const Element& el)
  831. {
  832. out.resize( 0 );
  833. const TokenList& tok = el.Tokens();
  834. if(tok.empty()) {
  835. ParseError("unexpected empty element",&el);
  836. }
  837. if(tok[0]->IsBinary()) {
  838. const char* data = tok[0]->begin(), *end = tok[0]->end();
  839. char type;
  840. uint32_t count;
  841. ReadBinaryDataArrayHead(data, end, type, count, el);
  842. if(!count) {
  843. return;
  844. }
  845. if (type != 'l') {
  846. ParseError("expected long array (binary)",&el);
  847. }
  848. std::vector<char> buff;
  849. ReadBinaryDataArray(type, count, data, end, buff, el);
  850. ai_assert(data == end);
  851. uint64_t dataToRead = static_cast<uint64_t>(count) * 8;
  852. if (dataToRead != buff.size()) {
  853. ParseError("Invalid read size (binary)",&el);
  854. }
  855. out.reserve(count);
  856. const uint64_t* ip = reinterpret_cast<const uint64_t*>(&buff[0]);
  857. for (unsigned int i = 0; i < count; ++i, ++ip) {
  858. BE_NCONST uint64_t val = *ip;
  859. AI_SWAP8(val);
  860. out.push_back(val);
  861. }
  862. return;
  863. }
  864. const size_t dim = ParseTokenAsDim(*tok[0]);
  865. // see notes in ParseVectorDataArray()
  866. out.reserve(dim);
  867. const Scope& scope = GetRequiredScope(el);
  868. const Element& a = GetRequiredElement(scope,"a",&el);
  869. for (TokenList::const_iterator it = a.Tokens().begin(), end = a.Tokens().end(); it != end; ) {
  870. const uint64_t ival = ParseTokenAsID(**it++);
  871. out.push_back(ival);
  872. }
  873. }
  874. // ------------------------------------------------------------------------------------------------
  875. // read an array of int64_ts
  876. void ParseVectorDataArray(std::vector<int64_t>& out, const Element& el)
  877. {
  878. out.resize( 0 );
  879. const TokenList& tok = el.Tokens();
  880. if (tok.empty()) {
  881. ParseError("unexpected empty element", &el);
  882. }
  883. if (tok[0]->IsBinary()) {
  884. const char* data = tok[0]->begin(), *end = tok[0]->end();
  885. char type;
  886. uint32_t count;
  887. ReadBinaryDataArrayHead(data, end, type, count, el);
  888. if (!count) {
  889. return;
  890. }
  891. if (type != 'l') {
  892. ParseError("expected long array (binary)", &el);
  893. }
  894. std::vector<char> buff;
  895. ReadBinaryDataArray(type, count, data, end, buff, el);
  896. ai_assert(data == end);
  897. uint64_t dataToRead = static_cast<uint64_t>(count) * 8;
  898. if (dataToRead != buff.size()) {
  899. ParseError("Invalid read size (binary)",&el);
  900. }
  901. out.reserve(count);
  902. const int64_t* ip = reinterpret_cast<const int64_t*>(&buff[0]);
  903. for (unsigned int i = 0; i < count; ++i, ++ip) {
  904. BE_NCONST int64_t val = *ip;
  905. AI_SWAP8(val);
  906. out.push_back(val);
  907. }
  908. return;
  909. }
  910. const size_t dim = ParseTokenAsDim(*tok[0]);
  911. // see notes in ParseVectorDataArray()
  912. out.reserve(dim);
  913. const Scope& scope = GetRequiredScope(el);
  914. const Element& a = GetRequiredElement(scope, "a", &el);
  915. for (TokenList::const_iterator it = a.Tokens().begin(), end = a.Tokens().end(); it != end;) {
  916. const int64_t ival = ParseTokenAsInt64(**it++);
  917. out.push_back(ival);
  918. }
  919. }
  920. // ------------------------------------------------------------------------------------------------
  921. aiMatrix4x4 ReadMatrix(const Element& element)
  922. {
  923. std::vector<float> values;
  924. ParseVectorDataArray(values,element);
  925. if(values.size() != 16) {
  926. ParseError("expected 16 matrix elements");
  927. }
  928. aiMatrix4x4 result;
  929. result.a1 = values[0];
  930. result.a2 = values[1];
  931. result.a3 = values[2];
  932. result.a4 = values[3];
  933. result.b1 = values[4];
  934. result.b2 = values[5];
  935. result.b3 = values[6];
  936. result.b4 = values[7];
  937. result.c1 = values[8];
  938. result.c2 = values[9];
  939. result.c3 = values[10];
  940. result.c4 = values[11];
  941. result.d1 = values[12];
  942. result.d2 = values[13];
  943. result.d3 = values[14];
  944. result.d4 = values[15];
  945. result.Transpose();
  946. return result;
  947. }
  948. // ------------------------------------------------------------------------------------------------
  949. // wrapper around ParseTokenAsString() with ParseError handling
  950. std::string ParseTokenAsString(const Token& t)
  951. {
  952. const char* err;
  953. const std::string& i = ParseTokenAsString(t,err);
  954. if(err) {
  955. ParseError(err,t);
  956. }
  957. return i;
  958. }
  959. bool HasElement( const Scope& sc, const std::string& index ) {
  960. const Element* el = sc[ index ];
  961. if ( nullptr == el ) {
  962. return false;
  963. }
  964. return true;
  965. }
  966. // ------------------------------------------------------------------------------------------------
  967. // extract a required element from a scope, abort if the element cannot be found
  968. const Element& GetRequiredElement(const Scope& sc, const std::string& index, const Element* element /*= nullptr*/)
  969. {
  970. const Element* el = sc[index];
  971. if(!el) {
  972. ParseError("did not find required element \"" + index + "\"",element);
  973. }
  974. return *el;
  975. }
  976. // ------------------------------------------------------------------------------------------------
  977. // extract required compound scope
  978. const Scope& GetRequiredScope(const Element& el)
  979. {
  980. const Scope* const s = el.Compound();
  981. if(!s) {
  982. ParseError("expected compound scope",&el);
  983. }
  984. return *s;
  985. }
  986. // ------------------------------------------------------------------------------------------------
  987. // get token at a particular index
  988. const Token& GetRequiredToken(const Element& el, unsigned int index)
  989. {
  990. const TokenList& t = el.Tokens();
  991. if(index >= t.size()) {
  992. ParseError(Formatter::format( "missing token at index " ) << index,&el);
  993. }
  994. return *t[index];
  995. }
  996. // ------------------------------------------------------------------------------------------------
  997. // wrapper around ParseTokenAsID() with ParseError handling
  998. uint64_t ParseTokenAsID(const Token& t)
  999. {
  1000. const char* err;
  1001. const uint64_t i = ParseTokenAsID(t,err);
  1002. if(err) {
  1003. ParseError(err,t);
  1004. }
  1005. return i;
  1006. }
  1007. // ------------------------------------------------------------------------------------------------
  1008. // wrapper around ParseTokenAsDim() with ParseError handling
  1009. size_t ParseTokenAsDim(const Token& t)
  1010. {
  1011. const char* err;
  1012. const size_t i = ParseTokenAsDim(t,err);
  1013. if(err) {
  1014. ParseError(err,t);
  1015. }
  1016. return i;
  1017. }
  1018. // ------------------------------------------------------------------------------------------------
  1019. // wrapper around ParseTokenAsFloat() with ParseError handling
  1020. float ParseTokenAsFloat(const Token& t)
  1021. {
  1022. const char* err;
  1023. const float i = ParseTokenAsFloat(t,err);
  1024. if(err) {
  1025. ParseError(err,t);
  1026. }
  1027. return i;
  1028. }
  1029. // ------------------------------------------------------------------------------------------------
  1030. // wrapper around ParseTokenAsInt() with ParseError handling
  1031. int ParseTokenAsInt(const Token& t)
  1032. {
  1033. const char* err;
  1034. const int i = ParseTokenAsInt(t,err);
  1035. if(err) {
  1036. ParseError(err,t);
  1037. }
  1038. return i;
  1039. }
  1040. // ------------------------------------------------------------------------------------------------
  1041. // wrapper around ParseTokenAsInt64() with ParseError handling
  1042. int64_t ParseTokenAsInt64(const Token& t)
  1043. {
  1044. const char* err;
  1045. const int64_t i = ParseTokenAsInt64(t, err);
  1046. if (err) {
  1047. ParseError(err, t);
  1048. }
  1049. return i;
  1050. }
  1051. } // !FBX
  1052. } // !Assimp
  1053. #endif