BaseImporter.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2021, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file BaseImporter.cpp
  35. * @brief Implementation of BaseImporter
  36. */
  37. #include "FileSystemFilter.h"
  38. #include "Importer.h"
  39. #include <assimp/BaseImporter.h>
  40. #include <assimp/ByteSwapper.h>
  41. #include <assimp/ParsingUtils.h>
  42. #include <assimp/importerdesc.h>
  43. #include <assimp/postprocess.h>
  44. #include <assimp/scene.h>
  45. #include <assimp/Importer.hpp>
  46. #include <cctype>
  47. #include <ios>
  48. #include <list>
  49. #include <memory>
  50. #include <sstream>
  51. using namespace Assimp;
  52. // ------------------------------------------------------------------------------------------------
  53. // Constructor to be privately used by Importer
  54. BaseImporter::BaseImporter() AI_NO_EXCEPT
  55. : m_progress() {
  56. }
  57. // ------------------------------------------------------------------------------------------------
  58. // Destructor, private as well
  59. BaseImporter::~BaseImporter() {
  60. // nothing to do here
  61. }
  62. void BaseImporter::UpdateImporterScale(Importer *pImp) {
  63. ai_assert(pImp != nullptr);
  64. ai_assert(importerScale != 0.0);
  65. ai_assert(fileScale != 0.0);
  66. double activeScale = importerScale * fileScale;
  67. // Set active scaling
  68. pImp->SetPropertyFloat(AI_CONFIG_APP_SCALE_KEY, static_cast<float>(activeScale));
  69. ASSIMP_LOG_DEBUG("UpdateImporterScale scale set: ", activeScale);
  70. }
  71. // ------------------------------------------------------------------------------------------------
  72. // Imports the given file and returns the imported data.
  73. aiScene *BaseImporter::ReadFile(Importer *pImp, const std::string &pFile, IOSystem *pIOHandler) {
  74. m_progress = pImp->GetProgressHandler();
  75. if (nullptr == m_progress) {
  76. return nullptr;
  77. }
  78. ai_assert(m_progress);
  79. // Gather configuration properties for this run
  80. SetupProperties(pImp);
  81. // Construct a file system filter to improve our success ratio at reading external files
  82. FileSystemFilter filter(pFile, pIOHandler);
  83. // create a scene object to hold the data
  84. std::unique_ptr<aiScene> sc(new aiScene());
  85. // dispatch importing
  86. try {
  87. InternReadFile(pFile, sc.get(), &filter);
  88. // Calculate import scale hook - required because pImp not available anywhere else
  89. // passes scale into ScaleProcess
  90. UpdateImporterScale(pImp);
  91. } catch( const std::exception &err ) {
  92. // extract error description
  93. m_ErrorText = err.what();
  94. ASSIMP_LOG_ERROR(err.what());
  95. m_Exception = std::current_exception();
  96. return nullptr;
  97. }
  98. // return what we gathered from the import.
  99. return sc.release();
  100. }
  101. // ------------------------------------------------------------------------------------------------
  102. void BaseImporter::SetupProperties(const Importer *) {
  103. // the default implementation does nothing
  104. }
  105. // ------------------------------------------------------------------------------------------------
  106. void BaseImporter::GetExtensionList(std::set<std::string> &extensions) {
  107. const aiImporterDesc *desc = GetInfo();
  108. ai_assert(desc != nullptr);
  109. const char *ext = desc->mFileExtensions;
  110. ai_assert(ext != nullptr);
  111. const char *last = ext;
  112. do {
  113. if (!*ext || *ext == ' ') {
  114. extensions.insert(std::string(last, ext - last));
  115. ai_assert(ext - last > 0);
  116. last = ext;
  117. while (*last == ' ') {
  118. ++last;
  119. }
  120. }
  121. } while (*ext++);
  122. }
  123. // ------------------------------------------------------------------------------------------------
  124. /*static*/ bool BaseImporter::SearchFileHeaderForToken(IOSystem *pIOHandler,
  125. const std::string &pFile,
  126. const char **tokens,
  127. unsigned int numTokens,
  128. unsigned int searchBytes /* = 200 */,
  129. bool tokensSol /* false */,
  130. bool noAlphaBeforeTokens /* false */) {
  131. ai_assert(nullptr != tokens);
  132. ai_assert(0 != numTokens);
  133. ai_assert(0 != searchBytes);
  134. if (nullptr == pIOHandler) {
  135. return false;
  136. }
  137. std::unique_ptr<IOStream> pStream(pIOHandler->Open(pFile));
  138. if (pStream) {
  139. // read 200 characters from the file
  140. std::unique_ptr<char[]> _buffer(new char[searchBytes + 1 /* for the '\0' */]);
  141. char *buffer(_buffer.get());
  142. const size_t read(pStream->Read(buffer, 1, searchBytes));
  143. if (0 == read) {
  144. return false;
  145. }
  146. for (size_t i = 0; i < read; ++i) {
  147. buffer[i] = static_cast<char>(::tolower((unsigned char)buffer[i]));
  148. }
  149. // It is not a proper handling of unicode files here ...
  150. // ehm ... but it works in most cases.
  151. char *cur = buffer, *cur2 = buffer, *end = &buffer[read];
  152. while (cur != end) {
  153. if (*cur) {
  154. *cur2++ = *cur;
  155. }
  156. ++cur;
  157. }
  158. *cur2 = '\0';
  159. std::string token;
  160. for (unsigned int i = 0; i < numTokens; ++i) {
  161. ai_assert(nullptr != tokens[i]);
  162. const size_t len(strlen(tokens[i]));
  163. token.clear();
  164. const char *ptr(tokens[i]);
  165. for (size_t tokIdx = 0; tokIdx < len; ++tokIdx) {
  166. token.push_back(static_cast<char>(tolower(static_cast<unsigned char>(*ptr))));
  167. ++ptr;
  168. }
  169. const char *r = strstr(buffer, token.c_str());
  170. if (!r) {
  171. continue;
  172. }
  173. // We need to make sure that we didn't accidentially identify the end of another token as our token,
  174. // e.g. in a previous version the "gltf " present in some gltf files was detected as "f "
  175. if (noAlphaBeforeTokens && (r != buffer && isalpha(static_cast<unsigned char>(r[-1])))) {
  176. continue;
  177. }
  178. // We got a match, either we don't care where it is, or it happens to
  179. // be in the beginning of the file / line
  180. if (!tokensSol || r == buffer || r[-1] == '\r' || r[-1] == '\n') {
  181. ASSIMP_LOG_DEBUG("Found positive match for header keyword: ", tokens[i]);
  182. return true;
  183. }
  184. }
  185. }
  186. return false;
  187. }
  188. // ------------------------------------------------------------------------------------------------
  189. // Simple check for file extension
  190. /*static*/ bool BaseImporter::SimpleExtensionCheck(const std::string &pFile,
  191. const char *ext0,
  192. const char *ext1,
  193. const char *ext2) {
  194. std::string::size_type pos = pFile.find_last_of('.');
  195. // no file extension - can't read
  196. if (pos == std::string::npos)
  197. return false;
  198. const char *ext_real = &pFile[pos + 1];
  199. if (!ASSIMP_stricmp(ext_real, ext0))
  200. return true;
  201. // check for other, optional, file extensions
  202. if (ext1 && !ASSIMP_stricmp(ext_real, ext1))
  203. return true;
  204. if (ext2 && !ASSIMP_stricmp(ext_real, ext2))
  205. return true;
  206. return false;
  207. }
  208. // ------------------------------------------------------------------------------------------------
  209. // Get file extension from path
  210. std::string BaseImporter::GetExtension(const std::string &file) {
  211. std::string::size_type pos = file.find_last_of('.');
  212. // no file extension at all
  213. if (pos == std::string::npos) {
  214. return std::string();
  215. }
  216. // thanks to Andy Maloney for the hint
  217. std::string ret = file.substr(pos + 1);
  218. ret = ai_tolower(ret);
  219. return ret;
  220. }
  221. // ------------------------------------------------------------------------------------------------
  222. // Check for magic bytes at the beginning of the file.
  223. /* static */ bool BaseImporter::CheckMagicToken(IOSystem *pIOHandler, const std::string &pFile,
  224. const void *_magic, unsigned int num, unsigned int offset, unsigned int size) {
  225. ai_assert(size <= 16);
  226. ai_assert(_magic);
  227. if (!pIOHandler) {
  228. return false;
  229. }
  230. union {
  231. const char *magic;
  232. const uint16_t *magic_u16;
  233. const uint32_t *magic_u32;
  234. };
  235. magic = reinterpret_cast<const char *>(_magic);
  236. std::unique_ptr<IOStream> pStream(pIOHandler->Open(pFile));
  237. if (pStream) {
  238. // skip to offset
  239. pStream->Seek(offset, aiOrigin_SET);
  240. // read 'size' characters from the file
  241. union {
  242. char data[16];
  243. uint16_t data_u16[8];
  244. uint32_t data_u32[4];
  245. };
  246. if (size != pStream->Read(data, 1, size)) {
  247. return false;
  248. }
  249. for (unsigned int i = 0; i < num; ++i) {
  250. // also check against big endian versions of tokens with size 2,4
  251. // that's just for convenience, the chance that we cause conflicts
  252. // is quite low and it can save some lines and prevent nasty bugs
  253. if (2 == size) {
  254. uint16_t rev = *magic_u16;
  255. ByteSwap::Swap(&rev);
  256. if (data_u16[0] == *magic_u16 || data_u16[0] == rev) {
  257. return true;
  258. }
  259. } else if (4 == size) {
  260. uint32_t rev = *magic_u32;
  261. ByteSwap::Swap(&rev);
  262. if (data_u32[0] == *magic_u32 || data_u32[0] == rev) {
  263. return true;
  264. }
  265. } else {
  266. // any length ... just compare
  267. if (!memcmp(magic, data, size)) {
  268. return true;
  269. }
  270. }
  271. magic += size;
  272. }
  273. }
  274. return false;
  275. }
  276. #ifdef ASSIMP_USE_HUNTER
  277. #include <utf8.h>
  278. #else
  279. #include "../contrib/utf8cpp/source/utf8.h"
  280. #endif
  281. // ------------------------------------------------------------------------------------------------
  282. // Convert to UTF8 data
  283. void BaseImporter::ConvertToUTF8(std::vector<char> &data) {
  284. //ConversionResult result;
  285. if (data.size() < 8) {
  286. throw DeadlyImportError("File is too small");
  287. }
  288. // UTF 8 with BOM
  289. if ((uint8_t)data[0] == 0xEF && (uint8_t)data[1] == 0xBB && (uint8_t)data[2] == 0xBF) {
  290. ASSIMP_LOG_DEBUG("Found UTF-8 BOM ...");
  291. std::copy(data.begin() + 3, data.end(), data.begin());
  292. data.resize(data.size() - 3);
  293. return;
  294. }
  295. // UTF 32 BE with BOM
  296. if (*((uint32_t *)&data.front()) == 0xFFFE0000) {
  297. // swap the endianness ..
  298. for (uint32_t *p = (uint32_t *)&data.front(), *end = (uint32_t *)&data.back(); p <= end; ++p) {
  299. AI_SWAP4P(p);
  300. }
  301. }
  302. // UTF 32 LE with BOM
  303. if (*((uint32_t *)&data.front()) == 0x0000FFFE) {
  304. ASSIMP_LOG_DEBUG("Found UTF-32 BOM ...");
  305. std::vector<char> output;
  306. int *ptr = (int *)&data[0];
  307. int *end = ptr + (data.size() / sizeof(int)) + 1;
  308. utf8::utf32to8(ptr, end, back_inserter(output));
  309. return;
  310. }
  311. // UTF 16 BE with BOM
  312. if (*((uint16_t *)&data.front()) == 0xFFFE) {
  313. // swap the endianness ..
  314. for (uint16_t *p = (uint16_t *)&data.front(), *end = (uint16_t *)&data.back(); p <= end; ++p) {
  315. ByteSwap::Swap2(p);
  316. }
  317. }
  318. // UTF 16 LE with BOM
  319. if (*((uint16_t *)&data.front()) == 0xFEFF) {
  320. ASSIMP_LOG_DEBUG("Found UTF-16 BOM ...");
  321. std::vector<unsigned char> output;
  322. utf8::utf16to8(data.begin(), data.end(), back_inserter(output));
  323. return;
  324. }
  325. }
  326. // ------------------------------------------------------------------------------------------------
  327. // Convert to UTF8 data to ISO-8859-1
  328. void BaseImporter::ConvertUTF8toISO8859_1(std::string &data) {
  329. size_t size = data.size();
  330. size_t i = 0, j = 0;
  331. while (i < size) {
  332. if ((unsigned char)data[i] < (size_t)0x80) {
  333. data[j] = data[i];
  334. } else if (i < size - 1) {
  335. if ((unsigned char)data[i] == 0xC2) {
  336. data[j] = data[++i];
  337. } else if ((unsigned char)data[i] == 0xC3) {
  338. data[j] = ((unsigned char)data[++i] + 0x40);
  339. } else {
  340. std::stringstream stream;
  341. stream << "UTF8 code " << std::hex << data[i] << data[i + 1] << " can not be converted into ISA-8859-1.";
  342. ASSIMP_LOG_ERROR(stream.str());
  343. data[j++] = data[i++];
  344. data[j] = data[i];
  345. }
  346. } else {
  347. ASSIMP_LOG_ERROR("UTF8 code but only one character remaining");
  348. data[j] = data[i];
  349. }
  350. i++;
  351. j++;
  352. }
  353. data.resize(j);
  354. }
  355. // ------------------------------------------------------------------------------------------------
  356. void BaseImporter::TextFileToBuffer(IOStream *stream,
  357. std::vector<char> &data,
  358. TextFileMode mode) {
  359. ai_assert(nullptr != stream);
  360. const size_t fileSize = stream->FileSize();
  361. if (mode == FORBID_EMPTY) {
  362. if (!fileSize) {
  363. throw DeadlyImportError("File is empty");
  364. }
  365. }
  366. data.reserve(fileSize + 1);
  367. data.resize(fileSize);
  368. if (fileSize > 0) {
  369. if (fileSize != stream->Read(&data[0], 1, fileSize)) {
  370. throw DeadlyImportError("File read error");
  371. }
  372. ConvertToUTF8(data);
  373. }
  374. // append a binary zero to simplify string parsing
  375. data.push_back(0);
  376. }
  377. // ------------------------------------------------------------------------------------------------
  378. namespace Assimp {
  379. // Represents an import request
  380. struct LoadRequest {
  381. LoadRequest(const std::string &_file, unsigned int _flags, const BatchLoader::PropertyMap *_map, unsigned int _id) :
  382. file(_file),
  383. flags(_flags),
  384. refCnt(1),
  385. scene(nullptr),
  386. loaded(false),
  387. id(_id) {
  388. if (_map) {
  389. map = *_map;
  390. }
  391. }
  392. bool operator==(const std::string &f) const {
  393. return file == f;
  394. }
  395. const std::string file;
  396. unsigned int flags;
  397. unsigned int refCnt;
  398. aiScene *scene;
  399. bool loaded;
  400. BatchLoader::PropertyMap map;
  401. unsigned int id;
  402. };
  403. } // namespace Assimp
  404. // ------------------------------------------------------------------------------------------------
  405. // BatchLoader::pimpl data structure
  406. struct Assimp::BatchData {
  407. BatchData(IOSystem *pIO, bool validate) :
  408. pIOSystem(pIO), pImporter(nullptr), next_id(0xffff), validate(validate) {
  409. ai_assert(nullptr != pIO);
  410. pImporter = new Importer();
  411. pImporter->SetIOHandler(pIO);
  412. }
  413. ~BatchData() {
  414. pImporter->SetIOHandler(nullptr); /* get pointer back into our possession */
  415. delete pImporter;
  416. }
  417. // IO system to be used for all imports
  418. IOSystem *pIOSystem;
  419. // Importer used to load all meshes
  420. Importer *pImporter;
  421. // List of all imports
  422. std::list<LoadRequest> requests;
  423. // Base path
  424. std::string pathBase;
  425. // Id for next item
  426. unsigned int next_id;
  427. // Validation enabled state
  428. bool validate;
  429. };
  430. typedef std::list<LoadRequest>::iterator LoadReqIt;
  431. // ------------------------------------------------------------------------------------------------
  432. BatchLoader::BatchLoader(IOSystem *pIO, bool validate) {
  433. ai_assert(nullptr != pIO);
  434. m_data = new BatchData(pIO, validate);
  435. }
  436. // ------------------------------------------------------------------------------------------------
  437. BatchLoader::~BatchLoader() {
  438. // delete all scenes what have not been polled by the user
  439. for (LoadReqIt it = m_data->requests.begin(); it != m_data->requests.end(); ++it) {
  440. delete (*it).scene;
  441. }
  442. delete m_data;
  443. }
  444. // ------------------------------------------------------------------------------------------------
  445. void BatchLoader::setValidation(bool enabled) {
  446. m_data->validate = enabled;
  447. }
  448. // ------------------------------------------------------------------------------------------------
  449. bool BatchLoader::getValidation() const {
  450. return m_data->validate;
  451. }
  452. // ------------------------------------------------------------------------------------------------
  453. unsigned int BatchLoader::AddLoadRequest(const std::string &file,
  454. unsigned int steps /*= 0*/, const PropertyMap *map /*= nullptr*/) {
  455. ai_assert(!file.empty());
  456. // check whether we have this loading request already
  457. for (LoadReqIt it = m_data->requests.begin(); it != m_data->requests.end(); ++it) {
  458. // Call IOSystem's path comparison function here
  459. if (m_data->pIOSystem->ComparePaths((*it).file, file)) {
  460. if (map) {
  461. if (!((*it).map == *map)) {
  462. continue;
  463. }
  464. } else if (!(*it).map.empty()) {
  465. continue;
  466. }
  467. (*it).refCnt++;
  468. return (*it).id;
  469. }
  470. }
  471. // no, we don't have it. So add it to the queue ...
  472. m_data->requests.emplace_back(file, steps, map, m_data->next_id);
  473. return m_data->next_id++;
  474. }
  475. // ------------------------------------------------------------------------------------------------
  476. aiScene *BatchLoader::GetImport(unsigned int which) {
  477. for (LoadReqIt it = m_data->requests.begin(); it != m_data->requests.end(); ++it) {
  478. if ((*it).id == which && (*it).loaded) {
  479. aiScene *sc = (*it).scene;
  480. if (!(--(*it).refCnt)) {
  481. m_data->requests.erase(it);
  482. }
  483. return sc;
  484. }
  485. }
  486. return nullptr;
  487. }
  488. // ------------------------------------------------------------------------------------------------
  489. void BatchLoader::LoadAll() {
  490. // no threaded implementation for the moment
  491. for (LoadReqIt it = m_data->requests.begin(); it != m_data->requests.end(); ++it) {
  492. // force validation in debug builds
  493. unsigned int pp = (*it).flags;
  494. if (m_data->validate) {
  495. pp |= aiProcess_ValidateDataStructure;
  496. }
  497. // setup config properties if necessary
  498. ImporterPimpl *pimpl = m_data->pImporter->Pimpl();
  499. pimpl->mFloatProperties = (*it).map.floats;
  500. pimpl->mIntProperties = (*it).map.ints;
  501. pimpl->mStringProperties = (*it).map.strings;
  502. pimpl->mMatrixProperties = (*it).map.matrices;
  503. if (!DefaultLogger::isNullLogger()) {
  504. ASSIMP_LOG_INFO("%%% BEGIN EXTERNAL FILE %%%");
  505. ASSIMP_LOG_INFO("File: ", (*it).file);
  506. }
  507. m_data->pImporter->ReadFile((*it).file, pp);
  508. (*it).scene = m_data->pImporter->GetOrphanedScene();
  509. (*it).loaded = true;
  510. ASSIMP_LOG_INFO("%%% END EXTERNAL FILE %%%");
  511. }
  512. }