FBXParser.cpp 37 KB

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