2
0

BaseImporter.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. /*
  2. Open Asset Import Library (ASSIMP)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2008, ASSIMP Development 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 Development 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 <string>
  37. #include "./../include/aiTypes.h"
  38. struct aiScene;
  39. namespace Assimp {
  40. class IOSystem;
  41. class Importer;
  42. // utility to do char4 to uint32 in a portable manner
  43. #define AI_MAKE_MAGIC(string) ((uint32_t)((string[0] << 24) + \
  44. (string[1] << 16) + (string[2] << 8) + string[3]))
  45. // ---------------------------------------------------------------------------
  46. /** FOR IMPORTER PLUGINS ONLY: Simple exception class to be thrown if an
  47. * error occurs while importing. */
  48. class ASSIMP_API ImportErrorException
  49. {
  50. public:
  51. /** Constructor with arguments */
  52. ImportErrorException( const std::string& pErrorText)
  53. {
  54. mErrorText = pErrorText;
  55. }
  56. // -------------------------------------------------------------------
  57. /** Returns the error text provided when throwing the exception */
  58. inline const std::string& GetErrorText() const
  59. { return mErrorText; }
  60. private:
  61. std::string mErrorText;
  62. };
  63. //! @cond never
  64. // ---------------------------------------------------------------------------
  65. /** @brief Internal PIMPL implementation for Assimp::Importer
  66. *
  67. * Using this idiom here allows us to drop the dependency from
  68. * std::vector and std::map in the public headers. Furthermore we are dropping
  69. * any STL interface problems caused by mismatching STL settings. All
  70. * size calculation are now done by us, not the app heap. */
  71. class ASSIMP_API ImporterPimpl
  72. {
  73. public:
  74. // Data type to store the key hash
  75. typedef unsigned int KeyType;
  76. // typedefs for our three configuration maps.
  77. // We don't need more, so there is no need for a generic solution
  78. typedef std::map<KeyType, int> IntPropertyMap;
  79. typedef std::map<KeyType, float> FloatPropertyMap;
  80. typedef std::map<KeyType, std::string> StringPropertyMap;
  81. public:
  82. /** IO handler to use for all file accesses. */
  83. IOSystem* mIOHandler;
  84. bool mIsDefaultHandler;
  85. /** Format-specific importer worker objects - one for each format we can read.*/
  86. std::vector<BaseImporter*> mImporter;
  87. /** Post processing steps we can apply at the imported data. */
  88. std::vector<BaseProcess*> mPostProcessingSteps;
  89. /** The imported data, if ReadFile() was successful, NULL otherwise. */
  90. aiScene* mScene;
  91. /** The error description, if there was one. */
  92. std::string mErrorString;
  93. /** List of integer properties */
  94. IntPropertyMap mIntProperties;
  95. /** List of floating-point properties */
  96. FloatPropertyMap mFloatProperties;
  97. /** List of string properties */
  98. StringPropertyMap mStringProperties;
  99. /** Used for testing - extra verbose mode causes the ValidateDataStructure-Step
  100. * to be executed before and after every single postprocess step */
  101. bool bExtraVerbose;
  102. /** Used by post-process steps to share data */
  103. SharedPostProcessInfo* mPPShared;
  104. };
  105. //! @endcond
  106. // ---------------------------------------------------------------------------
  107. /** FOR IMPORTER PLUGINS ONLY: The BaseImporter defines a common interface
  108. * for all importer worker classes.
  109. *
  110. * The interface defines two functions: CanRead() is used to check if the
  111. * importer can handle the format of the given file. If an implementation of
  112. * this function returns true, the importer then calls ReadFile() which
  113. * imports the given file. ReadFile is not overridable, it just calls
  114. * InternReadFile() and catches any ImportErrorException that might occur.
  115. */
  116. class ASSIMP_API BaseImporter
  117. {
  118. friend class Importer;
  119. protected:
  120. /** Constructor to be privately used by #Importer */
  121. BaseImporter();
  122. /** Destructor, private as well */
  123. virtual ~BaseImporter();
  124. public:
  125. // -------------------------------------------------------------------
  126. /** Returns whether the class can handle the format of the given file.
  127. *
  128. * The implementation should be as quick as possible. A check for
  129. * the file extension is enough. If no suitable loader is found with
  130. * this strategy, CanRead() is called again, the 'checkSig' parameter
  131. * set to true this time. Now the implementation is expected to
  132. * perform a full check of the file format, possibly searching the
  133. * first bytes of the file for magic identifiers or keywords.
  134. *
  135. * @param pFile Path and file name of the file to be examined.
  136. * @param pIOHandler The IO handler to use for accessing any file.
  137. * @param checkSig Set to true if this method is called a second time.
  138. * This time, the implementation may take more time to examine the
  139. * contents of the file to be loaded for magic bytes, keywords, etc
  140. * to be able to load files with unknown/not existent file extensions.
  141. * @return true if the class can read this file, false if not.
  142. *
  143. * @note Sometimes ASSIMP uses this method to determine whether a
  144. * a given file extension is generally supported. In this case the
  145. * file extension is passed in the pFile parameter, pIOHandler is NULL
  146. */
  147. virtual bool CanRead( const std::string& pFile,
  148. IOSystem* pIOHandler, bool checkSig) const = 0;
  149. // -------------------------------------------------------------------
  150. /** Imports the given file and returns the imported data.
  151. * If the import succeeds, ownership of the data is transferred to
  152. * the caller. If the import fails, NULL is returned. The function
  153. * takes care that any partially constructed data is destroyed
  154. * beforehand.
  155. *
  156. * @param pFile Path of the file to be imported.
  157. * @param pIOHandler IO-Handler used to open this and possible other files.
  158. * @return The imported data or NULL if failed. If it failed a
  159. * human-readable error description can be retrieved by calling
  160. * GetErrorText()
  161. *
  162. * @note This function is not intended to be overridden. Implement
  163. * InternReadFile() to do the import. If an exception is thrown somewhere
  164. * in InternReadFile(), this function will catch it and transform it into
  165. * a suitable response to the caller.
  166. */
  167. aiScene* ReadFile( const std::string& pFile, IOSystem* pIOHandler);
  168. // -------------------------------------------------------------------
  169. /** Returns the error description of the last error that occured.
  170. * @return A description of the last error that occured. An empty
  171. * string if there was no error.
  172. */
  173. const std::string& GetErrorText() const {
  174. return mErrorText;
  175. }
  176. // -------------------------------------------------------------------
  177. /** Called prior to ReadFile().
  178. * The function is a request to the importer to update its configuration
  179. * basing on the Importer's configuration property list.
  180. * @param pImp Importer instance
  181. */
  182. virtual void SetupProperties(const Importer* pImp);
  183. protected:
  184. // -------------------------------------------------------------------
  185. /** Called by Importer::GetExtensionList() for each loaded importer.
  186. * Importer implementations should append all file extensions
  187. * which they supported to the passed string.
  188. * Example: "*.blabb;*.quak;*.gug;*.foo" (no delimiter after the last!)
  189. * @param append Output string
  190. */
  191. virtual void GetExtensionList(std::string& append) = 0;
  192. // -------------------------------------------------------------------
  193. /** Imports the given file into the given scene structure. The
  194. * function is expected to throw an ImportErrorException if there is
  195. * an error. If it terminates normally, the data in aiScene is
  196. * expected to be correct. Override this function to implement the
  197. * actual importing.
  198. * <br>
  199. * The output scene must meet the following requirements:<br>
  200. * <ul>
  201. * <li>At least a root node must be there, even if its only purpose
  202. * is to reference one mesh.</li>
  203. * <li>aiMesh::mPrimitiveTypes may be 0. The types of primitives
  204. * in the mesh are determined automatically in this case.</li>
  205. * <li>the vertex data is stored in a pseudo-indexed "verbose" format.
  206. * In fact this means that every vertex that is referenced by
  207. * a face is unique. Or the other way round: a vertex index may
  208. * not occur twice in a single aiMesh.</li>
  209. * <li>aiAnimation::mDuration may be -1. Assimp determines the length
  210. * of the animation automatically in this case as the length of
  211. * the longest animation channel.</li>
  212. * <li>aiMesh::mBitangents may be NULL if tangents and normals are
  213. * given. In this case bitangents are computed as the cross product
  214. * between normal and tangent.</li>
  215. * <li>There needn't be a material. If none is there a default material
  216. * is generated. However, it is recommended practice for loaders
  217. * to generate a default material for yourself that matches the
  218. * default material setting for the file format better than Assimp's
  219. * generic default material. Note that default materials *should*
  220. * be named AI_DEFAULT_MATERIAL_NAME if they're just color-shaded
  221. * or AI_DEFAULT_TEXTURED_MATERIAL_NAME if they define a (dummy)
  222. * texture. </li>
  223. * </ul>
  224. * If the AI_SCENE_FLAGS_INCOMPLETE-Flag is <b>not</b> set:<ul>
  225. * <li> at least one mesh must be there</li>
  226. * <li> there may be no meshes with 0 vertices or faces</li>
  227. * </ul>
  228. * This won't be checked (except by the validation step): Assimp will
  229. * crash if one of the conditions is not met!
  230. *
  231. * @param pFile Path of the file to be imported.
  232. * @param pScene The scene object to hold the imported data.
  233. * NULL is not a valid parameter.
  234. * @param pIOHandler The IO handler to use for any file access.
  235. * NULL is not a valid parameter.
  236. */
  237. virtual void InternReadFile( const std::string& pFile,
  238. aiScene* pScene, IOSystem* pIOHandler) = 0;
  239. public: // static utilities
  240. // -------------------------------------------------------------------
  241. /** A utility for CanRead().
  242. *
  243. * The function searches the header of a file for a specific token
  244. * and returns true if this token is found. This works for text
  245. * files only. There is a rudimentary handling of UNICODE files.
  246. * The comparison is case independent.
  247. *
  248. * @param pIOSystem IO System to work with
  249. * @param file File name of the file
  250. * @param tokens List of tokens to search for
  251. * @param numTokens Size of the token array
  252. * @param searchBytes Number of bytes to be searched for the tokens.
  253. */
  254. static bool SearchFileHeaderForToken(IOSystem* pIOSystem,
  255. const std::string& file,
  256. const char** tokens,
  257. unsigned int numTokens,
  258. unsigned int searchBytes = 200);
  259. // -------------------------------------------------------------------
  260. /** @brief Check whether a file has a specific file extension
  261. * @param pFile Input file
  262. * @param ext0 Extension to check for. Lowercase characters only, no dot!
  263. * @param ext1 Optional second extension
  264. * @param ext2 Optional third extension
  265. * @note Case-insensitive
  266. */
  267. static bool SimpleExtensionCheck (const std::string& pFile,
  268. const char* ext0,
  269. const char* ext1 = NULL,
  270. const char* ext2 = NULL);
  271. // -------------------------------------------------------------------
  272. /** @brief Extract file extension from a string
  273. * @param pFile Input file
  274. * @return Extension without trailing dot, all lowercase
  275. */
  276. static std::string GetExtension (const std::string& pFile);
  277. // -------------------------------------------------------------------
  278. /** @brief Check whether a file starts with one or more magic tokens
  279. * @param pFile Input file
  280. * @param pIOHandler IO system to be used
  281. * @param magic n magic tokens
  282. * @params num Size of magic
  283. * @param offset Offset from file start where tokens are located
  284. * @param Size of one token, in bytes. Maximally 16 bytes.
  285. * @return true if one of the given tokens was found
  286. *
  287. * @note For convinence, the check is also performed for the
  288. * byte-swapped variant of all tokens (big endian). Only for
  289. * tokens of size 2,4.
  290. */
  291. static bool CheckMagicToken(IOSystem* pIOHandler, const std::string& pFile,
  292. const void* magic,
  293. unsigned int num,
  294. unsigned int offset = 0,
  295. unsigned int size = 4);
  296. // -------------------------------------------------------------------
  297. /** An utility for all text file loaders. It converts a file to our
  298. * UTF8 character set. Errors are reported, but ignored.
  299. *
  300. * @param data File buffer to be converted to UTF8 data. The buffer
  301. * is resized as appropriate. */
  302. static void ConvertToUTF8(std::vector<char>& data);
  303. // -------------------------------------------------------------------
  304. /** Utility for text file loaders which copies the contents of the
  305. * file into a memory buffer and converts it to our UTF8
  306. * representation.
  307. * @param stream Stream to read from.
  308. * @param data Output buffer to be resized and filled with the
  309. * converted text file data. The buffer is terminated with
  310. * a binary 0. */
  311. static void TextFileToBuffer(IOStream* stream,
  312. std::vector<char>& data);
  313. protected:
  314. /** Error description in case there was one. */
  315. std::string mErrorText;
  316. };
  317. struct BatchData;
  318. // ---------------------------------------------------------------------------
  319. /** FOR IMPORTER PLUGINS ONLY: A helper class for the pleasure of importers
  320. * which need to load many extern meshes recursively.
  321. *
  322. * The class uses several threads to load these meshes (or at least it
  323. * could, this has not yet been implemented at the moment).
  324. *
  325. * @note The class may not be used by more than one thread*/
  326. class ASSIMP_API BatchLoader
  327. {
  328. // friend of Importer
  329. public:
  330. //! @cond never
  331. // -------------------------------------------------------------------
  332. /** Wraps a full list of configuration properties for an importer.
  333. * Properties can be set using SetGenericProperty */
  334. struct PropertyMap
  335. {
  336. ImporterPimpl::IntPropertyMap ints;
  337. ImporterPimpl::FloatPropertyMap floats;
  338. ImporterPimpl::StringPropertyMap strings;
  339. bool operator == (const PropertyMap& prop) const {
  340. // fixme: really isocpp? gcc complains
  341. return ints == prop.ints && floats == prop.floats && strings == prop.strings;
  342. }
  343. bool empty () const {
  344. return ints.empty() && floats.empty() && strings.empty();
  345. }
  346. };
  347. //! @endcond
  348. public:
  349. // -------------------------------------------------------------------
  350. /** Construct a batch loader from a given IO system to be used to acess external files */
  351. BatchLoader(IOSystem* pIO);
  352. ~BatchLoader();
  353. // -------------------------------------------------------------------
  354. /** Add a new file to the list of files to be loaded.
  355. * @param file File to be loaded
  356. * @param steps Post-processing steps to be executed on the file
  357. * @param map Optional configuration properties
  358. * @return 'Load request channel' - an unique ID that can later
  359. * be used to access the imported file data.
  360. * @see GetImport */
  361. unsigned int AddLoadRequest (const std::string& file,
  362. unsigned int steps = 0, const PropertyMap* map = NULL);
  363. // -------------------------------------------------------------------
  364. /** Get an imported scene.
  365. * This polls the import from the internal request list.
  366. * If an import is requested several times, this function
  367. * can be called several times, too.
  368. *
  369. * @param which LRWC returned by AddLoadRequest().
  370. * @return NULL if there is no scene with this file name
  371. * in the queue of the scene hasn't been loaded yet. */
  372. aiScene* GetImport (unsigned int which);
  373. // -------------------------------------------------------------------
  374. /** Waits until all scenes have been loaded. */
  375. void LoadAll();
  376. private:
  377. // No need to have that in the public API ...
  378. BatchData* data;
  379. };
  380. } // end of namespace Assimp
  381. #endif // AI_BASEIMPORTER_H_INC