BaseImporter.cpp 19 KB

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