glTFAsset.h 33 KB

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