gltf_v1/
accessor.rs

1use json::accessor::{ComponentType, Type};
2
3use crate::{buffer::View, document::Document};
4
5/// A typed view into a buffer view.
6#[derive(Clone, Debug)]
7pub struct Accessor<'a> {
8    /// The parent `Document` struct.
9    #[allow(dead_code)]
10    document: &'a Document,
11
12    /// The corresponding JSON index.
13    index: &'a String,
14
15    /// The corresponding JSON struct.
16    json: &'a json::accessor::Accessor,
17
18    view: View<'a>,
19}
20
21impl<'a> Accessor<'a> {
22    pub(crate) fn new(
23        document: &'a Document,
24        index: &'a String,
25        json: &'a json::accessor::Accessor,
26    ) -> Self {
27        let view = document
28            .views()
29            .find(|x| x.index() == json.buffer_view.value())
30            .unwrap();
31        Self {
32            document,
33            index,
34            json,
35            view,
36        }
37    }
38    pub fn index(&self) -> &str {
39        self.index
40    }
41    pub fn name(&self) -> Option<&'a str> {
42        self.json.name.as_deref()
43    }
44    pub fn view(&self) -> &View<'a> {
45        &self.view
46    }
47    pub fn count(&self) -> usize {
48        self.json.count as usize
49    }
50    pub fn offset(&self) -> usize {
51        self.json.byte_offset as usize
52    }
53    pub fn stride(&self) -> Option<usize> {
54        self.json.byte_stride.map(|x| x as usize)
55    }
56    pub fn component_type(&self) -> ComponentType {
57        self.json.component_type.unwrap()
58    }
59    pub fn accessor_type(&self) -> Type {
60        self.json.type_.unwrap()
61    }
62}
63
64/// An `Iterator` that visits every accessor in a glTF asset.
65#[derive(Clone, Debug)]
66pub struct Accessors<'a> {
67    /// Internal accessor iterator.
68    pub(crate) iter: indexmap::map::Iter<'a, String, gltf_v1_json::Accessor>,
69
70    /// The internal root glTF object.
71    pub(crate) document: &'a Document,
72}
73
74impl ExactSizeIterator for Accessors<'_> {}
75impl<'a> Iterator for Accessors<'a> {
76    type Item = Accessor<'a>;
77
78    fn next(&mut self) -> Option<Self::Item> {
79        self.iter
80            .next()
81            .map(|(index, json)| Accessor::new(self.document, index, json))
82    }
83    fn size_hint(&self) -> (usize, Option<usize>) {
84        self.iter.size_hint()
85    }
86    fn count(self) -> usize {
87        self.iter.count()
88    }
89    fn last(self) -> Option<Self::Item> {
90        let document = self.document;
91        self.iter
92            .last()
93            .map(|(index, json)| Accessor::new(document, index, json))
94    }
95    fn nth(&mut self, n: usize) -> Option<Self::Item> {
96        self.iter
97            .nth(n)
98            .map(|(index, json)| Accessor::new(self.document, index, json))
99    }
100}