BaseImporter.cpp 16 KB

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