glTF2Asset.h 36 KB

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