VTK  9.3.20240418
vtkGLTFDocumentLoader.h
Go to the documentation of this file.
1 // SPDX-FileCopyrightText: Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
2 // SPDX-License-Identifier: BSD-3-Clause
3 
28 #ifndef vtkGLTFDocumentLoader_h
29 #define vtkGLTFDocumentLoader_h
30 
31 #include "GLTFSampler.h" // For "Sampler"
32 #include "vtkIOGeometryModule.h" // For export macro
33 #include "vtkObject.h"
34 #include "vtkResourceStream.h" // For "vtkResourceStream"
35 #include "vtkSmartPointer.h" // For "vtkSmartPointer"
36 #include "vtkURILoader.h" // For "vtkURILoader"
37 
38 #include <map> // For std::map
39 #include <memory> // For std::shared_ptr
40 #include <string> // For std::string
41 #include <vector> // For std::vector
42 
43 VTK_ABI_NAMESPACE_BEGIN
44 class vtkCellArray;
45 class vtkDataArray;
46 class vtkFloatArray;
47 class vtkImageData;
48 class vtkMatrix4x4;
49 class vtkPoints;
50 class vtkPolyData;
52 
53 class VTKIOGEOMETRY_EXPORT vtkGLTFDocumentLoader : public vtkObject
54 {
55 public:
58  void PrintSelf(ostream& os, vtkIndent indent) override;
59 
63  enum class Target : unsigned short
64  {
65  ARRAY_BUFFER = 34962,
66  ELEMENT_ARRAY_BUFFER = 34963
67  };
68 
73  enum class AccessorType : unsigned char
74  {
75  SCALAR,
76  VEC2,
77  VEC3,
78  VEC4,
79  MAT2,
80  MAT3,
81  MAT4,
82  INVALID
83  };
84 
89  enum class ComponentType : unsigned short
90  {
91  BYTE = 5120,
92  UNSIGNED_BYTE = 5121,
93  SHORT = 5122,
94  UNSIGNED_SHORT = 5123,
95  UNSIGNED_INT = 5125,
96  FLOAT = 5126
97  };
98 
99  /* The following structs help deserialize a glTF document, representing each object. As such,
100  * their members mostly match with the specification. Default values and boundaries are set
101  * according to the specification.
102  * Most of these structs contain a name property, which is optional, and, while being loaded, is
103  * not currently exploited by the loader.
104  * They are mostly root-level properties, and once created, are stored into vectors in the Model
105  * structure.
106  */
107 
112  struct BufferView
113  {
114  int Buffer;
118  int Target;
120  };
121 
128  struct Accessor
129  {
134  struct Sparse
135  {
136  int Count;
142  };
147  int Count;
148  unsigned int NumberOfComponents;
150  std::vector<double> Max;
151  std::vector<double> Min;
152  bool IsSparse;
155  };
156 
163  struct MorphTarget
164  {
165  // accessor indices from the .gltf file, the map's keys correspond to attribute names
166  std::map<std::string, int> AttributeIndices;
167  // attribute values
168  std::map<std::string, vtkSmartPointer<vtkFloatArray>> AttributeValues;
169  };
170 
178  struct Primitive
179  {
180  // accessor indices from the .glTF file, the map's keys correspond to attribute names
181  std::map<std::string, int> AttributeIndices;
184 
185  // attribute values from buffer data
186  std::map<std::string, vtkSmartPointer<vtkDataArray>> AttributeValues;
187 
189 
190  std::vector<MorphTarget> Targets;
191 
192  int Material;
193  int Mode;
194  int CellSize; // 1, 2 or 3, depending on draw mode
195 
196  // Primitive-specific extension metadata
197  struct Extensions
198  {
199  // KHR_draco_mesh_compression extension
200  // Only metadata are read (decoding and modifying the internal model is not done yet)
202  {
203  int BufferView = -1;
204  std::map<std::string, int> AttributeIndices;
205  };
207  };
209  };
210 
217  struct Node
218  {
219  std::vector<int> Children;
220  int Camera;
221  int Mesh;
222  int Skin;
223 
226 
227  bool TRSLoaded;
228 
230 
231  std::vector<float> InitialRotation;
232  std::vector<float> InitialTranslation;
233  std::vector<float> InitialScale;
234  std::vector<float> InitialWeights;
235  std::vector<float> Rotation;
236  std::vector<float> Translation;
237  std::vector<float> Scale;
238  std::vector<float> Weights;
239 
240  // Object-specific extension metadata
241  struct Extensions
242  {
243  // KHR_lights_punctual extension
245  {
246  int Light = -1;
247  };
249  };
251 
253 
255  };
256 
261  struct Mesh
262  {
263  std::vector<struct Primitive> Primitives;
264  std::vector<float> Weights;
266  };
267 
273  struct TextureInfo
274  {
275  int Index = -1;
276  int TexCoord;
277  };
278 
283  struct Image
284  {
288 
290 
292  };
293 
300  struct Material
301  {
302  enum class AlphaModeType : unsigned char
303  {
304  OPAQUE,
305  MASK,
306  BLEND
307  };
308 
310  {
312  std::vector<double> BaseColorFactor;
313 
317  };
318 
320 
326  std::vector<double> EmissiveFactor;
327 
329  double AlphaCutoff;
330 
332 
334 
335  // extension KHR_materials_unlit
336  bool Unlit;
337  };
338 
343  struct Texture
344  {
345  int Sampler;
346  int Source;
348  };
349 
354  struct Sampler : public GLTFSampler
355  {
357  };
358 
364  struct Scene
365  {
366  std::vector<unsigned int> Nodes;
368  };
369 
375  struct Skin
376  {
377  std::vector<vtkSmartPointer<vtkMatrix4x4>> InverseBindMatrices;
378  std::vector<int> Joints;
380  int Skeleton;
382  };
383 
390  struct Animation
391  {
392  struct Sampler
393  {
394  enum class InterpolationMode : unsigned char
395  {
396  LINEAR,
397  STEP,
398  CUBICSPLINE
399  };
401  unsigned int Input;
402  unsigned int Output;
404 
407 
411  void GetInterpolatedData(float t, size_t numberOfComponents, std::vector<float>* output,
412  bool forceStep = false, bool isRotation = false) const;
413  };
414 
415  struct Channel
416  {
417  enum class PathType : unsigned char
418  {
419  ROTATION,
420  TRANSLATION,
421  SCALE,
422  WEIGHTS
423  };
424  int Sampler;
427  };
428 
429  float Duration; // In seconds
430  std::vector<Animation::Channel> Channels;
431  std::vector<Animation::Sampler> Samplers;
433  };
434 
440  struct Camera
441  {
442  // common properties
443  double Znear;
444  double Zfar;
445  bool IsPerspective; // if not, camera mode is orthographic
446  // perspective
447  double Xmag;
448  double Ymag;
449  // orthographic
450  double Yfov;
451  double AspectRatio;
453  };
454 
461  struct Extensions
462  {
463  // KHR_lights_punctual extension
465  {
466  struct Light
467  {
468  enum class LightType : unsigned char
469  {
470  DIRECTIONAL,
471  POINT,
472  SPOT
473  };
475 
476  std::vector<double> Color;
477  double Intensity;
478  double Range;
479 
480  // Type-specific parameters
483 
485  };
486  std::vector<Light> Lights;
487  };
489  };
490 
494  struct Model
495  {
496  std::vector<Accessor> Accessors;
497  std::vector<Animation> Animations;
498  std::vector<std::vector<char>> Buffers;
499  std::vector<BufferView> BufferViews;
500  std::vector<Camera> Cameras;
501  std::vector<Image> Images;
502  std::vector<Material> Materials;
503  std::vector<Mesh> Meshes;
504  std::vector<Node> Nodes;
505  std::vector<Sampler> Samplers;
506  std::vector<Scene> Scenes;
507  std::vector<Skin> Skins;
508  std::vector<Texture> Textures;
509 
511 
517  };
518 
523  bool ApplyAnimation(float t, int animationId, bool forceStep = false);
524 
528  void ResetAnimation(int animationId);
529 
531 
536  bool LoadFileBuffer(VTK_FILEPATH const std::string& fileName, std::vector<char>& glbBuffer);
537  bool LoadStreamBuffer(vtkResourceStream* stream, std::vector<char>& glbBuffer);
539 
541 
552 
556  bool LoadModelData(const std::vector<char>& glbBuffer);
557 
562 
566  std::shared_ptr<Model> GetInternalModel();
567 
572 
576  virtual std::vector<std::string> GetSupportedExtensions();
577 
581  const std::vector<std::string>& GetUsedExtensions();
582 
589  void BuildGlobalTransforms(unsigned int nodeIndex, vtkSmartPointer<vtkMatrix4x4> parentTransform);
590 
595 
599  static void ComputeJointMatrices(const Model& model, const Skin& skin, Node& node,
601 
608  virtual void PrepareData() {}
609 
611 
616  vtkSetMacro(GLBStart, vtkTypeInt64);
617  vtkGetMacro(GLBStart, vtkTypeInt64);
619 
620 protected:
622  ~vtkGLTFDocumentLoader() override = default;
623 
624 private:
625  struct AccessorLoadingWorker;
626 
627  struct SparseAccessorLoadingWorker;
628 
629  template <typename Type>
630  struct BufferDataExtractionWorker;
631 
633  void operator=(const vtkGLTFDocumentLoader&) = delete;
634 
638  bool LoadSkinMatrixData();
639 
644  bool ExtractPrimitiveAttributes(Primitive& primitive);
645 
652  bool ExtractPrimitiveAccessorData(Primitive& primitive);
653 
658  bool BuildPolyDataFromPrimitive(Primitive& primitive);
659 
663  bool LoadAnimationData();
664 
668  bool LoadImageData();
669 
670  std::shared_ptr<Model> InternalModel;
671 
672  static const std::vector<std::string> SupportedExtensions;
673  std::vector<std::string> UsedExtensions;
674  vtkTypeInt64 GLBStart = 0;
675 };
676 
677 VTK_ABI_NAMESPACE_END
678 #endif
object to represent cell connectivity
Definition: vtkCellArray.h:286
abstract superclass for arrays of numeric data
Definition: vtkDataArray.h:155
dynamic, self-adjusting array of float
Deserialize a GLTF model file.
AccessorType
Defines an accessor's type.
static vtkGLTFDocumentLoader * New()
void ResetAnimation(int animationId)
Restore the transforms that were modified by an animation to their initial state.
bool LoadFileBuffer(VTK_FILEPATH const std::string &fileName, std::vector< char > &glbBuffer)
Load the binary part of a binary glTF (.glb) file.
bool LoadModelMetaDataFromFile(VTK_FILEPATH const std::string &FileName)
Reset internal Model struct, and serialize glTF metadata (all json information) into it.
bool LoadModelMetaDataFromStream(vtkResourceStream *stream, vtkURILoader *loader=nullptr)
Reset internal Model struct, and serialize glTF metadata (all json information) into it.
bool LoadModelData(const std::vector< char > &glbBuffer)
Load buffer data into the internal Model.
void BuildGlobalTransforms(unsigned int nodeIndex, vtkSmartPointer< vtkMatrix4x4 > parentTransform)
Concatenate the current node's local transform to its parent's global transform, storing the resultin...
static unsigned int GetNumberOfComponentsForType(vtkGLTFDocumentLoader::AccessorType type)
Returns the number of components for a given accessor type.
virtual void PrepareData()
Some extensions require a preparation on the model before building VTK objects.
void PrintSelf(ostream &os, vtkIndent indent) override
Methods invoked by print to print information about the object including superclasses.
static void ComputeJointMatrices(const Model &model, const Skin &skin, Node &node, std::vector< vtkSmartPointer< vtkMatrix4x4 >> &jointMats)
Compute all joint matrices of the skin of a specific node.
Target
Define an openGL draw target.
bool ApplyAnimation(float t, int animationId, bool forceStep=false)
Apply the specified animation, at the specified time value t, to the internal Model.
virtual std::vector< std::string > GetSupportedExtensions()
Get the list of extensions that are supported by this loader.
~vtkGLTFDocumentLoader() override=default
vtkGLTFDocumentLoader()=default
std::shared_ptr< Model > GetInternalModel()
Get the internal Model.
const std::vector< std::string > & GetUsedExtensions()
Get the list of extensions that are used by the current model.
bool LoadStreamBuffer(vtkResourceStream *stream, std::vector< char > &glbBuffer)
Load the binary part of a binary glTF (.glb) file.
ComponentType
Define a type for different data components.
bool BuildModelVTKGeometry()
Converts the internal Model's loaded data into more convenient vtk objects.
void BuildGlobalTransforms()
Build all global transforms.
topologically and geometrically regular array of data
Definition: vtkImageData.h:156
a simple class to control print indentation
Definition: vtkIndent.h:108
represent and manipulate 4x4 transformation matrices
Definition: vtkMatrix4x4.h:141
abstract base class for most VTK objects
Definition: vtkObject.h:162
represent and manipulate 3D points
Definition: vtkPoints.h:139
concrete dataset represents vertices, lines, polygons, and triangle strips
Definition: vtkPolyData.h:181
Abstract class used for custom streams.
Helper class for readers and importer that need to load more than one resource.
Definition: vtkURILoader.h:100
dynamic, self-adjusting array of unsigned short
@ vector
Definition: vtkX3D.h:237
@ type
Definition: vtkX3D.h:516
@ string
Definition: vtkX3D.h:490
This struct describes a glTF sampler object.
Definition: GLTFSampler.h:16
This struct describes an accessor.sparse glTF object.
This struct describes an accessor glTF object.
vtkSmartPointer< vtkFloatArray > OutputData
vtkSmartPointer< vtkFloatArray > InputData
void GetInterpolatedData(float t, size_t numberOfComponents, std::vector< float > *output, bool forceStep=false, bool isRotation=false) const
Get the interpolated animation output at time t.
This struct describes a glTF animation object.
std::vector< Animation::Channel > Channels
std::vector< Animation::Sampler > Samplers
This struct describes a glTF bufferView object.
This struct describes a glTF camera object.
This struct contains extension metadata.
This struct describes a glTF image object.
vtkSmartPointer< vtkImageData > ImageData
This struct describes a glTF material object.
This struct describes a glTF mesh object.
std::vector< struct Primitive > Primitives
This struct contains all data from a gltf asset.
std::vector< std::vector< char > > Buffers
std::vector< BufferView > BufferViews
vtkSmartPointer< vtkResourceStream > Stream
std::vector< Animation > Animations
std::vector< Material > Materials
std::vector< Accessor > Accessors
vtkSmartPointer< vtkURILoader > URILoader
This struct describes a glTF Morph Target object.
std::map< std::string, vtkSmartPointer< vtkFloatArray > > AttributeValues
std::map< std::string, int > AttributeIndices
Node::Extensions::KHRLightsPunctual KHRLightsPunctualMetaData
This struct describes a glTF node object.
vtkSmartPointer< vtkMatrix4x4 > GlobalTransform
vtkSmartPointer< vtkMatrix4x4 > Matrix
vtkSmartPointer< vtkMatrix4x4 > Transform
std::vector< float > InitialRotation
std::vector< float > InitialWeights
std::vector< float > InitialTranslation
Primitive::Extensions::KHRDracoMeshCompression KHRDracoMetaData
This struct describes a glTF primitive object.
vtkSmartPointer< vtkCellArray > Indices
std::map< std::string, int > AttributeIndices
std::vector< MorphTarget > Targets
vtkSmartPointer< vtkPolyData > Geometry
std::map< std::string, vtkSmartPointer< vtkDataArray > > AttributeValues
This struct describes a glTF sampler object.
This struct describes a glTF scene object.
std::vector< unsigned int > Nodes
This struct describes a glTF asset.
std::vector< vtkSmartPointer< vtkMatrix4x4 > > InverseBindMatrices
This struct describes a glTF textureInfo object, mostly used in material descriptions They contain tw...
This struct describes a glTF texture object.
#define ARRAY_BUFFER
#define ELEMENT_ARRAY_BUFFER
#define VTK_FILEPATH