shine_gltf/
root.rs

1use crate::buffer;
2use crate::extensions;
3use crate::texture;
4use crate::validation;
5use serde;
6use serde_derive::{Deserialize, Serialize};
7use serde_json;
8use shine_gltf_macro::Validate;
9use std::{self, cmp, fmt, io, marker, str};
10
11use crate::path::Path;
12use crate::validation::Validate;
13use crate::{Accessor, Animation, Asset, Buffer, Camera, Error, Image, Material, Mesh, Node, Scene, Skin, Texture, Value};
14
15/// Helper trait for retrieving top-level objects by a universal identifier.
16pub trait Get<T> {
17    /// Retrieves a single value at the given index.
18    fn get(&self, id: &Index<T>) -> Option<&T>;
19}
20
21/// Helper trait for retrieving top-level objects by a universal identifier.
22pub trait GetMut<T> {
23    /// Retrieves a single value at the given index.
24    fn get_mut(&mut self, id: &Index<T>) -> Option<&mut T>;
25}
26
27/// Represents an offset into an array of type `T` owned by the root glTF object.
28#[derive(Clone, Copy, PartialOrd)]
29pub struct Index<T>(u32, marker::PhantomData<T>);
30
31/// The root object of a glTF 2.0 asset.
32#[derive(Clone, Debug, Default, Deserialize, Serialize, Validate)]
33pub struct Root {
34    /// An array of accessors.
35    #[serde(default)]
36    #[serde(skip_serializing_if = "Vec::is_empty")]
37    pub accessors: Vec<Accessor>,
38
39    /// An array of keyframe animations.
40    #[serde(default)]
41    #[serde(skip_serializing_if = "Vec::is_empty")]
42    pub animations: Vec<Animation>,
43
44    /// Metadata about the glTF asset.
45    pub asset: Asset,
46
47    /// An array of buffers.
48    #[serde(default)]
49    #[serde(skip_serializing_if = "Vec::is_empty")]
50    pub buffers: Vec<Buffer>,
51
52    /// An array of buffer views.
53    #[serde(default, rename = "bufferViews")]
54    #[serde(skip_serializing_if = "Vec::is_empty")]
55    pub buffer_views: Vec<buffer::View>,
56
57    /// The default scene.
58    #[serde(skip_serializing_if = "Option::is_none")]
59    pub scene: Option<Index<Scene>>,
60
61    /// Extension specific data.
62    #[serde(default, skip_serializing_if = "Option::is_none")]
63    pub extensions: Option<extensions::root::Root>,
64
65    /// Names of glTF extensions used somewhere in this asset.
66    #[serde(default, rename = "extensionsUsed")]
67    #[serde(skip_serializing_if = "Vec::is_empty")]
68    pub extensions_used: Vec<String>,
69
70    /// Names of glTF extensions required to properly load this asset.
71    #[serde(default, rename = "extensionsRequired")]
72    #[serde(skip_serializing_if = "Vec::is_empty")]
73    pub extensions_required: Vec<String>,
74
75    /// An array of cameras.
76    #[serde(default)]
77    #[serde(skip_serializing_if = "Vec::is_empty")]
78    pub cameras: Vec<Camera>,
79
80    /// An array of images.
81    #[serde(default)]
82    #[serde(skip_serializing_if = "Vec::is_empty")]
83    pub images: Vec<Image>,
84
85    /// An array of materials.
86    #[serde(default)]
87    #[serde(skip_serializing_if = "Vec::is_empty")]
88    pub materials: Vec<Material>,
89
90    /// An array of meshes.
91    #[serde(default)]
92    #[serde(skip_serializing_if = "Vec::is_empty")]
93    pub meshes: Vec<Mesh>,
94
95    /// An array of nodes.
96    #[serde(default)]
97    #[serde(skip_serializing_if = "Vec::is_empty")]
98    pub nodes: Vec<Node>,
99
100    /// An array of samplers.
101    #[serde(default)]
102    #[serde(skip_serializing_if = "Vec::is_empty")]
103    pub samplers: Vec<texture::Sampler>,
104
105    /// An array of scenes.
106    #[serde(default)]
107    #[serde(skip_serializing_if = "Vec::is_empty")]
108    pub scenes: Vec<Scene>,
109
110    /// An array of skins.
111    #[serde(default)]
112    #[serde(skip_serializing_if = "Vec::is_empty")]
113    pub skins: Vec<Skin>,
114
115    /// An array of textures.
116    #[serde(default)]
117    #[serde(skip_serializing_if = "Vec::is_empty")]
118    pub textures: Vec<Texture>,
119}
120
121impl Root {
122    /// Returns a single item from the root object.
123    pub fn get<T>(&self, index: &Index<T>) -> Option<&T>
124    where
125        Self: Get<T>,
126    {
127        (self as &dyn Get<T>).get(index)
128    }
129
130    /// Deserialize from a JSON byte slice.
131    pub fn from_slice(slice: &[u8]) -> Result<Self, Error> {
132        serde_json::from_slice(slice)
133    }
134
135    /// Deserialize from a stream of JSON.
136    pub fn from_reader<R>(reader: R) -> Result<Self, Error>
137    where
138        R: io::Read,
139    {
140        serde_json::from_reader(reader)
141    }
142
143    /// Serialize as a `String` of JSON.
144    pub fn to_string(&self) -> Result<String, Error> {
145        serde_json::to_string(self)
146    }
147
148    /// Serialize as a pretty-printed `String` of JSON.
149    pub fn to_string_pretty(&self) -> Result<String, Error> {
150        serde_json::to_string_pretty(self)
151    }
152
153    /// Serialize as a generic JSON value.
154    pub fn to_value(&self) -> Result<Value, Error> {
155        serde_json::to_value(self)
156    }
157
158    /// Serialize as a JSON byte vector.
159    pub fn to_vec(&self) -> Result<Vec<u8>, Error> {
160        serde_json::to_vec(self)
161    }
162
163    /// Serialize as a pretty-printed JSON byte vector.
164    pub fn to_vec_pretty(&self) -> Result<Vec<u8>, Error> {
165        serde_json::to_vec_pretty(self)
166    }
167
168    /// Serialize as a JSON byte writertor.
169    pub fn to_writer<W>(&self, writer: W) -> Result<(), Error>
170    where
171        W: io::Write,
172    {
173        serde_json::to_writer(writer, self)
174    }
175
176    /// Serialize as a pretty-printed JSON byte writertor.
177    pub fn to_writer_pretty<W>(&self, writer: W) -> Result<(), Error>
178    where
179        W: io::Write,
180    {
181        serde_json::to_writer_pretty(writer, self)
182    }
183}
184
185impl str::FromStr for Root {
186    type Err = Error;
187
188    /// Deserialize from a JSON string slice.
189    fn from_str(str_: &str) -> Result<Self, Self::Err> {
190        serde_json::from_str(str_)
191    }
192}
193
194impl<T> Index<T> {
195    /// Creates a new `Index` representing an offset into an array containing `T`.
196    pub fn new(value: u32) -> Self {
197        Index(value, std::marker::PhantomData)
198    }
199
200    /// Returns the internal offset value.
201    pub fn value(&self) -> usize {
202        self.0 as usize
203    }
204}
205
206impl<T> serde::Serialize for Index<T> {
207    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
208    where
209        S: ::serde::Serializer,
210    {
211        serializer.serialize_u64(self.value() as u64)
212    }
213}
214
215impl<'de, T> serde::Deserialize<'de> for Index<T> {
216    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
217    where
218        D: serde::Deserializer<'de>,
219    {
220        struct Visitor<T>(marker::PhantomData<T>);
221        impl<'de, T> serde::de::Visitor<'de> for Visitor<T> {
222            type Value = Index<T>;
223
224            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
225                formatter.write_str("index into child of root")
226            }
227
228            fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
229            where
230                E: serde::de::Error,
231            {
232                Ok(Index::new(value as u32))
233            }
234        }
235        deserializer.deserialize_u64(Visitor::<T>(marker::PhantomData))
236    }
237}
238
239impl<T> fmt::Debug for Index<T> {
240    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
241        write!(f, "{}", self.0)
242    }
243}
244
245impl<T> cmp::PartialEq for Index<T> {
246    fn eq(&self, other: &Index<T>) -> bool {
247        self.value() == other.value()
248    }
249}
250
251impl<T> fmt::Display for Index<T> {
252    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
253        write!(f, "{}", self.0)
254    }
255}
256
257impl<T: Validate> Validate for Index<T>
258where
259    Root: Get<T>,
260{
261    fn validate_minimally<P, R>(&self, root: &Root, path: P, report: &mut R)
262    where
263        P: Fn() -> Path,
264        R: FnMut(&dyn Fn() -> Path, validation::Error),
265    {
266        if root.get(self).is_none() {
267            report(&path, validation::Error::IndexOutOfBounds);
268        }
269    }
270}
271
272macro_rules! impl_get {
273    ($ty:ty, $field:ident) => {
274        impl<'a> Get<$ty> for Root {
275            fn get(&self, index: &Index<$ty>) -> Option<&$ty> {
276                self.$field.get(index.value())
277            }
278        }
279    };
280}
281
282impl_get!(Accessor, accessors);
283impl_get!(Animation, animations);
284impl_get!(Buffer, buffers);
285impl_get!(buffer::View, buffer_views);
286impl_get!(Camera, cameras);
287impl_get!(Image, images);
288impl_get!(Material, materials);
289impl_get!(Mesh, meshes);
290impl_get!(Node, nodes);
291impl_get!(texture::Sampler, samplers);
292impl_get!(Scene, scenes);
293impl_get!(Skin, skins);
294impl_get!(Texture, textures);
295
296macro_rules! impl_get_mut {
297    ($ty:ty, $field:ident) => {
298        impl<'a> GetMut<$ty> for Root {
299            fn get_mut(&mut self, index: &Index<$ty>) -> Option<&mut $ty> {
300                self.$field.get_mut(index.value())
301            }
302        }
303    };
304}
305
306impl_get_mut!(Accessor, accessors);
307impl_get_mut!(Animation, animations);
308impl_get_mut!(Buffer, buffers);
309impl_get_mut!(buffer::View, buffer_views);
310impl_get_mut!(Camera, cameras);
311impl_get_mut!(Image, images);
312impl_get_mut!(Material, materials);
313impl_get_mut!(Mesh, meshes);
314impl_get_mut!(Node, nodes);
315impl_get_mut!(texture::Sampler, samplers);
316impl_get_mut!(Scene, scenes);
317impl_get_mut!(Skin, skins);
318impl_get_mut!(Texture, textures);
319
320macro_rules! impl_add_vec {
321    ($ty:ty, $fn:ident, $field:ident) => {
322        impl Root {
323            pub fn $fn(&mut self, data: $ty) -> Index<$ty> {
324                let id = self.$field.len() as u32;
325                self.$field.push(data);
326                Index::new(id)
327            }
328        }
329    };
330}
331
332impl_add_vec!(Accessor, add_accessor, accessors);
333impl_add_vec!(Buffer, add_buffer, buffers);
334impl_add_vec!(buffer::View, add_buffer_view, buffer_views);
335impl_add_vec!(Node, add_node, nodes);
336impl_add_vec!(Mesh, add_mesh, meshes);
337impl_add_vec!(Scene, add_scene, scenes);