BaseImporter.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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 Definition of the base class for all importer worker classes. */
  34. #ifndef INCLUDED_AI_BASEIMPORTER_H
  35. #define INCLUDED_AI_BASEIMPORTER_H
  36. #include "Exceptional.h"
  37. #include <string>
  38. #include <map>
  39. #include <vector>
  40. #include <set>
  41. #include <assimp/types.h>
  42. #include <assimp/ProgressHandler.hpp>
  43. struct aiScene;
  44. namespace Assimp {
  45. class Importer;
  46. class IOSystem;
  47. class BaseProcess;
  48. class SharedPostProcessInfo;
  49. class IOStream;
  50. // utility to do char4 to uint32 in a portable manner
  51. #define AI_MAKE_MAGIC(string) ((uint32_t)((string[0] << 24) + \
  52. (string[1] << 16) + (string[2] << 8) + string[3]))
  53. // ---------------------------------------------------------------------------
  54. template <typename T>
  55. struct ScopeGuard
  56. {
  57. explicit ScopeGuard(T* obj) : obj(obj), mdismiss() {}
  58. ~ScopeGuard () throw() {
  59. if (!mdismiss) {
  60. delete obj;
  61. }
  62. obj = NULL;
  63. }
  64. T* dismiss() {
  65. mdismiss=true;
  66. return obj;
  67. }
  68. operator T*() {
  69. return obj;
  70. }
  71. T* operator -> () {
  72. return obj;
  73. }
  74. private:
  75. // no copying allowed.
  76. ScopeGuard();
  77. ScopeGuard( const ScopeGuard & );
  78. ScopeGuard &operator = ( const ScopeGuard & );
  79. T* obj;
  80. bool mdismiss;
  81. };
  82. // ---------------------------------------------------------------------------
  83. /** FOR IMPORTER PLUGINS ONLY: The BaseImporter defines a common interface
  84. * for all importer worker classes.
  85. *
  86. * The interface defines two functions: CanRead() is used to check if the
  87. * importer can handle the format of the given file. If an implementation of
  88. * this function returns true, the importer then calls ReadFile() which
  89. * imports the given file. ReadFile is not overridable, it just calls
  90. * InternReadFile() and catches any ImportErrorException that might occur.
  91. */
  92. class ASSIMP_API BaseImporter
  93. {
  94. friend class Importer;
  95. public:
  96. /** Constructor to be privately used by #Importer */
  97. BaseImporter();
  98. /** Destructor, private as well */
  99. virtual ~BaseImporter();
  100. public:
  101. // -------------------------------------------------------------------
  102. /** Returns whether the class can handle the format of the given file.
  103. *
  104. * The implementation should be as quick as possible. A check for
  105. * the file extension is enough. If no suitable loader is found with
  106. * this strategy, CanRead() is called again, the 'checkSig' parameter
  107. * set to true this time. Now the implementation is expected to
  108. * perform a full check of the file structure, possibly searching the
  109. * first bytes of the file for magic identifiers or keywords.
  110. *
  111. * @param pFile Path and file name of the file to be examined.
  112. * @param pIOHandler The IO handler to use for accessing any file.
  113. * @param checkSig Set to true if this method is called a second time.
  114. * This time, the implementation may take more time to examine the
  115. * contents of the file to be loaded for magic bytes, keywords, etc
  116. * to be able to load files with unknown/not existent file extensions.
  117. * @return true if the class can read this file, false if not.
  118. */
  119. virtual bool CanRead(
  120. const std::string& pFile,
  121. IOSystem* pIOHandler,
  122. bool checkSig
  123. ) const = 0;
  124. // -------------------------------------------------------------------
  125. /** Imports the given file and returns the imported data.
  126. * If the import succeeds, ownership of the data is transferred to
  127. * the caller. If the import fails, NULL is returned. The function
  128. * takes care that any partially constructed data is destroyed
  129. * beforehand.
  130. *
  131. * @param pImp #Importer object hosting this loader.
  132. * @param pFile Path of the file to be imported.
  133. * @param pIOHandler IO-Handler used to open this and possible other files.
  134. * @return The imported data or NULL if failed. If it failed a
  135. * human-readable error description can be retrieved by calling
  136. * GetErrorText()
  137. *
  138. * @note This function is not intended to be overridden. Implement
  139. * InternReadFile() to do the import. If an exception is thrown somewhere
  140. * in InternReadFile(), this function will catch it and transform it into
  141. * a suitable response to the caller.
  142. */
  143. aiScene* ReadFile(
  144. const Importer* pImp,
  145. const std::string& pFile,
  146. IOSystem* pIOHandler
  147. );
  148. // -------------------------------------------------------------------
  149. /** Returns the error description of the last error that occurred.
  150. * @return A description of the last error that occurred. An empty
  151. * string if there was no error.
  152. */
  153. const std::string& GetErrorText() const {
  154. return m_ErrorText;
  155. }
  156. // -------------------------------------------------------------------
  157. /** Called prior to ReadFile().
  158. * The function is a request to the importer to update its configuration
  159. * basing on the Importer's configuration property list.
  160. * @param pImp Importer instance
  161. */
  162. virtual void SetupProperties(
  163. const Importer* pImp
  164. );
  165. // -------------------------------------------------------------------
  166. /** Called by #Importer::GetImporterInfo to get a description of
  167. * some loader features. Importers must provide this information. */
  168. virtual const aiImporterDesc* GetInfo() const = 0;
  169. // -------------------------------------------------------------------
  170. /** Called by #Importer::GetExtensionList for each loaded importer.
  171. * Take the extension list contained in the structure returned by
  172. * #GetInfo and insert all file extensions into the given set.
  173. * @param extension set to collect file extensions in*/
  174. void GetExtensionList(std::set<std::string>& extensions);
  175. protected:
  176. // -------------------------------------------------------------------
  177. /** Imports the given file into the given scene structure. The
  178. * function is expected to throw an ImportErrorException if there is
  179. * an error. If it terminates normally, the data in aiScene is
  180. * expected to be correct. Override this function to implement the
  181. * actual importing.
  182. * <br>
  183. * The output scene must meet the following requirements:<br>
  184. * <ul>
  185. * <li>At least a root node must be there, even if its only purpose
  186. * is to reference one mesh.</li>
  187. * <li>aiMesh::mPrimitiveTypes may be 0. The types of primitives
  188. * in the mesh are determined automatically in this case.</li>
  189. * <li>the vertex data is stored in a pseudo-indexed "verbose" format.
  190. * In fact this means that every vertex that is referenced by
  191. * a face is unique. Or the other way round: a vertex index may
  192. * not occur twice in a single aiMesh.</li>
  193. * <li>aiAnimation::mDuration may be -1. Assimp determines the length
  194. * of the animation automatically in this case as the length of
  195. * the longest animation channel.</li>
  196. * <li>aiMesh::mBitangents may be NULL if tangents and normals are
  197. * given. In this case bitangents are computed as the cross product
  198. * between normal and tangent.</li>
  199. * <li>There needn't be a material. If none is there a default material
  200. * is generated. However, it is recommended practice for loaders
  201. * to generate a default material for yourself that matches the
  202. * default material setting for the file format better than Assimp's
  203. * generic default material. Note that default materials *should*
  204. * be named AI_DEFAULT_MATERIAL_NAME if they're just color-shaded
  205. * or AI_DEFAULT_TEXTURED_MATERIAL_NAME if they define a (dummy)
  206. * texture. </li>
  207. * </ul>
  208. * If the AI_SCENE_FLAGS_INCOMPLETE-Flag is <b>not</b> set:<ul>
  209. * <li> at least one mesh must be there</li>
  210. * <li> there may be no meshes with 0 vertices or faces</li>
  211. * </ul>
  212. * This won't be checked (except by the validation step): Assimp will
  213. * crash if one of the conditions is not met!
  214. *
  215. * @param pFile Path of the file to be imported.
  216. * @param pScene The scene object to hold the imported data.
  217. * NULL is not a valid parameter.
  218. * @param pIOHandler The IO handler to use for any file access.
  219. * NULL is not a valid parameter. */
  220. virtual void InternReadFile(
  221. const std::string& pFile,
  222. aiScene* pScene,
  223. IOSystem* pIOHandler
  224. ) = 0;
  225. public: // static utilities
  226. // -------------------------------------------------------------------
  227. /** A utility for CanRead().
  228. *
  229. * The function searches the header of a file for a specific token
  230. * and returns true if this token is found. This works for text
  231. * files only. There is a rudimentary handling of UNICODE files.
  232. * The comparison is case independent.
  233. *
  234. * @param pIOSystem IO System to work with
  235. * @param file File name of the file
  236. * @param tokens List of tokens to search for
  237. * @param numTokens Size of the token array
  238. * @param searchBytes Number of bytes to be searched for the tokens.
  239. */
  240. static bool SearchFileHeaderForToken(
  241. IOSystem* pIOSystem,
  242. const std::string& file,
  243. const char** tokens,
  244. unsigned int numTokens,
  245. unsigned int searchBytes = 200,
  246. bool tokensSol = false);
  247. // -------------------------------------------------------------------
  248. /** @brief Check whether a file has a specific file extension
  249. * @param pFile Input file
  250. * @param ext0 Extension to check for. Lowercase characters only, no dot!
  251. * @param ext1 Optional second extension
  252. * @param ext2 Optional third extension
  253. * @note Case-insensitive
  254. */
  255. static bool SimpleExtensionCheck (
  256. const std::string& pFile,
  257. const char* ext0,
  258. const char* ext1 = NULL,
  259. const char* ext2 = NULL);
  260. // -------------------------------------------------------------------
  261. /** @brief Extract file extension from a string
  262. * @param pFile Input file
  263. * @return Extension without trailing dot, all lowercase
  264. */
  265. static std::string GetExtension (
  266. const std::string& pFile);
  267. // -------------------------------------------------------------------
  268. /** @brief Check whether a file starts with one or more magic tokens
  269. * @param pFile Input file
  270. * @param pIOHandler IO system to be used
  271. * @param magic n magic tokens
  272. * @params num Size of magic
  273. * @param offset Offset from file start where tokens are located
  274. * @param Size of one token, in bytes. Maximally 16 bytes.
  275. * @return true if one of the given tokens was found
  276. *
  277. * @note For convinence, the check is also performed for the
  278. * byte-swapped variant of all tokens (big endian). Only for
  279. * tokens of size 2,4.
  280. */
  281. static bool CheckMagicToken(
  282. IOSystem* pIOHandler,
  283. const std::string& pFile,
  284. const void* magic,
  285. unsigned int num,
  286. unsigned int offset = 0,
  287. unsigned int size = 4);
  288. // -------------------------------------------------------------------
  289. /** An utility for all text file loaders. It converts a file to our
  290. * UTF8 character set. Errors are reported, but ignored.
  291. *
  292. * @param data File buffer to be converted to UTF8 data. The buffer
  293. * is resized as appropriate. */
  294. static void ConvertToUTF8(
  295. std::vector<char>& data);
  296. // -------------------------------------------------------------------
  297. /** An utility for all text file loaders. It converts a file from our
  298. * UTF8 character set back to ISO-8859-1. Errors are reported, but ignored.
  299. *
  300. * @param data File buffer to be converted from UTF8 to ISO-8859-1. The buffer
  301. * is resized as appropriate. */
  302. static void ConvertUTF8toISO8859_1(
  303. std::string& data);
  304. // -------------------------------------------------------------------
  305. /// @brief Enum to define, if empty files are ok or not.
  306. enum TextFileMode {
  307. ALLOW_EMPTY,
  308. FORBID_EMPTY
  309. };
  310. // -------------------------------------------------------------------
  311. /** Utility for text file loaders which copies the contents of the
  312. * file into a memory buffer and converts it to our UTF8
  313. * representation.
  314. * @param stream Stream to read from.
  315. * @param data Output buffer to be resized and filled with the
  316. * converted text file data. The buffer is terminated with
  317. * a binary 0.
  318. * @param mode Whether it is OK to load empty text files. */
  319. static void TextFileToBuffer(
  320. IOStream* stream,
  321. std::vector<char>& data,
  322. TextFileMode mode = FORBID_EMPTY);
  323. // -------------------------------------------------------------------
  324. /** Utility function to move a std::vector into a aiScene array
  325. * @param vec The vector to be moved
  326. * @param out The output pointer to the allocated array.
  327. * @param numOut The output count of elements copied. */
  328. template<typename T>
  329. AI_FORCE_INLINE
  330. static void CopyVector(
  331. std::vector<T>& vec,
  332. T*& out,
  333. unsigned int& outLength)
  334. {
  335. outLength = unsigned(vec.size());
  336. if (outLength) {
  337. out = new T[outLength];
  338. std::swap_ranges(vec.begin(), vec.end(), out);
  339. }
  340. }
  341. protected:
  342. /// Error description in case there was one.
  343. std::string m_ErrorText;
  344. /// Currently set progress handler.
  345. ProgressHandler* m_progress;
  346. };
  347. } // end of namespace Assimp
  348. #endif // AI_BASEIMPORTER_H_INC