miniassimp

view include/miniassimp/BaseImporter.h @ 0:879c81d94345

initial commit
author John Tsiombikas <nuclear@member.fsf.org>
date Mon, 28 Jan 2019 18:19:26 +0200
parents
children
line source
1 /*
2 Open Asset Import Library (assimp)
3 ----------------------------------------------------------------------
5 Copyright (c) 2006-2018, assimp team
8 All rights reserved.
10 Redistribution and use of this software in source and binary forms,
11 with or without modification, are permitted provided that the
12 following conditions are met:
14 * Redistributions of source code must retain the above
15 copyright notice, this list of conditions and the
16 following disclaimer.
18 * Redistributions in binary form must reproduce the above
19 copyright notice, this list of conditions and the
20 following disclaimer in the documentation and/or other
21 materials provided with the distribution.
23 * Neither the name of the assimp team, nor the names of its
24 contributors may be used to endorse or promote products
25 derived from this software without specific prior
26 written permission of the assimp team.
28 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 ----------------------------------------------------------------------
41 */
43 /** @file Definition of the base class for all importer worker classes. */
44 #ifndef INCLUDED_AI_BASEIMPORTER_H
45 #define INCLUDED_AI_BASEIMPORTER_H
47 #include "Exceptional.h"
49 #include <vector>
50 #include <set>
51 #include <miniassimp/types.h>
52 #include <miniassimp/ProgressHandler.hpp>
54 struct aiScene;
55 struct aiImporterDesc;
57 namespace Assimp {
59 class Importer;
60 class IOSystem;
61 class BaseProcess;
62 class SharedPostProcessInfo;
63 class IOStream;
65 // utility to do char4 to uint32 in a portable manner
66 #define AI_MAKE_MAGIC(string) ((uint32_t)((string[0] << 24) + \
67 (string[1] << 16) + (string[2] << 8) + string[3]))
70 // ---------------------------------------------------------------------------
71 /** FOR IMPORTER PLUGINS ONLY: The BaseImporter defines a common interface
72 * for all importer worker classes.
73 *
74 * The interface defines two functions: CanRead() is used to check if the
75 * importer can handle the format of the given file. If an implementation of
76 * this function returns true, the importer then calls ReadFile() which
77 * imports the given file. ReadFile is not overridable, it just calls
78 * InternReadFile() and catches any ImportErrorException that might occur.
79 */
80 class ASSIMP_API BaseImporter {
81 friend class Importer;
83 public:
85 /** Constructor to be privately used by #Importer */
86 BaseImporter() AI_NO_EXCEPT;
88 /** Destructor, private as well */
89 virtual ~BaseImporter();
91 // -------------------------------------------------------------------
92 /** Returns whether the class can handle the format of the given file.
93 *
94 * The implementation should be as quick as possible. A check for
95 * the file extension is enough. If no suitable loader is found with
96 * this strategy, CanRead() is called again, the 'checkSig' parameter
97 * set to true this time. Now the implementation is expected to
98 * perform a full check of the file structure, possibly searching the
99 * first bytes of the file for magic identifiers or keywords.
100 *
101 * @param pFile Path and file name of the file to be examined.
102 * @param pIOHandler The IO handler to use for accessing any file.
103 * @param checkSig Set to true if this method is called a second time.
104 * This time, the implementation may take more time to examine the
105 * contents of the file to be loaded for magic bytes, keywords, etc
106 * to be able to load files with unknown/not existent file extensions.
107 * @return true if the class can read this file, false if not.
108 */
109 virtual bool CanRead(
110 const std::string& pFile,
111 IOSystem* pIOHandler,
112 bool checkSig
113 ) const = 0;
115 // -------------------------------------------------------------------
116 /** Imports the given file and returns the imported data.
117 * If the import succeeds, ownership of the data is transferred to
118 * the caller. If the import fails, NULL is returned. The function
119 * takes care that any partially constructed data is destroyed
120 * beforehand.
121 *
122 * @param pImp #Importer object hosting this loader.
123 * @param pFile Path of the file to be imported.
124 * @param pIOHandler IO-Handler used to open this and possible other files.
125 * @return The imported data or NULL if failed. If it failed a
126 * human-readable error description can be retrieved by calling
127 * GetErrorText()
128 *
129 * @note This function is not intended to be overridden. Implement
130 * InternReadFile() to do the import. If an exception is thrown somewhere
131 * in InternReadFile(), this function will catch it and transform it into
132 * a suitable response to the caller.
133 */
134 aiScene* ReadFile(
135 const Importer* pImp,
136 const std::string& pFile,
137 IOSystem* pIOHandler
138 );
140 // -------------------------------------------------------------------
141 /** Returns the error description of the last error that occurred.
142 * @return A description of the last error that occurred. An empty
143 * string if there was no error.
144 */
145 const std::string& GetErrorText() const {
146 return m_ErrorText;
147 }
149 // -------------------------------------------------------------------
150 /** Called prior to ReadFile().
151 * The function is a request to the importer to update its configuration
152 * basing on the Importer's configuration property list.
153 * @param pImp Importer instance
154 */
155 virtual void SetupProperties(
156 const Importer* pImp
157 );
159 // -------------------------------------------------------------------
160 /** Called by #Importer::GetImporterInfo to get a description of
161 * some loader features. Importers must provide this information. */
162 virtual const aiImporterDesc* GetInfo() const = 0;
164 // -------------------------------------------------------------------
165 /** Called by #Importer::GetExtensionList for each loaded importer.
166 * Take the extension list contained in the structure returned by
167 * #GetInfo and insert all file extensions into the given set.
168 * @param extension set to collect file extensions in*/
169 void GetExtensionList(std::set<std::string>& extensions);
171 protected:
173 // -------------------------------------------------------------------
174 /** Imports the given file into the given scene structure. The
175 * function is expected to throw an ImportErrorException if there is
176 * an error. If it terminates normally, the data in aiScene is
177 * expected to be correct. Override this function to implement the
178 * actual importing.
179 * <br>
180 * The output scene must meet the following requirements:<br>
181 * <ul>
182 * <li>At least a root node must be there, even if its only purpose
183 * is to reference one mesh.</li>
184 * <li>aiMesh::mPrimitiveTypes may be 0. The types of primitives
185 * in the mesh are determined automatically in this case.</li>
186 * <li>the vertex data is stored in a pseudo-indexed "verbose" format.
187 * In fact this means that every vertex that is referenced by
188 * a face is unique. Or the other way round: a vertex index may
189 * not occur twice in a single aiMesh.</li>
190 * <li>aiAnimation::mDuration may be -1. Assimp determines the length
191 * of the animation automatically in this case as the length of
192 * the longest animation channel.</li>
193 * <li>aiMesh::mBitangents may be NULL if tangents and normals are
194 * given. In this case bitangents are computed as the cross product
195 * between normal and tangent.</li>
196 * <li>There needn't be a material. If none is there a default material
197 * is generated. However, it is recommended practice for loaders
198 * to generate a default material for yourself that matches the
199 * default material setting for the file format better than Assimp's
200 * generic default material. Note that default materials *should*
201 * be named AI_DEFAULT_MATERIAL_NAME if they're just color-shaded
202 * or AI_DEFAULT_TEXTURED_MATERIAL_NAME if they define a (dummy)
203 * texture. </li>
204 * </ul>
205 * If the AI_SCENE_FLAGS_INCOMPLETE-Flag is <b>not</b> set:<ul>
206 * <li> at least one mesh must be there</li>
207 * <li> there may be no meshes with 0 vertices or faces</li>
208 * </ul>
209 * This won't be checked (except by the validation step): Assimp will
210 * crash if one of the conditions is not met!
211 *
212 * @param pFile Path of the file to be imported.
213 * @param pScene The scene object to hold the imported data.
214 * NULL is not a valid parameter.
215 * @param pIOHandler The IO handler to use for any file access.
216 * NULL is not a valid parameter. */
217 virtual void InternReadFile(
218 const std::string& pFile,
219 aiScene* pScene,
220 IOSystem* pIOHandler
221 ) = 0;
223 public: // static utilities
225 // -------------------------------------------------------------------
226 /** A utility for CanRead().
227 *
228 * The function searches the header of a file for a specific token
229 * and returns true if this token is found. This works for text
230 * files only. There is a rudimentary handling of UNICODE files.
231 * The comparison is case independent.
232 *
233 * @param pIOSystem IO System to work with
234 * @param file File name of the file
235 * @param tokens List of tokens to search for
236 * @param numTokens Size of the token array
237 * @param searchBytes Number of bytes to be searched for the tokens.
238 */
239 static bool SearchFileHeaderForToken(
240 IOSystem* pIOSystem,
241 const std::string& file,
242 const char** tokens,
243 unsigned int numTokens,
244 unsigned int searchBytes = 200,
245 bool tokensSol = false,
246 bool noAlphaBeforeTokens = false);
248 // -------------------------------------------------------------------
249 /** @brief Check whether a file has a specific file extension
250 * @param pFile Input file
251 * @param ext0 Extension to check for. Lowercase characters only, no dot!
252 * @param ext1 Optional second extension
253 * @param ext2 Optional third extension
254 * @note Case-insensitive
255 */
256 static bool SimpleExtensionCheck (
257 const std::string& pFile,
258 const char* ext0,
259 const char* ext1 = NULL,
260 const char* ext2 = NULL);
262 // -------------------------------------------------------------------
263 /** @brief Extract file extension from a string
264 * @param pFile Input file
265 * @return Extension without trailing dot, all lowercase
266 */
267 static std::string GetExtension (
268 const std::string& pFile);
270 // -------------------------------------------------------------------
271 /** @brief Check whether a file starts with one or more magic tokens
272 * @param pFile Input file
273 * @param pIOHandler IO system to be used
274 * @param magic n magic tokens
275 * @params num Size of magic
276 * @param offset Offset from file start where tokens are located
277 * @param Size of one token, in bytes. Maximally 16 bytes.
278 * @return true if one of the given tokens was found
279 *
280 * @note For convenience, the check is also performed for the
281 * byte-swapped variant of all tokens (big endian). Only for
282 * tokens of size 2,4.
283 */
284 static bool CheckMagicToken(
285 IOSystem* pIOHandler,
286 const std::string& pFile,
287 const void* magic,
288 unsigned int num,
289 unsigned int offset = 0,
290 unsigned int size = 4);
292 // -------------------------------------------------------------------
293 /** An utility for all text file loaders. It converts a file to our
294 * UTF8 character set. Errors are reported, but ignored.
295 *
296 * @param data File buffer to be converted to UTF8 data. The buffer
297 * is resized as appropriate. */
298 static void ConvertToUTF8(
299 std::vector<char>& data);
301 // -------------------------------------------------------------------
302 /** An utility for all text file loaders. It converts a file from our
303 * UTF8 character set back to ISO-8859-1. Errors are reported, but ignored.
304 *
305 * @param data File buffer to be converted from UTF8 to ISO-8859-1. The buffer
306 * is resized as appropriate. */
307 static void ConvertUTF8toISO8859_1(
308 std::string& data);
310 // -------------------------------------------------------------------
311 /// @brief Enum to define, if empty files are ok or not.
312 enum TextFileMode {
313 ALLOW_EMPTY,
314 FORBID_EMPTY
315 };
317 // -------------------------------------------------------------------
318 /** Utility for text file loaders which copies the contents of the
319 * file into a memory buffer and converts it to our UTF8
320 * representation.
321 * @param stream Stream to read from.
322 * @param data Output buffer to be resized and filled with the
323 * converted text file data. The buffer is terminated with
324 * a binary 0.
325 * @param mode Whether it is OK to load empty text files. */
326 static void TextFileToBuffer(
327 IOStream* stream,
328 std::vector<char>& data,
329 TextFileMode mode = FORBID_EMPTY);
331 // -------------------------------------------------------------------
332 /** Utility function to move a std::vector into a aiScene array
333 * @param vec The vector to be moved
334 * @param out The output pointer to the allocated array.
335 * @param numOut The output count of elements copied. */
336 template<typename T>
337 AI_FORCE_INLINE
338 static void CopyVector(
339 std::vector<T>& vec,
340 T*& out,
341 unsigned int& outLength)
342 {
343 outLength = unsigned(vec.size());
344 if (outLength) {
345 out = new T[outLength];
346 std::swap_ranges(vec.begin(), vec.end(), out);
347 }
348 }
350 protected:
351 /// Error description in case there was one.
352 std::string m_ErrorText;
353 /// Currently set progress handler.
354 ProgressHandler* m_progress;
355 };
359 } // end of namespace Assimp
361 #endif // AI_BASEIMPORTER_H_INC