FBXParser.cpp 37 KB

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