gltf_json/
root.rs

1use crate::buffer;
2use crate::extensions;
3use crate::texture;
4use crate::validation;
5use gltf_derive::Validate;
6use serde_derive::{Deserialize, Serialize};
7use std::{self, fmt, io, marker};
8
9use crate::path::Path;
10use crate::{
11    Accessor, Animation, Asset, Buffer, Camera, Error, Extras, Image, Material, Mesh, Node, Scene,
12    Skin, Texture, Value,
13};
14use validation::Validate;
15
16// TODO: As a breaking change, simplify by replacing uses of `Get<T>` with `AsRef<[T]>`.
17
18/// Helper trait for retrieving top-level objects by a universal identifier.
19pub trait Get<T> {
20    /// Retrieves a single value at the given index.
21    fn get(&self, id: Index<T>) -> Option<&T>;
22}
23
24/// Represents an offset into a vector of type `T` owned by the root glTF object.
25///
26/// This type may be used with the following functions:
27///
28/// * [`Root::get()`] to retrieve objects from [`Root`].
29/// * [`Root::push()`] to add new objects to [`Root`].
30pub struct Index<T>(u32, marker::PhantomData<fn() -> T>);
31
32impl<T> Index<T> {
33    /// Given a vector of glTF objects, call [`Vec::push()`] to insert it into the vector,
34    /// then return an [`Index`] for it.
35    ///
36    /// This allows you to easily obtain [`Index`] values with the correct index and type when
37    /// creating a glTF asset. Note that for [`Root`], you can call [`Root::push()`] without
38    /// needing to retrieve the correct vector first.
39    ///
40    /// # Panics
41    ///
42    /// Panics if the vector has [`u32::MAX`] or more elements, in which case an `Index` cannot be
43    /// created.
44    pub fn push(vec: &mut Vec<T>, value: T) -> Index<T> {
45        let len = vec.len();
46        let Ok(index): Result<u32, _> = len.try_into() else {
47            panic!(
48                "glTF vector of {ty} has {len} elements, which exceeds the Index limit",
49                ty = std::any::type_name::<T>(),
50            );
51        };
52
53        vec.push(value);
54        Index::new(index)
55    }
56}
57
58/// The root object of a glTF 2.0 asset.
59#[derive(Clone, Debug, Default, Deserialize, Serialize, Validate)]
60#[gltf(validate_hook = "root_validate_hook")]
61pub struct Root {
62    /// An array of accessors.
63    #[serde(default)]
64    #[serde(skip_serializing_if = "Vec::is_empty")]
65    pub accessors: Vec<Accessor>,
66
67    /// An array of keyframe animations.
68    #[serde(default)]
69    #[serde(skip_serializing_if = "Vec::is_empty")]
70    pub animations: Vec<Animation>,
71
72    /// Metadata about the glTF asset.
73    pub asset: Asset,
74
75    /// An array of buffers.
76    #[serde(default)]
77    #[serde(skip_serializing_if = "Vec::is_empty")]
78    pub buffers: Vec<Buffer>,
79
80    /// An array of buffer views.
81    #[serde(default, rename = "bufferViews")]
82    #[serde(skip_serializing_if = "Vec::is_empty")]
83    pub buffer_views: Vec<buffer::View>,
84
85    /// The default scene.
86    #[serde(skip_serializing_if = "Option::is_none")]
87    pub scene: Option<Index<Scene>>,
88
89    /// Extension specific data.
90    #[serde(default, skip_serializing_if = "Option::is_none")]
91    pub extensions: Option<extensions::root::Root>,
92
93    /// Optional application specific data.
94    #[serde(default)]
95    #[cfg_attr(feature = "extras", serde(skip_serializing_if = "Option::is_none"))]
96    #[cfg_attr(not(feature = "extras"), serde(skip_serializing))]
97    pub extras: Extras,
98
99    /// Names of glTF extensions used somewhere in this asset.
100    #[serde(default, rename = "extensionsUsed")]
101    #[serde(skip_serializing_if = "Vec::is_empty")]
102    pub extensions_used: Vec<String>,
103
104    /// Names of glTF extensions required to properly load this asset.
105    #[serde(default, rename = "extensionsRequired")]
106    #[serde(skip_serializing_if = "Vec::is_empty")]
107    pub extensions_required: Vec<String>,
108
109    /// An array of cameras.
110    #[serde(default)]
111    #[serde(skip_serializing_if = "Vec::is_empty")]
112    pub cameras: Vec<Camera>,
113
114    /// An array of images.
115    #[serde(default)]
116    #[serde(skip_serializing_if = "Vec::is_empty")]
117    pub images: Vec<Image>,
118
119    /// An array of materials.
120    #[serde(default)]
121    #[serde(skip_serializing_if = "Vec::is_empty")]
122    pub materials: Vec<Material>,
123
124    /// An array of meshes.
125    #[serde(default)]
126    #[serde(skip_serializing_if = "Vec::is_empty")]
127    pub meshes: Vec<Mesh>,
128
129    /// An array of nodes.
130    #[serde(default)]
131    #[serde(skip_serializing_if = "Vec::is_empty")]
132    pub nodes: Vec<Node>,
133
134    /// An array of samplers.
135    #[serde(default)]
136    #[serde(skip_serializing_if = "Vec::is_empty")]
137    pub samplers: Vec<texture::Sampler>,
138
139    /// An array of scenes.
140    #[serde(default)]
141    #[serde(skip_serializing_if = "Vec::is_empty")]
142    pub scenes: Vec<Scene>,
143
144    /// An array of skins.
145    #[serde(default)]
146    #[serde(skip_serializing_if = "Vec::is_empty")]
147    pub skins: Vec<Skin>,
148
149    /// An array of textures.
150    #[serde(default)]
151    #[serde(skip_serializing_if = "Vec::is_empty")]
152    pub textures: Vec<Texture>,
153}
154
155fn root_validate_hook<P, R>(root: &Root, _also_root: &Root, path: P, report: &mut R)
156where
157    P: Fn() -> Path,
158    R: FnMut(&dyn Fn() -> Path, crate::validation::Error),
159{
160    for (i, ext) in root.extensions_required.iter().enumerate() {
161        if !crate::extensions::ENABLED_EXTENSIONS.contains(&ext.as_str()) {
162            report(
163                &|| {
164                    path()
165                        .field("extensionsRequired")
166                        .index(i)
167                        .value_str(ext.as_str())
168                },
169                crate::validation::Error::Unsupported,
170            );
171        }
172    }
173}
174
175impl Root {
176    /// Returns a single item from the root object.
177    pub fn get<T>(&self, index: Index<T>) -> Option<&T>
178    where
179        Self: Get<T>,
180    {
181        (self as &dyn Get<T>).get(index)
182    }
183
184    /// Insert the given value into this (as via [`Vec::push()`]), then return the [`Index`] to it.
185    ///
186    /// This allows you to easily obtain [`Index`] values with the correct index and type when
187    /// creating a glTF asset.
188    ///
189    /// If you have a mutable borrow conflict when using this method, consider using the more
190    /// explicit [`Index::push()`] method, passing it only the necessary vector.
191    ///
192    /// # Panics
193    ///
194    /// Panics if there are already [`u32::MAX`] or more elements of this type,
195    /// in which case an `Index` cannot be created.
196    #[track_caller]
197    pub fn push<T>(&mut self, value: T) -> Index<T>
198    where
199        Self: AsMut<Vec<T>>,
200    {
201        Index::push(self.as_mut(), value)
202    }
203
204    /// Deserialize from a JSON string slice.
205    #[allow(clippy::should_implement_trait)]
206    pub fn from_str(str_: &str) -> Result<Self, Error> {
207        serde_json::from_str(str_)
208    }
209
210    /// Deserialize from a JSON byte slice.
211    pub fn from_slice(slice: &[u8]) -> Result<Self, Error> {
212        serde_json::from_slice(slice)
213    }
214
215    /// Deserialize from a stream of JSON.
216    pub fn from_reader<R>(reader: R) -> Result<Self, Error>
217    where
218        R: io::Read,
219    {
220        serde_json::from_reader(reader)
221    }
222
223    /// Serialize as a `String` of JSON.
224    pub fn to_string(&self) -> Result<String, Error> {
225        serde_json::to_string(self)
226    }
227
228    /// Serialize as a pretty-printed `String` of JSON.
229    pub fn to_string_pretty(&self) -> Result<String, Error> {
230        serde_json::to_string_pretty(self)
231    }
232
233    /// Serialize as a generic JSON value.
234    pub fn to_value(&self) -> Result<Value, Error> {
235        serde_json::to_value(self)
236    }
237
238    /// Serialize as a JSON byte vector.
239    pub fn to_vec(&self) -> Result<Vec<u8>, Error> {
240        serde_json::to_vec(self)
241    }
242
243    /// Serialize as a pretty-printed JSON byte vector.
244    pub fn to_vec_pretty(&self) -> Result<Vec<u8>, Error> {
245        serde_json::to_vec_pretty(self)
246    }
247
248    /// Serialize as a JSON byte writertor.
249    pub fn to_writer<W>(&self, writer: W) -> Result<(), Error>
250    where
251        W: io::Write,
252    {
253        serde_json::to_writer(writer, self)
254    }
255
256    /// Serialize as a pretty-printed JSON byte writertor.
257    pub fn to_writer_pretty<W>(&self, writer: W) -> Result<(), Error>
258    where
259        W: io::Write,
260    {
261        serde_json::to_writer_pretty(writer, self)
262    }
263}
264
265impl<T> Index<T> {
266    /// Creates a new `Index` representing an offset into an array containing `T`.
267    pub fn new(value: u32) -> Self {
268        Index(value, std::marker::PhantomData)
269    }
270
271    /// Returns the internal offset value.
272    pub fn value(&self) -> usize {
273        self.0 as usize
274    }
275}
276
277impl<T> serde::Serialize for Index<T> {
278    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
279    where
280        S: ::serde::Serializer,
281    {
282        serializer.serialize_u64(self.value() as u64)
283    }
284}
285
286impl<'de, T> serde::Deserialize<'de> for Index<T> {
287    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
288    where
289        D: serde::Deserializer<'de>,
290    {
291        struct Visitor<T>(marker::PhantomData<T>);
292        impl<'de, T> serde::de::Visitor<'de> for Visitor<T> {
293            type Value = Index<T>;
294
295            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
296                formatter.write_str("index into child of root")
297            }
298
299            fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
300            where
301                E: serde::de::Error,
302            {
303                Ok(Index::new(value as u32))
304            }
305        }
306        deserializer.deserialize_u64(Visitor::<T>(marker::PhantomData))
307    }
308}
309
310impl<T> Clone for Index<T> {
311    fn clone(&self) -> Self {
312        *self
313    }
314}
315
316impl<T> Copy for Index<T> {}
317
318impl<T> Ord for Index<T> {
319    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
320        self.0.cmp(&other.0)
321    }
322}
323impl<T> PartialOrd for Index<T> {
324    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
325        Some(self.cmp(other))
326    }
327}
328
329impl<T> Eq for Index<T> {}
330impl<T> PartialEq for Index<T> {
331    fn eq(&self, other: &Self) -> bool {
332        self.0 == other.0
333    }
334}
335
336impl<T> std::hash::Hash for Index<T> {
337    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
338        self.0.hash(state);
339    }
340}
341
342impl<T> fmt::Debug for Index<T> {
343    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
344        write!(f, "{}", self.0)
345    }
346}
347
348impl<T> fmt::Display for Index<T> {
349    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
350        write!(f, "{}", self.0)
351    }
352}
353
354impl<T: Validate> Validate for Index<T>
355where
356    Root: Get<T>,
357{
358    fn validate<P, R>(&self, root: &Root, path: P, report: &mut R)
359    where
360        P: Fn() -> Path,
361        R: FnMut(&dyn Fn() -> Path, validation::Error),
362    {
363        if root.get(*self).is_none() {
364            report(&path, validation::Error::IndexOutOfBounds);
365        }
366    }
367}
368
369macro_rules! impl_get {
370    ($ty:ty, $field:ident) => {
371        impl<'a> Get<$ty> for Root {
372            fn get(&self, index: Index<$ty>) -> Option<&$ty> {
373                self.$field.get(index.value())
374            }
375        }
376        impl AsRef<[$ty]> for Root {
377            fn as_ref(&self) -> &[$ty] {
378                &self.$field
379            }
380        }
381        impl AsMut<Vec<$ty>> for Root {
382            fn as_mut(&mut self) -> &mut Vec<$ty> {
383                &mut self.$field
384            }
385        }
386    };
387}
388
389impl_get!(Accessor, accessors);
390impl_get!(Animation, animations);
391impl_get!(Buffer, buffers);
392impl_get!(buffer::View, buffer_views);
393impl_get!(Camera, cameras);
394impl_get!(Image, images);
395impl_get!(Material, materials);
396impl_get!(Mesh, meshes);
397impl_get!(Node, nodes);
398impl_get!(texture::Sampler, samplers);
399impl_get!(Scene, scenes);
400impl_get!(Skin, skins);
401impl_get!(Texture, textures);
402
403#[cfg(test)]
404mod tests {
405    use super::*;
406    use std::collections::HashSet;
407
408    #[test]
409    fn index_is_partialeq() {
410        assert_eq!(Index::<Node>::new(1), Index::new(1));
411        assert_ne!(Index::<Node>::new(1), Index::new(2));
412    }
413
414    #[test]
415    fn index_is_hash() {
416        let set = HashSet::from([Index::<Node>::new(1), Index::new(1234)]);
417        assert!(set.contains(&Index::new(1234)));
418        assert!(!set.contains(&Index::new(999)));
419        assert_eq!(set.len(), 2);
420    }
421
422    #[test]
423    fn index_is_ord() {
424        assert!(Index::<Node>::new(1) < Index::new(1234));
425    }
426
427    fn _index_is_send_sync()
428    where
429        Index<Material>: Send + Sync,
430    {
431    }
432
433    #[test]
434    fn index_push() {
435        let some_object = "hello";
436
437        let mut vec = Vec::new();
438        assert_eq!(Index::push(&mut vec, some_object), Index::new(0));
439        assert_eq!(Index::push(&mut vec, some_object), Index::new(1));
440    }
441
442    #[test]
443    fn root_push() {
444        let some_object = Buffer {
445            byte_length: validation::USize64(1),
446            #[cfg(feature = "names")]
447            name: None,
448            uri: None,
449            extensions: None,
450            extras: Default::default(),
451        };
452
453        let mut root = Root::default();
454        assert_eq!(root.push(some_object.clone()), Index::new(0));
455        assert_eq!(root.push(some_object), Index::new(1));
456    }
457
458    #[test]
459    fn root_extensions() {
460        use crate::validation::Error;
461        use crate::Path;
462
463        let mut root = super::Root {
464            extensions_required: vec!["KHR_lights_punctual".to_owned()],
465            ..Default::default()
466        };
467
468        let mut errors = Vec::new();
469        root.validate(&root, Path::new, &mut |path, error| {
470            errors.push((path(), error));
471        });
472
473        #[cfg(feature = "KHR_lights_punctual")]
474        {
475            assert!(errors.is_empty());
476        }
477
478        #[cfg(not(feature = "KHR_lights_punctual"))]
479        {
480            assert_eq!(1, errors.len());
481            let (path, error) = errors.get(0).unwrap();
482            assert_eq!(
483                path.as_str(),
484                "extensionsRequired[0] = \"KHR_lights_punctual\""
485            );
486            assert_eq!(*error, Error::Unsupported);
487        }
488
489        root.extensions_required = vec!["KHR_mesh_quantization".to_owned()];
490        errors.clear();
491        root.validate(&root, Path::new, &mut |path, error| {
492            errors.push((path(), error));
493        });
494        assert_eq!(1, errors.len());
495        let (path, error) = errors.get(0).unwrap();
496        assert_eq!(
497            path.as_str(),
498            "extensionsRequired[0] = \"KHR_mesh_quantization\""
499        );
500        assert_eq!(*error, Error::Unsupported);
501    }
502}