BaseImporter.h 14 KB

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