BaseImporter.cpp 19 KB

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