glTFAsset.h 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196
  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 glTFAsset.h
  34. * Declares a glTF class to handle gltf/glb files
  35. *
  36. * glTF Extensions Support:
  37. * KHR_binary_glTF: full
  38. * KHR_materials_common: full
  39. */
  40. #ifndef GLTFASSET_H_INC
  41. #define GLTFASSET_H_INC
  42. #ifndef ASSIMP_BUILD_NO_GLTF_IMPORTER
  43. #include <map>
  44. #include <string>
  45. #include <list>
  46. #include <vector>
  47. #include <algorithm>
  48. #include <stdexcept>
  49. #define RAPIDJSON_HAS_STDSTRING 1
  50. #include <rapidjson/rapidjson.h>
  51. #include <rapidjson/document.h>
  52. #include <rapidjson/error/en.h>
  53. #ifdef ASSIMP_API
  54. # include <memory>
  55. # include <assimp/DefaultIOSystem.h>
  56. # include "ByteSwapper.h"
  57. #else
  58. # include <memory>
  59. # define AI_SWAP4(p)
  60. # define ai_assert
  61. #endif
  62. #if _MSC_VER > 1500 || (defined __GNUC___)
  63. # define ASSIMP_GLTF_USE_UNORDERED_MULTIMAP
  64. # else
  65. # define gltf_unordered_map map
  66. #endif
  67. #ifdef ASSIMP_GLTF_USE_UNORDERED_MULTIMAP
  68. # include <unordered_map>
  69. # if _MSC_VER > 1600
  70. # define gltf_unordered_map unordered_map
  71. # else
  72. # define gltf_unordered_map tr1::unordered_map
  73. # endif
  74. #endif
  75. namespace glTF
  76. {
  77. #ifdef ASSIMP_API
  78. using Assimp::IOStream;
  79. using Assimp::IOSystem;
  80. using std::shared_ptr;
  81. #else
  82. using std::shared_ptr;
  83. typedef std::runtime_error DeadlyImportError;
  84. typedef std::runtime_error DeadlyExportError;
  85. enum aiOrigin { aiOrigin_SET = 0, aiOrigin_CUR = 1, aiOrigin_END = 2 };
  86. class IOSystem;
  87. class IOStream
  88. {
  89. FILE* f;
  90. public:
  91. IOStream(FILE* file) : f(file) {}
  92. ~IOStream() { fclose(f); f = 0; }
  93. size_t Read(void* b, size_t sz, size_t n) { return fread(b, sz, n, f); }
  94. size_t Write(const void* b, size_t sz, size_t n) { return fwrite(b, sz, n, f); }
  95. int Seek(size_t off, aiOrigin orig) { return fseek(f, off, int(orig)); }
  96. size_t Tell() const { return ftell(f); }
  97. size_t FileSize() {
  98. long p = Tell(), len = (Seek(0, aiOrigin_END), Tell());
  99. return size_t((Seek(p, aiOrigin_SET), len));
  100. }
  101. };
  102. #endif
  103. using rapidjson::Value;
  104. using rapidjson::Document;
  105. class Asset;
  106. class AssetWriter;
  107. struct BufferView; // here due to cross-reference
  108. struct Texture;
  109. struct Light;
  110. struct Skin;
  111. // Vec/matrix types, as raw float arrays
  112. typedef float (vec3)[3];
  113. typedef float (vec4)[4];
  114. typedef float (mat4)[16];
  115. namespace Util
  116. {
  117. void EncodeBase64(const uint8_t* in, size_t inLength, std::string& out);
  118. size_t DecodeBase64(const char* in, size_t inLength, uint8_t*& out);
  119. inline size_t DecodeBase64(const char* in, uint8_t*& out)
  120. {
  121. return DecodeBase64(in, strlen(in), out);
  122. }
  123. struct DataURI
  124. {
  125. const char* mediaType;
  126. const char* charset;
  127. bool base64;
  128. const char* data;
  129. size_t dataLength;
  130. };
  131. //! Check if a uri is a data URI
  132. inline bool ParseDataURI(const char* uri, size_t uriLen, DataURI& out);
  133. }
  134. //! Magic number for GLB files
  135. #define AI_GLB_MAGIC_NUMBER "glTF"
  136. #ifdef ASSIMP_API
  137. #include "./../include/assimp/Compiler/pushpack1.h"
  138. #endif
  139. //! For the KHR_binary_glTF extension (binary .glb file)
  140. //! 20-byte header (+ the JSON + a "body" data section)
  141. struct GLB_Header
  142. {
  143. uint8_t magic[4]; //!< Magic number: "glTF"
  144. uint32_t version; //!< Version number (always 1 as of the last update)
  145. uint32_t length; //!< Total length of the Binary glTF, including header, scene, and body, in bytes
  146. uint32_t sceneLength; //!< Length, in bytes, of the glTF scene
  147. uint32_t sceneFormat; //!< Specifies the format of the glTF scene (see the SceneFormat enum)
  148. } PACK_STRUCT;
  149. #ifdef ASSIMP_API
  150. #include "./../include/assimp/Compiler/poppack1.h"
  151. #endif
  152. //! Values for the GLB_Header::sceneFormat field
  153. enum SceneFormat
  154. {
  155. SceneFormat_JSON = 0
  156. };
  157. //! Values for the mesh primitive modes
  158. enum PrimitiveMode
  159. {
  160. PrimitiveMode_POINTS = 0,
  161. PrimitiveMode_LINES = 1,
  162. PrimitiveMode_LINE_LOOP = 2,
  163. PrimitiveMode_LINE_STRIP = 3,
  164. PrimitiveMode_TRIANGLES = 4,
  165. PrimitiveMode_TRIANGLE_STRIP = 5,
  166. PrimitiveMode_TRIANGLE_FAN = 6
  167. };
  168. //! Values for the Accessor::componentType field
  169. enum ComponentType
  170. {
  171. ComponentType_BYTE = 5120,
  172. ComponentType_UNSIGNED_BYTE = 5121,
  173. ComponentType_SHORT = 5122,
  174. ComponentType_UNSIGNED_SHORT = 5123,
  175. ComponentType_UNSIGNED_INT = 5125,
  176. ComponentType_FLOAT = 5126
  177. };
  178. inline unsigned int ComponentTypeSize(ComponentType t)
  179. {
  180. switch (t) {
  181. case ComponentType_SHORT:
  182. case ComponentType_UNSIGNED_SHORT:
  183. return 2;
  184. case ComponentType_UNSIGNED_INT:
  185. case ComponentType_FLOAT:
  186. return 4;
  187. case ComponentType_BYTE:
  188. case ComponentType_UNSIGNED_BYTE:
  189. return 1;
  190. default:
  191. std::string err = "GLTF: Unsupported Component Type ";
  192. err += t;
  193. throw DeadlyImportError(err);
  194. }
  195. }
  196. //! Values for the BufferView::target field
  197. enum BufferViewTarget
  198. {
  199. BufferViewTarget_ARRAY_BUFFER = 34962,
  200. BufferViewTarget_ELEMENT_ARRAY_BUFFER = 34963
  201. };
  202. //! Values for the Sampler::magFilter field
  203. enum SamplerMagFilter
  204. {
  205. SamplerMagFilter_Nearest = 9728,
  206. SamplerMagFilter_Linear = 9729
  207. };
  208. //! Values for the Sampler::minFilter field
  209. enum SamplerMinFilter
  210. {
  211. SamplerMinFilter_Nearest = 9728,
  212. SamplerMinFilter_Linear = 9729,
  213. SamplerMinFilter_Nearest_Mipmap_Nearest = 9984,
  214. SamplerMinFilter_Linear_Mipmap_Nearest = 9985,
  215. SamplerMinFilter_Nearest_Mipmap_Linear = 9986,
  216. SamplerMinFilter_Linear_Mipmap_Linear = 9987
  217. };
  218. //! Values for the Sampler::wrapS and Sampler::wrapT field
  219. enum SamplerWrap
  220. {
  221. SamplerWrap_Clamp_To_Edge = 33071,
  222. SamplerWrap_Mirrored_Repeat = 33648,
  223. SamplerWrap_Repeat = 10497
  224. };
  225. //! Values for the Texture::format and Texture::internalFormat fields
  226. enum TextureFormat
  227. {
  228. TextureFormat_ALPHA = 6406,
  229. TextureFormat_RGB = 6407,
  230. TextureFormat_RGBA = 6408,
  231. TextureFormat_LUMINANCE = 6409,
  232. TextureFormat_LUMINANCE_ALPHA = 6410
  233. };
  234. //! Values for the Texture::target field
  235. enum TextureTarget
  236. {
  237. TextureTarget_TEXTURE_2D = 3553
  238. };
  239. //! Values for the Texture::type field
  240. enum TextureType
  241. {
  242. TextureType_UNSIGNED_BYTE = 5121,
  243. TextureType_UNSIGNED_SHORT_5_6_5 = 33635,
  244. TextureType_UNSIGNED_SHORT_4_4_4_4 = 32819,
  245. TextureType_UNSIGNED_SHORT_5_5_5_1 = 32820
  246. };
  247. //! Values for the Accessor::type field (helper class)
  248. class AttribType
  249. {
  250. public:
  251. enum Value
  252. { SCALAR, VEC2, VEC3, VEC4, MAT2, MAT3, MAT4 };
  253. private:
  254. static const size_t NUM_VALUES = static_cast<size_t>(MAT4)+1;
  255. struct Info
  256. { const char* name; unsigned int numComponents; };
  257. template<int N> struct data
  258. { static const Info infos[NUM_VALUES]; };
  259. public:
  260. inline static Value FromString(const char* str)
  261. {
  262. for (size_t i = 0; i < NUM_VALUES; ++i) {
  263. if (strcmp(data<0>::infos[i].name, str) == 0) {
  264. return static_cast<Value>(i);
  265. }
  266. }
  267. return SCALAR;
  268. }
  269. inline static const char* ToString(Value type)
  270. {
  271. return data<0>::infos[static_cast<size_t>(type)].name;
  272. }
  273. inline static unsigned int GetNumComponents(Value type)
  274. {
  275. return data<0>::infos[static_cast<size_t>(type)].numComponents;
  276. }
  277. };
  278. // must match the order of the AttribTypeTraits::Value enum!
  279. template<int N> const AttribType::Info
  280. AttribType::data<N>::infos[AttribType::NUM_VALUES] = {
  281. { "SCALAR", 1 }, { "VEC2", 2 }, { "VEC3", 3 }, { "VEC4", 4 }, { "MAT2", 4 }, { "MAT3", 9 }, { "MAT4", 16 }
  282. };
  283. //! A reference to one top-level object, which is valid
  284. //! until the Asset instance is destroyed
  285. template<class T>
  286. class Ref
  287. {
  288. std::vector<T*>* vector;
  289. unsigned int index;
  290. public:
  291. Ref() : vector(0), index(0) {}
  292. Ref(std::vector<T*>& vec, unsigned int idx) : vector(&vec), index(idx) {}
  293. inline unsigned int GetIndex() const
  294. { return index; }
  295. operator bool() const
  296. { return vector != 0; }
  297. T* operator->()
  298. { return (*vector)[index]; }
  299. T& operator*()
  300. { return *((*vector)[index]); }
  301. };
  302. //! Helper struct to represent values that might not be present
  303. template<class T>
  304. struct Nullable
  305. {
  306. T value;
  307. bool isPresent;
  308. Nullable() : isPresent(false) {}
  309. Nullable(T& val) : value(val), isPresent(true) {}
  310. };
  311. //! Base classe for all glTF top-level objects
  312. struct Object
  313. {
  314. std::string id; //!< The globally unique ID used to reference this object
  315. std::string name; //!< The user-defined name of this object
  316. //! Objects marked as special are not exported (used to emulate the binary body buffer)
  317. virtual bool IsSpecial() const
  318. { return false; }
  319. virtual ~Object() {}
  320. //! Maps special IDs to another ID, where needed. Subclasses may override it (statically)
  321. static const char* TranslateId(Asset& /*r*/, const char* id)
  322. { return id; }
  323. };
  324. //
  325. // Classes for each glTF top-level object type
  326. //
  327. //! A typed view into a BufferView. A BufferView contains raw binary data.
  328. //! An accessor provides a typed view into a BufferView or a subset of a BufferView
  329. //! similar to how WebGL's vertexAttribPointer() defines an attribute in a buffer.
  330. struct Accessor : public Object
  331. {
  332. Ref<BufferView> bufferView; //!< The ID of the bufferView. (required)
  333. unsigned int byteOffset; //!< The offset relative to the start of the bufferView in bytes. (required)
  334. unsigned int byteStride; //!< The stride, in bytes, between attributes referenced by this accessor. (default: 0)
  335. ComponentType componentType; //!< The datatype of components in the attribute. (required)
  336. unsigned int count; //!< The number of attributes referenced by this accessor. (required)
  337. AttribType::Value type; //!< Specifies if the attribute is a scalar, vector, or matrix. (required)
  338. std::vector<float> max; //!< Maximum value of each component in this attribute.
  339. std::vector<float> min; //!< Minimum value of each component in this attribute.
  340. unsigned int GetNumComponents();
  341. unsigned int GetBytesPerComponent();
  342. unsigned int GetElementSize();
  343. inline uint8_t* GetPointer();
  344. template<class T>
  345. bool ExtractData(T*& outData);
  346. void WriteData(size_t count, const void* src_buffer, size_t src_stride);
  347. //! Helper class to iterate the data
  348. class Indexer
  349. {
  350. friend struct Accessor;
  351. Accessor& accessor;
  352. uint8_t* data;
  353. size_t elemSize, stride;
  354. Indexer(Accessor& acc);
  355. public:
  356. //! Accesses the i-th value as defined by the accessor
  357. template<class T>
  358. T GetValue(int i);
  359. //! Accesses the i-th value as defined by the accessor
  360. inline unsigned int GetUInt(int i)
  361. {
  362. return GetValue<unsigned int>(i);
  363. }
  364. inline bool IsValid() const
  365. {
  366. return data != 0;
  367. }
  368. };
  369. inline Indexer GetIndexer()
  370. {
  371. return Indexer(*this);
  372. }
  373. Accessor() {}
  374. void Read(Value& obj, Asset& r);
  375. };
  376. //! A buffer points to binary geometry, animation, or skins.
  377. struct Buffer : public Object
  378. {
  379. /********************* Types *********************/
  380. public:
  381. enum Type
  382. {
  383. Type_arraybuffer,
  384. Type_text
  385. };
  386. /// \struct SEncodedRegion
  387. /// Descriptor of encoded region in "bufferView".
  388. struct SEncodedRegion
  389. {
  390. const size_t Offset;///< Offset from begin of "bufferView" to encoded region, in bytes.
  391. const size_t EncodedData_Length;///< Size of encoded region, in bytes.
  392. uint8_t* const DecodedData;///< Cached encoded data.
  393. const size_t DecodedData_Length;///< Size of decoded region, in bytes.
  394. const std::string ID;///< ID of the region.
  395. /// \fn SEncodedRegion(const size_t pOffset, const size_t pEncodedData_Length, uint8_t* pDecodedData, const size_t pDecodedData_Length, const std::string pID)
  396. /// Constructor.
  397. /// \param [in] pOffset - offset from begin of "bufferView" to encoded region, in bytes.
  398. /// \param [in] pEncodedData_Length - size of encoded region, in bytes.
  399. /// \param [in] pDecodedData - pointer to decoded data array.
  400. /// \param [in] pDecodedData_Length - size of encoded region, in bytes.
  401. /// \param [in] pID - ID of the region.
  402. SEncodedRegion(const size_t pOffset, const size_t pEncodedData_Length, uint8_t* pDecodedData, const size_t pDecodedData_Length, const std::string pID)
  403. : Offset(pOffset), EncodedData_Length(pEncodedData_Length), DecodedData(pDecodedData), DecodedData_Length(pDecodedData_Length), ID(pID)
  404. {}
  405. /// \fn ~SEncodedRegion()
  406. /// Destructor.
  407. ~SEncodedRegion() { delete [] DecodedData; }
  408. };
  409. /******************* Variables *******************/
  410. //std::string uri; //!< The uri of the buffer. Can be a filepath, a data uri, etc. (required)
  411. size_t byteLength; //!< The length of the buffer in bytes. (default: 0)
  412. //std::string type; //!< XMLHttpRequest responseType (default: "arraybuffer")
  413. Type type;
  414. /// \var EncodedRegion_Current
  415. /// Pointer to currently active encoded region.
  416. /// Why not decoding all regions at once and not to set one buffer with decoded data?
  417. /// Yes, why not? Even "accessor" point to decoded data. I mean that fields "byteOffset", "byteStride" and "count" has values which describes decoded
  418. /// data array. But only in range of mesh while is active parameters from "compressedData". For another mesh accessors point to decoded data too. But
  419. /// offset is counted for another regions is encoded.
  420. /// Example. You have two meshes. For every of it you have 4 bytes of data. That data compressed to 2 bytes. So, you have buffer with encoded data:
  421. /// M1_E0, M1_E1, M2_E0, M2_E1.
  422. /// After decoding you'll get:
  423. /// M1_D0, M1_D1, M1_D2, M1_D3, M2_D0, M2_D1, M2_D2, M2_D3.
  424. /// "accessors" must to use values that point to decoded data - obviously. So, you'll expect "accessors" like
  425. /// "accessor_0" : { byteOffset: 0, byteLength: 4}, "accessor_1" : { byteOffset: 4, byteLength: 4}
  426. /// but in real life you'll get:
  427. /// "accessor_0" : { byteOffset: 0, byteLength: 4}, "accessor_1" : { byteOffset: 2, byteLength: 4}
  428. /// Yes, accessor of next mesh has offset and length which mean: current mesh data is decoded, all other data is encoded.
  429. /// And when before you start to read data of current mesh (with encoded data ofcourse) you must decode region of "bufferView", after read finished
  430. /// delete encoding mark. And after that you can repeat process: decode data of mesh, read, delete decoded data.
  431. ///
  432. /// Remark. Encoding all data at once is good in world with computers which do not has RAM limitation. So, you must use step by step encoding in
  433. /// exporter and importer. And, thanks to such way, there is no need to load whole file into memory.
  434. SEncodedRegion* EncodedRegion_Current;
  435. private:
  436. shared_ptr<uint8_t> mData; //!< Pointer to the data
  437. bool mIsSpecial; //!< Set to true for special cases (e.g. the body buffer)
  438. /// \var EncodedRegion_List
  439. /// List of encoded regions.
  440. std::list<SEncodedRegion*> EncodedRegion_List;
  441. /******************* Functions *******************/
  442. public:
  443. Buffer();
  444. ~Buffer();
  445. void Read(Value& obj, Asset& r);
  446. bool LoadFromStream(IOStream& stream, size_t length = 0, size_t baseOffset = 0);
  447. /// \fn void EncodedRegion_Mark(const size_t pOffset, const size_t pEncodedData_Length, uint8_t* pDecodedData, const size_t pDecodedData_Length, const std::string& pID)
  448. /// Mark region of "bufferView" as encoded. When data is request from such region then "bufferView" use decoded data.
  449. /// \param [in] pOffset - offset from begin of "bufferView" to encoded region, in bytes.
  450. /// \param [in] pEncodedData_Length - size of encoded region, in bytes.
  451. /// \param [in] pDecodedData - pointer to decoded data array.
  452. /// \param [in] pDecodedData_Length - size of encoded region, in bytes.
  453. /// \param [in] pID - ID of the region.
  454. void EncodedRegion_Mark(const size_t pOffset, const size_t pEncodedData_Length, uint8_t* pDecodedData, const size_t pDecodedData_Length, const std::string& pID);
  455. /// \fn void EncodedRegion_SetCurrent(const std::string& pID)
  456. /// Select current encoded region by ID. \sa EncodedRegion_Current.
  457. /// \param [in] pID - ID of the region.
  458. void EncodedRegion_SetCurrent(const std::string& pID);
  459. /// \fn bool ReplaceData(const size_t pBufferData_Offset, const size_t pBufferData_Count, const uint8_t* pReplace_Data, const size_t pReplace_Count)
  460. /// Replace part of buffer data. Pay attention that function work with original array of data (\ref mData) not with encoded regions.
  461. /// \param [in] pBufferData_Offset - index of first element in buffer from which new data will be placed.
  462. /// \param [in] pBufferData_Count - count of bytes in buffer which will be replaced.
  463. /// \param [in] pReplace_Data - pointer to array with new data for buffer.
  464. /// \param [in] pReplace_Count - count of bytes in new data.
  465. /// \return true - if successfully replaced, false if input arguments is out of range.
  466. bool ReplaceData(const size_t pBufferData_Offset, const size_t pBufferData_Count, const uint8_t* pReplace_Data, const size_t pReplace_Count);
  467. size_t AppendData(uint8_t* data, size_t length);
  468. void Grow(size_t amount);
  469. uint8_t* GetPointer()
  470. { return mData.get(); }
  471. void MarkAsSpecial()
  472. { mIsSpecial = true; }
  473. bool IsSpecial() const
  474. { return mIsSpecial; }
  475. std::string GetURI()
  476. { return std::string(this->id) + ".bin"; }
  477. static const char* TranslateId(Asset& r, const char* id);
  478. };
  479. //! A view into a buffer generally representing a subset of the buffer.
  480. struct BufferView : public Object
  481. {
  482. Ref<Buffer> buffer; //! The ID of the buffer. (required)
  483. size_t byteOffset; //! The offset into the buffer in bytes. (required)
  484. size_t byteLength; //! The length of the bufferView in bytes. (default: 0)
  485. BufferViewTarget target; //! The target that the WebGL buffer should be bound to.
  486. void Read(Value& obj, Asset& r);
  487. };
  488. struct Camera : public Object
  489. {
  490. enum Type
  491. {
  492. Perspective,
  493. Orthographic
  494. };
  495. Type type;
  496. union
  497. {
  498. struct {
  499. float aspectRatio; //!<The floating - point aspect ratio of the field of view. (0 = undefined = use the canvas one)
  500. float yfov; //!<The floating - point vertical field of view in radians. (required)
  501. float zfar; //!<The floating - point distance to the far clipping plane. (required)
  502. float znear; //!< The floating - point distance to the near clipping plane. (required)
  503. } perspective;
  504. struct {
  505. float xmag; //! The floating-point horizontal magnification of the view. (required)
  506. float ymag; //! The floating-point vertical magnification of the view. (required)
  507. float zfar; //! The floating-point distance to the far clipping plane. (required)
  508. float znear; //! The floating-point distance to the near clipping plane. (required)
  509. } ortographic;
  510. };
  511. Camera() {}
  512. void Read(Value& obj, Asset& r);
  513. };
  514. //! Image data used to create a texture.
  515. struct Image : public Object
  516. {
  517. std::string uri; //! The uri of the image, that can be a file path, a data URI, etc.. (required)
  518. Ref<BufferView> bufferView;
  519. std::string mimeType;
  520. int width, height;
  521. private:
  522. uint8_t* mData;
  523. size_t mDataLength;
  524. public:
  525. Image();
  526. void Read(Value& obj, Asset& r);
  527. inline bool HasData() const
  528. { return mDataLength > 0; }
  529. inline size_t GetDataLength() const
  530. { return mDataLength; }
  531. inline const uint8_t* GetData() const
  532. { return mData; }
  533. inline uint8_t* StealData();
  534. inline void SetData(uint8_t* data, size_t length, Asset& r);
  535. };
  536. //! Holds a material property that can be a texture or a color
  537. struct TexProperty
  538. {
  539. Ref<Texture> texture;
  540. vec4 color;
  541. };
  542. //! The material appearance of a primitive.
  543. struct Material : public Object
  544. {
  545. //Ref<Sampler> source; //!< The ID of the technique.
  546. //std::gltf_unordered_map<std::string, std::string> values; //!< A dictionary object of parameter values.
  547. //! Techniques defined by KHR_materials_common
  548. enum Technique
  549. {
  550. Technique_undefined = 0,
  551. Technique_BLINN,
  552. Technique_PHONG,
  553. Technique_LAMBERT,
  554. Technique_CONSTANT
  555. };
  556. TexProperty ambient;
  557. TexProperty diffuse;
  558. TexProperty specular;
  559. TexProperty emission;
  560. bool doubleSided;
  561. bool transparent;
  562. float transparency;
  563. float shininess;
  564. Technique technique;
  565. Material() { SetDefaults(); }
  566. void Read(Value& obj, Asset& r);
  567. void SetDefaults();
  568. };
  569. //! A set of primitives to be rendered. A node can contain one or more meshes. A node's transform places the mesh in the scene.
  570. struct Mesh : public Object
  571. {
  572. typedef std::vector< Ref<Accessor> > AccessorList;
  573. struct Primitive
  574. {
  575. PrimitiveMode mode;
  576. struct Attributes {
  577. AccessorList position, normal, texcoord, color, joint, jointmatrix, weight;
  578. } attributes;
  579. Ref<Accessor> indices;
  580. Ref<Material> material;
  581. };
  582. /// \struct SExtension
  583. /// Extension used for mesh.
  584. struct SExtension
  585. {
  586. /// \enum EType
  587. /// Type of extension.
  588. enum EType
  589. {
  590. #ifdef ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC
  591. Compression_Open3DGC,///< Compression of mesh data using Open3DGC algorithm.
  592. #endif
  593. Unknown
  594. };
  595. EType Type;///< Type of extension.
  596. /// \fn SExtension
  597. /// Constructor.
  598. /// \param [in] pType - type of extension.
  599. SExtension(const EType pType)
  600. : Type(pType)
  601. {}
  602. virtual ~SExtension() {
  603. // empty
  604. }
  605. };
  606. #ifdef ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC
  607. /// \struct SCompression_Open3DGC
  608. /// Compression of mesh data using Open3DGC algorithm.
  609. struct SCompression_Open3DGC : public SExtension
  610. {
  611. using SExtension::Type;
  612. std::string Buffer;///< ID of "buffer" used for storing compressed data.
  613. size_t Offset;///< Offset in "bufferView" where compressed data are stored.
  614. size_t Count;///< Count of elements in compressed data. Is always equivalent to size in bytes: look comments for "Type" and "Component_Type".
  615. bool Binary;///< If true then "binary" mode is used for coding, if false - "ascii" mode.
  616. size_t IndicesCount;///< Count of indices in mesh.
  617. size_t VerticesCount;///< Count of vertices in mesh.
  618. // AttribType::Value Type;///< Is always "SCALAR".
  619. // ComponentType Component_Type;///< Is always "ComponentType_UNSIGNED_BYTE" (5121).
  620. /// \fn SCompression_Open3DGC
  621. /// Constructor.
  622. SCompression_Open3DGC()
  623. : SExtension(Compression_Open3DGC) {
  624. // empty
  625. }
  626. virtual ~SCompression_Open3DGC() {
  627. // empty
  628. }
  629. };
  630. #endif
  631. std::vector<Primitive> primitives;
  632. std::list<SExtension*> Extension;///< List of extensions used in mesh.
  633. Mesh() {}
  634. /// \fn ~Mesh()
  635. /// Destructor.
  636. ~Mesh() { for(std::list<SExtension*>::iterator it = Extension.begin(), it_end = Extension.end(); it != it_end; it++) { delete *it; }; }
  637. /// \fn void Read(Value& pJSON_Object, Asset& pAsset_Root)
  638. /// Get mesh data from JSON-object and place them to root asset.
  639. /// \param [in] pJSON_Object - reference to pJSON-object from which data are read.
  640. /// \param [out] pAsset_Root - reference to root assed where data will be stored.
  641. void Read(Value& pJSON_Object, Asset& pAsset_Root);
  642. #ifdef ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC
  643. /// \fn void Decode_O3DGC(const SCompression_Open3DGC& pCompression_Open3DGC, Asset& pAsset_Root)
  644. /// Decode part of "buffer" which encoded with Open3DGC algorithm.
  645. /// \param [in] pCompression_Open3DGC - reference to structure which describe encoded region.
  646. /// \param [out] pAsset_Root - reference to root assed where data will be stored.
  647. void Decode_O3DGC(const SCompression_Open3DGC& pCompression_Open3DGC, Asset& pAsset_Root);
  648. #endif
  649. };
  650. struct Node : public Object
  651. {
  652. std::vector< Ref<Node> > children;
  653. std::vector< Ref<Mesh> > meshes;
  654. Nullable<mat4> matrix;
  655. Nullable<vec3> translation;
  656. Nullable<vec4> rotation;
  657. Nullable<vec3> scale;
  658. Ref<Camera> camera;
  659. Ref<Light> light;
  660. std::vector< Ref<Node> > skeletons; //!< The ID of skeleton nodes. Each of which is the root of a node hierarchy.
  661. Ref<Skin> skin; //!< The ID of the skin referenced by this node.
  662. std::string jointName; //!< Name used when this node is a joint in a skin.
  663. Ref<Node> parent; //!< This is not part of the glTF specification. Used as a helper.
  664. Node() {}
  665. void Read(Value& obj, Asset& r);
  666. };
  667. struct Program : public Object
  668. {
  669. Program() {}
  670. void Read(Value& obj, Asset& r);
  671. };
  672. struct Sampler : public Object
  673. {
  674. SamplerMagFilter magFilter; //!< The texture magnification filter. (required)
  675. SamplerMinFilter minFilter; //!< The texture minification filter. (required)
  676. SamplerWrap wrapS; //!< The texture wrapping in the S direction. (required)
  677. SamplerWrap wrapT; //!< The texture wrapping in the T direction. (required)
  678. Sampler() {}
  679. void Read(Value& obj, Asset& r);
  680. void SetDefaults();
  681. };
  682. struct Scene : public Object
  683. {
  684. std::vector< Ref<Node> > nodes;
  685. Scene() {}
  686. void Read(Value& obj, Asset& r);
  687. };
  688. struct Shader : public Object
  689. {
  690. Shader() {}
  691. void Read(Value& obj, Asset& r);
  692. };
  693. struct Skin : public Object
  694. {
  695. Nullable<mat4> bindShapeMatrix; //!< Floating-point 4x4 transformation matrix stored in column-major order.
  696. Ref<Accessor> inverseBindMatrices; //!< The ID of the accessor containing the floating-point 4x4 inverse-bind matrices.
  697. std::vector<Ref<Node>> jointNames; //!< Joint names of the joints (nodes with a jointName property) in this skin.
  698. std::string name; //!< The user-defined name of this object.
  699. Skin() {}
  700. void Read(Value& obj, Asset& r);
  701. };
  702. struct Technique : public Object
  703. {
  704. struct Parameters
  705. {
  706. };
  707. struct States
  708. {
  709. };
  710. struct Functions
  711. {
  712. };
  713. Technique() {}
  714. void Read(Value& obj, Asset& r);
  715. };
  716. //! A texture and its sampler.
  717. struct Texture : public Object
  718. {
  719. Ref<Sampler> sampler; //!< The ID of the sampler used by this texture. (required)
  720. Ref<Image> source; //!< The ID of the image used by this texture. (required)
  721. //TextureFormat format; //!< The texture's format. (default: TextureFormat_RGBA)
  722. //TextureFormat internalFormat; //!< The texture's internal format. (default: TextureFormat_RGBA)
  723. //TextureTarget target; //!< The target that the WebGL texture should be bound to. (default: TextureTarget_TEXTURE_2D)
  724. //TextureType type; //!< Texel datatype. (default: TextureType_UNSIGNED_BYTE)
  725. Texture() {}
  726. void Read(Value& obj, Asset& r);
  727. };
  728. //! A light (from KHR_materials_common extension)
  729. struct Light : public Object
  730. {
  731. enum Type
  732. {
  733. Type_undefined,
  734. Type_ambient,
  735. Type_directional,
  736. Type_point,
  737. Type_spot
  738. };
  739. Type type;
  740. vec4 color;
  741. float distance;
  742. float constantAttenuation;
  743. float linearAttenuation;
  744. float quadraticAttenuation;
  745. float falloffAngle;
  746. float falloffExponent;
  747. Light() {}
  748. void Read(Value& obj, Asset& r);
  749. void SetDefaults();
  750. };
  751. struct Animation : public Object
  752. {
  753. struct AnimSampler {
  754. std::string id; //!< The ID of this sampler.
  755. std::string input; //!< The ID of a parameter in this animation to use as key-frame input.
  756. std::string interpolation; //!< Type of interpolation algorithm to use between key-frames.
  757. std::string output; //!< The ID of a parameter in this animation to use as key-frame output.
  758. };
  759. struct AnimChannel {
  760. std::string sampler; //!< The ID of one sampler present in the containing animation's samplers property.
  761. struct AnimTarget {
  762. Ref<Node> id; //!< The ID of the node to animate.
  763. std::string path; //!< The name of property of the node to animate ("translation", "rotation", or "scale").
  764. } target;
  765. };
  766. struct AnimParameters {
  767. Ref<Accessor> TIME; //!< Accessor reference to a buffer storing a array of floating point scalar values.
  768. Ref<Accessor> rotation; //!< Accessor reference to a buffer storing a array of four-component floating-point vectors.
  769. Ref<Accessor> scale; //!< Accessor reference to a buffer storing a array of three-component floating-point vectors.
  770. Ref<Accessor> translation; //!< Accessor reference to a buffer storing a array of three-component floating-point vectors.
  771. };
  772. // AnimChannel Channels[3]; //!< Connect the output values of the key-frame animation to a specific node in the hierarchy.
  773. // AnimParameters Parameters; //!< The samplers that interpolate between the key-frames.
  774. // AnimSampler Samplers[3]; //!< The parameterized inputs representing the key-frame data.
  775. std::vector<AnimChannel> Channels; //!< Connect the output values of the key-frame animation to a specific node in the hierarchy.
  776. AnimParameters Parameters; //!< The samplers that interpolate between the key-frames.
  777. std::vector<AnimSampler> Samplers; //!< The parameterized inputs representing the key-frame data.
  778. Animation() {}
  779. void Read(Value& obj, Asset& r);
  780. };
  781. //! Base class for LazyDict that acts as an interface
  782. class LazyDictBase
  783. {
  784. public:
  785. virtual ~LazyDictBase() {}
  786. virtual void AttachToDocument(Document& doc) = 0;
  787. virtual void DetachFromDocument() = 0;
  788. virtual void WriteObjects(AssetWriter& writer) = 0;
  789. };
  790. template<class T>
  791. class LazyDict;
  792. //! (Implemented in glTFAssetWriter.h)
  793. template<class T>
  794. void WriteLazyDict(LazyDict<T>& d, AssetWriter& w);
  795. //! Manages lazy loading of the glTF top-level objects, and keeps a reference to them by ID
  796. //! It is the owner the loaded objects, so when it is destroyed it also deletes them
  797. template<class T>
  798. class LazyDict : public LazyDictBase
  799. {
  800. friend class Asset;
  801. friend class AssetWriter;
  802. typedef typename std::gltf_unordered_map< std::string, unsigned int > Dict;
  803. std::vector<T*> mObjs; //! The read objects
  804. Dict mObjsById; //! The read objects accessible by id
  805. const char* mDictId; //! ID of the dictionary object
  806. const char* mExtId; //! ID of the extension defining the dictionary
  807. Value* mDict; //! JSON dictionary object
  808. Asset& mAsset; //! The asset instance
  809. void AttachToDocument(Document& doc);
  810. void DetachFromDocument();
  811. void WriteObjects(AssetWriter& writer)
  812. { WriteLazyDict<T>(*this, writer); }
  813. Ref<T> Add(T* obj);
  814. public:
  815. LazyDict(Asset& asset, const char* dictId, const char* extId = 0);
  816. ~LazyDict();
  817. Ref<T> Get(const char* id);
  818. Ref<T> Get(unsigned int i);
  819. Ref<T> Get(const std::string& pID) { return Get(pID.c_str()); }
  820. Ref<T> Create(const char* id);
  821. Ref<T> Create(const std::string& id)
  822. { return Create(id.c_str()); }
  823. inline unsigned int Size() const
  824. { return unsigned(mObjs.size()); }
  825. inline T& operator[](size_t i)
  826. { return *mObjs[i]; }
  827. };
  828. struct AssetMetadata
  829. {
  830. std::string copyright; //!< A copyright message suitable for display to credit the content creator.
  831. std::string generator; //!< Tool that generated this glTF model.Useful for debugging.
  832. bool premultipliedAlpha; //!< Specifies if the shaders were generated with premultiplied alpha. (default: false)
  833. struct {
  834. std::string api; //!< Specifies the target rendering API (default: "WebGL")
  835. std::string version; //!< Specifies the target rendering API (default: "1.0.3")
  836. } profile; //!< Specifies the target rendering API and version, e.g., WebGL 1.0.3. (default: {})
  837. std::string version; //!< The glTF format version (should be 1.0)
  838. void Read(Document& doc);
  839. AssetMetadata()
  840. : premultipliedAlpha(false)
  841. , version("")
  842. {
  843. }
  844. };
  845. //
  846. // glTF Asset class
  847. //
  848. //! Root object for a glTF asset
  849. class Asset
  850. {
  851. typedef std::gltf_unordered_map<std::string, int> IdMap;
  852. template<class T>
  853. friend class LazyDict;
  854. friend struct Buffer; // To access OpenFile
  855. friend class AssetWriter;
  856. private:
  857. IOSystem* mIOSystem;
  858. std::string mCurrentAssetDir;
  859. size_t mSceneLength;
  860. size_t mBodyOffset, mBodyLength;
  861. std::vector<LazyDictBase*> mDicts;
  862. IdMap mUsedIds;
  863. Ref<Buffer> mBodyBuffer;
  864. Asset(Asset&);
  865. Asset& operator=(const Asset&);
  866. public:
  867. //! Keeps info about the enabled extensions
  868. struct Extensions
  869. {
  870. bool KHR_binary_glTF;
  871. bool KHR_materials_common;
  872. } extensionsUsed;
  873. AssetMetadata asset;
  874. // Dictionaries for each type of object
  875. LazyDict<Accessor> accessors;
  876. LazyDict<Animation> animations;
  877. LazyDict<Buffer> buffers;
  878. LazyDict<BufferView> bufferViews;
  879. LazyDict<Camera> cameras;
  880. LazyDict<Image> images;
  881. LazyDict<Material> materials;
  882. LazyDict<Mesh> meshes;
  883. LazyDict<Node> nodes;
  884. //LazyDict<Program> programs;
  885. LazyDict<Sampler> samplers;
  886. LazyDict<Scene> scenes;
  887. //LazyDict<Shader> shaders;
  888. LazyDict<Skin> skins;
  889. //LazyDict<Technique> techniques;
  890. LazyDict<Texture> textures;
  891. LazyDict<Light> lights; // KHR_materials_common ext
  892. Ref<Scene> scene;
  893. public:
  894. Asset(IOSystem* io = 0)
  895. : mIOSystem(io)
  896. , asset()
  897. , accessors (*this, "accessors")
  898. , animations (*this, "animations")
  899. , buffers (*this, "buffers")
  900. , bufferViews (*this, "bufferViews")
  901. , cameras (*this, "cameras")
  902. , images (*this, "images")
  903. , materials (*this, "materials")
  904. , meshes (*this, "meshes")
  905. , nodes (*this, "nodes")
  906. //, programs (*this, "programs")
  907. , samplers (*this, "samplers")
  908. , scenes (*this, "scenes")
  909. //, shaders (*this, "shaders")
  910. , skins (*this, "skins")
  911. //, techniques (*this, "techniques")
  912. , textures (*this, "textures")
  913. , lights (*this, "lights", "KHR_materials_common")
  914. {
  915. memset(&extensionsUsed, 0, sizeof(extensionsUsed));
  916. }
  917. //! Main function
  918. void Load(const std::string& file, bool isBinary = false);
  919. //! Enables the "KHR_binary_glTF" extension on the asset
  920. void SetAsBinary();
  921. //! Search for an available name, starting from the given strings
  922. std::string FindUniqueID(const std::string& str, const char* suffix);
  923. Ref<Buffer> GetBodyBuffer()
  924. { return mBodyBuffer; }
  925. private:
  926. void ReadBinaryHeader(IOStream& stream);
  927. void ReadExtensionsUsed(Document& doc);
  928. IOStream* OpenFile(std::string path, const char* mode, bool absolute = false);
  929. };
  930. }
  931. // Include the implementation of the methods
  932. #include "glTFAsset.inl"
  933. #endif // ASSIMP_BUILD_NO_GLTF_IMPORTER
  934. #endif // GLTFASSET_H_INC