gltf_json/
accessor.rs

1use crate::validation::{Checked, Error, USize64};
2use crate::{buffer, extensions, Extras, Index, Path, Root};
3use gltf_derive::Validate;
4use serde::{de, ser};
5use serde_derive::{Deserialize, Serialize};
6use serde_json::Value;
7use std::fmt;
8
9/// The component data type.
10#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize)]
11pub enum ComponentType {
12    /// Corresponds to `GL_BYTE`.
13    I8 = 1,
14    /// Corresponds to `GL_UNSIGNED_BYTE`.
15    U8,
16    /// Corresponds to `GL_SHORT`.
17    I16,
18    /// Corresponds to `GL_UNSIGNED_SHORT`.
19    U16,
20    /// Corresponds to `GL_UNSIGNED_INT`.
21    U32,
22    /// Corresponds to `GL_FLOAT`.
23    F32,
24}
25
26/// Specifies whether an attribute, vector, or matrix.
27#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize)]
28pub enum Type {
29    /// Scalar quantity.
30    Scalar = 1,
31    /// 2D vector.
32    Vec2,
33    /// 3D vector.
34    Vec3,
35    /// 4D vector.
36    Vec4,
37    /// 2x2 matrix.
38    Mat2,
39    /// 3x3 matrix.
40    Mat3,
41    /// 4x4 matrix.
42    Mat4,
43}
44
45/// Corresponds to `GL_BYTE`.
46pub const BYTE: u32 = 5120;
47
48/// Corresponds to `GL_UNSIGNED_BYTE`.
49pub const UNSIGNED_BYTE: u32 = 5121;
50
51/// Corresponds to `GL_SHORT`.
52pub const SHORT: u32 = 5122;
53
54/// Corresponds to `GL_UNSIGNED_SHORT`.
55pub const UNSIGNED_SHORT: u32 = 5123;
56
57/// Corresponds to `GL_UNSIGNED_INT`.
58pub const UNSIGNED_INT: u32 = 5125;
59
60/// Corresponds to `GL_FLOAT`.
61pub const FLOAT: u32 = 5126;
62
63/// All valid generic vertex attribute component types.
64pub const VALID_COMPONENT_TYPES: &[u32] = &[
65    BYTE,
66    UNSIGNED_BYTE,
67    SHORT,
68    UNSIGNED_SHORT,
69    UNSIGNED_INT,
70    FLOAT,
71];
72
73/// All valid index component types.
74pub const VALID_INDEX_TYPES: &[u32] = &[UNSIGNED_BYTE, UNSIGNED_SHORT, UNSIGNED_INT];
75
76/// All valid accessor types.
77pub const VALID_ACCESSOR_TYPES: &[&str] =
78    &["SCALAR", "VEC2", "VEC3", "VEC4", "MAT2", "MAT3", "MAT4"];
79
80/// Contains data structures for sparse storage.
81pub mod sparse {
82    use super::*;
83    use crate::extensions;
84
85    /// Indices of those attributes that deviate from their initialization value.
86    #[derive(Clone, Debug, Deserialize, Serialize, Validate)]
87    pub struct Indices {
88        /// The parent buffer view containing the sparse indices.
89        ///
90        /// The referenced buffer view must not have `ARRAY_BUFFER` nor
91        /// `ELEMENT_ARRAY_BUFFER` as its target.
92        #[serde(rename = "bufferView")]
93        pub buffer_view: Index<buffer::View>,
94
95        /// The offset relative to the start of the parent `BufferView` in bytes.
96        #[serde(default, rename = "byteOffset")]
97        pub byte_offset: USize64,
98
99        /// The data type of each index.
100        #[serde(rename = "componentType")]
101        pub component_type: Checked<IndexComponentType>,
102
103        /// Extension specific data.
104        #[serde(default, skip_serializing_if = "Option::is_none")]
105        pub extensions: Option<extensions::accessor::sparse::Indices>,
106
107        /// Optional application specific data.
108        #[serde(default)]
109        #[cfg_attr(feature = "extras", serde(skip_serializing_if = "Option::is_none"))]
110        #[cfg_attr(not(feature = "extras"), serde(skip_serializing))]
111        pub extras: Extras,
112    }
113
114    /// Sparse storage of attributes that deviate from their initialization value.
115    #[derive(Clone, Debug, Deserialize, Serialize, Validate)]
116    pub struct Sparse {
117        /// The number of attributes encoded in this sparse accessor.
118        pub count: USize64,
119
120        /// Index array of size `count` that points to those accessor attributes
121        /// that deviate from their initialization value.
122        ///
123        /// Indices must strictly increase.
124        pub indices: Indices,
125
126        /// Array of size `count * number_of_components` storing the displaced
127        /// accessor attributes pointed by `indices`.
128        ///
129        /// Substituted values must have the same `component_type` and number of
130        /// components as the base `Accessor`.
131        pub values: Values,
132
133        /// Extension specific data.
134        #[serde(default, skip_serializing_if = "Option::is_none")]
135        pub extensions: Option<extensions::accessor::sparse::Sparse>,
136
137        /// Optional application specific data.
138        #[serde(default)]
139        #[cfg_attr(feature = "extras", serde(skip_serializing_if = "Option::is_none"))]
140        #[cfg_attr(not(feature = "extras"), serde(skip_serializing))]
141        pub extras: Extras,
142    }
143
144    /// Array of size `count * number_of_components` storing the displaced
145    /// accessor attributes pointed by `accessor::sparse::Indices`.
146    #[derive(Clone, Debug, Deserialize, Serialize, Validate)]
147    pub struct Values {
148        /// The parent buffer view containing the sparse indices.
149        ///
150        /// The referenced buffer view must not have `ARRAY_BUFFER` nor
151        /// `ELEMENT_ARRAY_BUFFER` as its target.
152        #[serde(rename = "bufferView")]
153        pub buffer_view: Index<buffer::View>,
154
155        /// The offset relative to the start of the parent buffer view in bytes.
156        #[serde(default, rename = "byteOffset")]
157        pub byte_offset: USize64,
158
159        /// Extension specific data.
160        #[serde(default, skip_serializing_if = "Option::is_none")]
161        pub extensions: Option<extensions::accessor::sparse::Values>,
162
163        /// Optional application specific data.
164        #[serde(default)]
165        #[cfg_attr(feature = "extras", serde(skip_serializing_if = "Option::is_none"))]
166        #[cfg_attr(not(feature = "extras"), serde(skip_serializing))]
167        pub extras: Extras,
168    }
169}
170
171/// A typed view into a buffer view.
172#[derive(Clone, Debug, Deserialize, Serialize, Validate)]
173#[gltf(validate_hook = "accessor_validate_hook")]
174pub struct Accessor {
175    /// The parent buffer view this accessor reads from.
176    ///
177    /// This field can be omitted in sparse accessors.
178    #[serde(rename = "bufferView")]
179    #[serde(skip_serializing_if = "Option::is_none")]
180    pub buffer_view: Option<Index<buffer::View>>,
181
182    /// The offset relative to the start of the parent `BufferView` in bytes.
183    ///
184    /// This field can be omitted in sparse accessors.
185    #[serde(default, rename = "byteOffset")]
186    #[serde(skip_serializing_if = "Option::is_none")]
187    pub byte_offset: Option<USize64>,
188
189    /// The number of components within the buffer view - not to be confused
190    /// with the number of bytes in the buffer view.
191    pub count: USize64,
192
193    /// The data type of components in the attribute.
194    #[serde(rename = "componentType")]
195    pub component_type: Checked<GenericComponentType>,
196
197    /// Extension specific data.
198    #[serde(default, skip_serializing_if = "Option::is_none")]
199    pub extensions: Option<extensions::accessor::Accessor>,
200
201    /// Optional application specific data.
202    #[serde(default)]
203    #[cfg_attr(feature = "extras", serde(skip_serializing_if = "Option::is_none"))]
204    #[cfg_attr(not(feature = "extras"), serde(skip_serializing))]
205    pub extras: Extras,
206
207    /// Specifies if the attribute is a scalar, vector, or matrix.
208    #[serde(rename = "type")]
209    pub type_: Checked<Type>,
210
211    /// Minimum value of each component in this attribute.
212    #[serde(default, skip_serializing_if = "Option::is_none")]
213    pub min: Option<Value>,
214
215    /// Maximum value of each component in this attribute.
216    #[serde(default, skip_serializing_if = "Option::is_none")]
217    pub max: Option<Value>,
218
219    /// Optional user-defined name for this object.
220    #[cfg(feature = "names")]
221    #[cfg_attr(feature = "names", serde(skip_serializing_if = "Option::is_none"))]
222    pub name: Option<String>,
223
224    /// Specifies whether integer data values should be normalized.
225    #[serde(default, skip_serializing_if = "is_normalized_default")]
226    pub normalized: bool,
227
228    /// Sparse storage of attributes that deviate from their initialization
229    /// value.
230    #[serde(default)]
231    #[serde(skip_serializing_if = "Option::is_none")]
232    pub sparse: Option<sparse::Sparse>,
233}
234
235fn accessor_validate_hook<P, R>(accessor: &Accessor, _root: &Root, path: P, report: &mut R)
236where
237    P: Fn() -> Path,
238    R: FnMut(&dyn Fn() -> Path, Error),
239{
240    if accessor.sparse.is_none() && accessor.buffer_view.is_none() {
241        // If sparse is missing, then bufferView must be present. Report that bufferView is
242        // missing since it is the more common one to require.
243        report(&|| path().field("bufferView"), Error::Missing);
244    }
245}
246
247// Help serde avoid serializing this glTF 2.0 default value.
248fn is_normalized_default(b: &bool) -> bool {
249    !*b
250}
251
252/// The data type of an index.
253#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
254pub struct IndexComponentType(pub ComponentType);
255
256/// The data type of a generic vertex attribute.
257#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
258pub struct GenericComponentType(pub ComponentType);
259
260impl<'de> de::Deserialize<'de> for Checked<GenericComponentType> {
261    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
262    where
263        D: de::Deserializer<'de>,
264    {
265        struct Visitor;
266        impl<'de> de::Visitor<'de> for Visitor {
267            type Value = Checked<GenericComponentType>;
268
269            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
270                write!(f, "any of: {:?}", VALID_COMPONENT_TYPES)
271            }
272
273            fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
274            where
275                E: de::Error,
276            {
277                use self::ComponentType::*;
278                use crate::validation::Checked::*;
279                Ok(match value as u32 {
280                    BYTE => Valid(GenericComponentType(I8)),
281                    UNSIGNED_BYTE => Valid(GenericComponentType(U8)),
282                    SHORT => Valid(GenericComponentType(I16)),
283                    UNSIGNED_SHORT => Valid(GenericComponentType(U16)),
284                    UNSIGNED_INT => Valid(GenericComponentType(U32)),
285                    FLOAT => Valid(GenericComponentType(F32)),
286                    _ => Invalid,
287                })
288            }
289        }
290        deserializer.deserialize_u64(Visitor)
291    }
292}
293
294impl<'de> de::Deserialize<'de> for Checked<IndexComponentType> {
295    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
296    where
297        D: de::Deserializer<'de>,
298    {
299        struct Visitor;
300        impl<'de> de::Visitor<'de> for Visitor {
301            type Value = Checked<IndexComponentType>;
302
303            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
304                write!(f, "any of: {:?}", VALID_INDEX_TYPES)
305            }
306
307            fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
308            where
309                E: de::Error,
310            {
311                use self::ComponentType::*;
312                use crate::validation::Checked::*;
313                Ok(match value as u32 {
314                    UNSIGNED_BYTE => Valid(IndexComponentType(U8)),
315                    UNSIGNED_SHORT => Valid(IndexComponentType(U16)),
316                    UNSIGNED_INT => Valid(IndexComponentType(U32)),
317                    _ => Invalid,
318                })
319            }
320        }
321        deserializer.deserialize_u64(Visitor)
322    }
323}
324
325impl<'de> de::Deserialize<'de> for Checked<Type> {
326    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
327    where
328        D: de::Deserializer<'de>,
329    {
330        struct Visitor;
331        impl<'de> de::Visitor<'de> for Visitor {
332            type Value = Checked<Type>;
333
334            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
335                write!(f, "any of: {:?}", VALID_ACCESSOR_TYPES)
336            }
337
338            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
339            where
340                E: de::Error,
341            {
342                use self::Type::*;
343                use crate::validation::Checked::*;
344                Ok(match value {
345                    "SCALAR" => Valid(Scalar),
346                    "VEC2" => Valid(Vec2),
347                    "VEC3" => Valid(Vec3),
348                    "VEC4" => Valid(Vec4),
349                    "MAT2" => Valid(Mat2),
350                    "MAT3" => Valid(Mat3),
351                    "MAT4" => Valid(Mat4),
352                    _ => Invalid,
353                })
354            }
355        }
356        deserializer.deserialize_str(Visitor)
357    }
358}
359
360impl ser::Serialize for Type {
361    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
362    where
363        S: ser::Serializer,
364    {
365        serializer.serialize_str(match *self {
366            Type::Scalar => "SCALAR",
367            Type::Vec2 => "VEC2",
368            Type::Vec3 => "VEC3",
369            Type::Vec4 => "VEC4",
370            Type::Mat2 => "MAT2",
371            Type::Mat3 => "MAT3",
372            Type::Mat4 => "MAT4",
373        })
374    }
375}
376
377impl ComponentType {
378    /// Returns the number of bytes this value represents.
379    pub fn size(&self) -> usize {
380        use self::ComponentType::*;
381        match *self {
382            I8 | U8 => 1,
383            I16 | U16 => 2,
384            F32 | U32 => 4,
385        }
386    }
387
388    /// Returns the corresponding `GLenum`.
389    pub fn as_gl_enum(self) -> u32 {
390        match self {
391            ComponentType::I8 => BYTE,
392            ComponentType::U8 => UNSIGNED_BYTE,
393            ComponentType::I16 => SHORT,
394            ComponentType::U16 => UNSIGNED_SHORT,
395            ComponentType::U32 => UNSIGNED_INT,
396            ComponentType::F32 => FLOAT,
397        }
398    }
399}
400
401impl ser::Serialize for ComponentType {
402    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
403    where
404        S: ser::Serializer,
405    {
406        serializer.serialize_u32(self.as_gl_enum())
407    }
408}
409
410impl Type {
411    /// Returns the equivalent number of scalar quantities this type represents.
412    pub fn multiplicity(&self) -> usize {
413        use self::Type::*;
414        match *self {
415            Scalar => 1,
416            Vec2 => 2,
417            Vec3 => 3,
418            Vec4 | Mat2 => 4,
419            Mat3 => 9,
420            Mat4 => 16,
421        }
422    }
423}