Skip to main content

three_rs/loaders/
buffer_geometry_loader.rs

1//! Port of `three.js/src/loaders/BufferGeometryLoader.js`: `data.index`,
2//! `data.attributes` and `data.morphAttributes` (plain, instanced and
3//! interleaved, of any typed-array kind but `Float64Array`), and
4//! `data.morphTargetsRelative`. Not ported: `groups`, `boundingSphere`,
5//! `name`, `userData`, `usage`, `gpuType`, `isInstancedBufferGeometry`.
6//!
7//! `load()` reads from the filesystem instead of the examples web server; the
8//! JSON it parses is byte-identical to what the page fetches.
9
10use std::collections::HashMap;
11use std::path::Path;
12use std::rc::Rc;
13
14use crate::core::{
15    ArrayKind, BufferAttribute, BufferGeometry, Index, InterleavedBuffer, TypedArray,
16};
17use crate::error::Error;
18
19/// three.js' `BufferGeometryLoader`.
20pub struct BufferGeometryLoader;
21
22impl Default for BufferGeometryLoader {
23    fn default() -> Self {
24        Self::new()
25    }
26}
27
28impl BufferGeometryLoader {
29    /// A loader with no state — `new BufferGeometryLoader()`.
30    pub fn new() -> Self {
31        Self
32    }
33
34    /// `loader.load( url, onLoad )` — synchronous here, since the harness
35    /// renders a single frame once loading has settled.
36    pub fn load(&self, path: impl AsRef<Path>) -> Result<BufferGeometry, Error> {
37        let path = path.as_ref();
38        let text = crate::io::read_to_string(path)?;
39        let json: serde_json::Value =
40            serde_json::from_str(&text).map_err(|source| Error::Json {
41                path: Some(path.to_path_buf()),
42                source,
43            })?;
44        self.parse(&json)
45    }
46
47    /// `BufferGeometryLoader.parse( json )`.
48    pub fn parse(&self, json: &serde_json::Value) -> Result<BufferGeometry, Error> {
49        let mut geometry = BufferGeometry::new();
50
51        let data = &json["data"];
52
53        if let Some(index) = data.get("index") {
54            let array = number_array(&index["array"])?;
55            geometry.set_index_attribute(match index["type"].as_str() {
56                Some("Uint16Array") => Index::U16(array.iter().map(|&v| v as u16).collect()),
57                Some("Uint32Array") => Index::U32(array.iter().map(|&v| v as u32).collect()),
58                other => {
59                    return Err(Error::UnsupportedFormat {
60                        what: "index type",
61                        value: format!("{other:?}"),
62                    })
63                }
64            });
65        }
66
67        let mut interleaved = HashMap::new();
68
69        if let Some(attributes) = data.get("attributes").and_then(|a| a.as_object()) {
70            for (key, attribute) in attributes {
71                let buffer_attribute = parse_attribute(data, attribute, &mut interleaved)?;
72                geometry.set_attribute(key, buffer_attribute);
73            }
74        }
75
76        if let Some(morph_attributes) = data.get("morphAttributes").and_then(|a| a.as_object()) {
77            for (key, attribute_array) in morph_attributes {
78                let array = attribute_array
79                    .as_array()
80                    .ok_or_else(|| Error::UnsupportedFormat {
81                        what: "morphAttributes entry",
82                        value: attribute_array.to_string(),
83                    })?
84                    .iter()
85                    .map(|attribute| parse_attribute(data, attribute, &mut interleaved))
86                    .collect::<Result<Vec<_>, _>>()?;
87                geometry.set_morph_attribute(key, array);
88            }
89        }
90
91        if data["morphTargetsRelative"].as_bool() == Some(true) {
92            geometry.morph_targets_relative = true;
93        }
94
95        Ok(geometry)
96    }
97}
98
99/// One entry of `data.attributes` or `data.morphAttributes`: an
100/// `InterleavedBufferAttribute` over a shared [`InterleavedBuffer`], or an
101/// (instanced) `BufferAttribute` over `getTypedArray( type, array )`.
102fn parse_attribute(
103    data: &serde_json::Value,
104    attribute: &serde_json::Value,
105    interleaved: &mut HashMap<String, Rc<InterleavedBuffer>>,
106) -> Result<BufferAttribute, Error> {
107    let item_size = usize_field(attribute, "itemSize")?;
108    let normalized = attribute["normalized"].as_bool().unwrap_or(false);
109
110    if attribute["isInterleavedBufferAttribute"].as_bool() == Some(true) {
111        let uuid = string_field(attribute, "data")?;
112        let buffer = interleaved_buffer(data, uuid, interleaved)?;
113        let offset = usize_field(attribute, "offset")?;
114        return Ok(BufferAttribute::interleaved(
115            buffer, item_size, offset, normalized,
116        ));
117    }
118
119    // `getTypedArray( type, array )`: each JSON number stored the way the
120    // typed array's constructor stores it.
121    let kind = array_kind(&attribute["type"])?;
122    let array = TypedArray::from_f64(kind, &number_array(&attribute["array"])?);
123    Ok(
124        if attribute["isInstancedBufferAttribute"].as_bool() == Some(true) {
125            BufferAttribute::from_typed_instanced(array, item_size, normalized)
126        } else {
127            BufferAttribute::from_typed(array, item_size, normalized)
128        },
129    )
130}
131
132/// `getInterleavedBuffer( json, uuid )`: `data.interleavedBuffers[ uuid ]`,
133/// a typed view of `data.arrayBuffers[ buffer ]` (stored as `Uint32Array`
134/// words) with a stride, built once per uuid so every view shares it.
135///
136/// three also caches the `ArrayBuffer`, so two interleaved buffers over one
137/// array buffer alias each other's memory; here each gets its own copy.
138fn interleaved_buffer(
139    data: &serde_json::Value,
140    uuid: &str,
141    interleaved: &mut HashMap<String, Rc<InterleavedBuffer>>,
142) -> Result<Rc<InterleavedBuffer>, Error> {
143    if let Some(buffer) = interleaved.get(uuid) {
144        return Ok(buffer.clone());
145    }
146    let json = &data["interleavedBuffers"][uuid];
147    if json.is_null() {
148        return Err(Error::UnsupportedFormat {
149            what: "interleavedBuffers uuid",
150            value: uuid.to_string(),
151        });
152    }
153    let array_buffer = &data["arrayBuffers"][string_field(json, "buffer")?];
154    // `new Uint32Array( arrayBuffer ).buffer`.
155    let TypedArray::U32(words) = TypedArray::from_f64(ArrayKind::U32, &number_array(array_buffer)?)
156    else {
157        unreachable!("from_f64(U32) is a Uint32Array")
158    };
159    let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
160    let array = TypedArray::from_le_bytes(array_kind(&json["type"])?, &bytes);
161    let buffer = Rc::new(InterleavedBuffer::new(array, usize_field(json, "stride")?));
162    interleaved.insert(uuid.to_string(), buffer.clone());
163    Ok(buffer)
164}
165
166/// `TYPED_ARRAYS[ type ]` from three's `utils.js`, less `Float64Array`,
167/// which no attribute kind holds.
168fn array_kind(value: &serde_json::Value) -> Result<ArrayKind, Error> {
169    Ok(match value.as_str() {
170        Some("Float32Array") => ArrayKind::F32,
171        Some("Int8Array") => ArrayKind::I8,
172        Some("Uint8Array") => ArrayKind::U8,
173        Some("Uint8ClampedArray") => ArrayKind::U8Clamped,
174        Some("Int16Array") => ArrayKind::I16,
175        Some("Uint16Array") => ArrayKind::U16,
176        Some("Int32Array") => ArrayKind::I32,
177        Some("Uint32Array") => ArrayKind::U32,
178        _ => {
179            return Err(Error::UnsupportedFormat {
180                what: "attribute type",
181                value: value.to_string(),
182            })
183        }
184    })
185}
186
187fn usize_field(json: &serde_json::Value, what: &'static str) -> Result<usize, Error> {
188    json[what]
189        .as_u64()
190        .map(|v| v as usize)
191        .ok_or_else(|| Error::UnsupportedFormat {
192            what,
193            value: json[what].to_string(),
194        })
195}
196
197fn string_field<'a>(json: &'a serde_json::Value, what: &'static str) -> Result<&'a str, Error> {
198    json[what].as_str().ok_or_else(|| Error::UnsupportedFormat {
199        what,
200        value: json[what].to_string(),
201    })
202}
203
204fn number_array(value: &serde_json::Value) -> Result<Vec<f64>, Error> {
205    value
206        .as_array()
207        .ok_or_else(|| Error::UnsupportedFormat {
208            what: "attribute array",
209            value: value.to_string(),
210        })?
211        .iter()
212        .map(|v| {
213            v.as_f64().ok_or_else(|| Error::UnsupportedFormat {
214                what: "attribute value",
215                value: v.to_string(),
216            })
217        })
218        .collect()
219}