Skip to main content

three_rs/core/
buffer_attribute.rs

1//! `BufferAttribute`, `InterleavedBuffer` and `InterleavedBufferAttribute` —
2//! `src/core/BufferAttribute.js`, `InterleavedBuffer.js`,
3//! `InterleavedBufferAttribute.js` (three r187), plus the attribute half of
4//! `StorageBufferAttribute.js`.
5//!
6//! # Design (issue #294)
7//!
8//! Until this module the port held every attribute as `Vec<f32>` with one
9//! `integer` flag for `skinIndex`, uploaded as `Float32xN` or `Uint32x4`, and
10//! kept the only interleaved data (Line2's `InstancedInterleavedBuffer`) as a
11//! node-side special case. The decisions below replace that; each is the shape
12//! the port takes and why, so the porter and the next reader do not re-derive
13//! them.
14//!
15//! ## 1. One struct, a typed value enum inside — not a generic
16//!
17//! [`BufferAttribute`] stays a single type. Its storage is a [`TypedArray`]
18//! enum with one variant per JavaScript array three uses on an attribute:
19//! `F32(Vec<f32>)`, `F16(Vec<u16>)` (IEEE binary16 bits, converted with
20//! [`crate::extras::from_half_float`] / [`crate::extras::to_half_float`],
21//! three's `DataUtils`), `I8`, `U8`, `U8Clamped`, `I16`, `U16`, `I32`, `U32`.
22//! `normalized` is a field beside it, as in three.
23//!
24//! Why not `BufferAttribute<T: Element>`: `BufferGeometry` stores attributes
25//! heterogeneously and `get_attribute(name)` returns one by name, so the store
26//! needs type erasure anyway, and an erased wrapper over a generic is the enum
27//! with a second type surface on top. The enum also keeps `set_attribute`,
28//! `get_attribute` and the 120-odd `BufferAttribute::new(Vec<f32>, n)` call
29//! sites compiling unchanged: `new` is `Float32BufferAttribute`, three's
30//! default. The typed constructors mirror three's class names as functions:
31//! `BufferAttribute::uint8(array, item_size, normalized)` is
32//! `new Uint8BufferAttribute( array, itemSize, normalized )`, and so on for
33//! `int8`, `uint8_clamped`, `int16`, `uint16`, `int32`, `uint32`, `float16`;
34//! `BufferAttribute::from_typed(TypedArray, item_size, normalized)` is the
35//! base constructor.
36//!
37//! ## 2. Reading: `array()` is the `Float32Array` view, `data()` the typed one
38//!
39//! `array()` / `array_mut()` keep returning `Ref<Vec<f32>>` / `RefMut<Vec<f32>>`
40//! and are the fast path every geometry algorithm uses. On an attribute whose
41//! storage is not `F32` they **panic** naming `data()`, the same way code that
42//! assumes `attribute.array` is a `Float32Array` breaks in three when handed a
43//! `Uint8Array`. `data()` / `data_mut()` return the [`TypedArray`] itself.
44//! `get_x..get_w` and `set_x..set_xyzw` work on every variant: a read widens to
45//! `f64` and, when `normalized`, applies `MathUtils.denormalize` for the
46//! variant's range; a write applies `MathUtils.normalize` then narrows, with
47//! `U8Clamped` clamping instead of wrapping. `count()` is `len / item_size` in
48//! elements, whatever the element width.
49//!
50//! The `integer` flag and `new_integer` go: `skinIndex` becomes
51//! `BufferAttribute::uint32` (a glTF `JOINTS_0` is `Uint8`/`Uint16`
52//! non-normalized, which three widens to `Uint32` on upload — decision 3 — so
53//! the GPU sees the same bytes either way).
54//!
55//! ## 3. `normalized` → `wgpu::VertexFormat`: three's table, including its padding
56//!
57//! The format is `WebGPUAttributeUtils._getVertexFormat()` after
58//! `createAttribute()` has had its way with the array, in this order:
59//!
60//! * `F32` → `Float32xN`; `I32`/`U32` → `Sint32xN`/`Uint32xN`, `N` 1..4. At
61//!   `itemSize === 1` three's map ignores `normalized`, so a normalized
62//!   `Int32Array`/`Uint32Array` of item size 1 is `sint32`/`uint32` while
63//!   `getTypeFromAttribute()` declares it `f32` (decision 4) — a pairing
64//!   WebGPU rejects at pipeline creation. The port reproduces both halves.
65//! * `F16` → `Float16xN` with `N` padded to 2 or 4 (a 16-bit stride must be a
66//!   multiple of 4 bytes), and never widened. This is a deliberate
67//!   divergence: three stores a `Float16BufferAttribute` in a `Uint16Array`,
68//!   so a non-normalized, non-interleaved one goes through the widening below
69//!   into a `Uint32Array`, and `_getVertexFormat` then pairs the `float16`
70//!   prefix (picked by attribute class) with a 4-byte element and asks for
71//!   `float16x3` for item size 3 — not a WebGPU format. The port keeps the
72//!   binary16 bits and pads, which is what the class asks for.
73//!   `itemSize === 1` has no `Float16` entry in three's item-size-1 map and
74//!   errors.
75//! * Every row three has no format for — `F16` at item size 1, a normalized
76//!   32-bit array above item size 1, the 8- and 16-bit item-size-1 rows
77//!   below — panics in [`ArrayKind::vertex_format`] with three's message.
78//!   That is a deliberate divergence too: three only logs `error(
79//!   'WebGPUAttributeUtils: Vertex format not supported yet.' )` and returns
80//!   `undefined`, and the draw then fails as a WebGPU validation error on the
81//!   pipeline, away from the attribute that caused it. Failing at the table
82//!   names the array kind, item size and flags.
83//! * 8- and 16-bit **non-normalized, non-interleaved**: `createAttribute()`
84//!   rebuilds the array as `Int32Array`/`Uint32Array` and assigns it back, so
85//!   `_getVertexFormat` then sees a 32-bit array → `Sint32xN`/`Uint32xN`. The
86//!   port widens at upload only; the CPU array keeps its type (three's
87//!   `bufferAttribute.array = array` side effect is not reproduced, and
88//!   `array()`/`get_x()` stay consistent with what the caller built).
89//! * 8- and 16-bit **normalized**: `Snorm8xN`/`Unorm8xN`/`Snorm16xN`/`Unorm16xN`
90//!   with `N` padded so the byte stride is a multiple of 4 — `N = 3` becomes 4
91//!   for both widths, `N = 1` is an error for 8-bit (no item-size-1 entry) and
92//!   for 16-bit. The padding is applied to the uploaded bytes too, element by
93//!   element, exactly as `createAttribute()`'s `paddedArray` loop does, and to
94//!   the `arrayStride` (`createShaderVertexBuffers()` rounds it up).
95//! * 8- and 16-bit **interleaved** (`isInterleavedBufferAttribute`): no
96//!   widening; the format comes straight from the array type — `Uint8xN`,
97//!   `Sint16xN`, their normalized forms — `N` padded as above; `arrayStride` is
98//!   `data.stride * bytes_per_element`, the attribute's `offset` is
99//!   `offset * bytes_per_element`.
100//!
101//! The table lives in one function, [`TypedArray::vertex_format`] (array kind,
102//! item size, normalized, interleaved) → `(wgpu::VertexFormat, padded_item_size)`,
103//! and is the thing the unit test checks row by row.
104//!
105//! ## 4. The shader type comes from the attribute, not from the node
106//!
107//! `NodeBuilder.getTypeFromAttribute()`: `normalized` or `F16` → `float`/`vecN`;
108//! otherwise `I*` → `int`/`ivecN`, `U*` → `uint`/`uvecN`, `F32` → `float`/`vecN`.
109//! `AttributeNode.generate()` declares the slot in **that** type and casts to
110//! the node's own type with `builder.format()`. Today the port's
111//! `Node::Attribute { name, ty }` declares the slot in `ty`. To do what three
112//! does the builder has to know the geometry's attributes, so
113//! `SetupContext` grows `geometry_attributes: Vec<AttributeDesc>` — one entry
114//! per `geometry.attributes` in insertion order with `name`, element kind,
115//! `item_size`, `normalized`, step mode, and for an interleaved attribute a
116//! geometry-local group index (the position of the first view of the same
117//! buffer, so two geometries laid out alike share a program), stride and
118//! offset. It is hashed into the program cache key
119//! (as `instanced_attributes` is now, which it replaces: "instanced" is a bit
120//! on the descriptor). `vertex_color_size` and `has_tangent_attribute` could
121//! be derived from it; leave them alone in this PR, the diff is wide enough.
122//!
123//! `NodeProgram::vertex_buffers()` builds one `VertexBufferDesc` per geometry
124//! attribute buffer: non-interleaved attributes one buffer each, interleaved
125//! attributes sharing an `InterleavedBuffer` one buffer with several entries —
126//! the grouping it already does for `InstanceBuffer`, keyed on that group
127//! index (the renderer keys the GPU buffer itself on the interleaved buffer's
128//! id, decision 5). `programs::vertex_format(Type)`
129//! goes; the format rides on the slot from the descriptor.
130//!
131//! ## 5. An interleaved buffer is one GPU buffer; its attributes are views
132//!
133//! [`InterleavedBuffer`] owns `RefCell<TypedArray>`, `stride`, a `version`
134//! (`needsUpdate`) and an id from the attribute counter; `new_instanced(array,
135//! stride, mesh_per_attribute)` is `InstancedInterleavedBuffer`. It is shared
136//! as `Rc<InterleavedBuffer>`. A [`BufferAttribute`] is either its own
137//! storage or a view: `BufferAttribute::interleaved(Rc<InterleavedBuffer>,
138//! item_size, offset, normalized)` is `new InterleavedBufferAttribute( data,
139//! itemSize, offset, normalized )`; `is_interleaved()` and `data_buffer()`
140//! expose the view. The getters/setters index `offset + index * stride`.
141//! `array()` on an interleaved `F32` view returns the **whole** shared array,
142//! as three's `InterleavedBufferAttribute.array` getter does.
143//!
144//! The renderer keys the GPU buffer on the `InterleavedBuffer`'s id, three's
145//! `backend.get( attribute.data )`, so two views upload once and share a
146//! vertex-buffer slot, and `InterleavedBuffer::set_needs_update` refreshes it.
147//! `GeometryGpu` drops the position/normal/uv/other split and the three-entry
148//! version array for one list of `(buffer key, wgpu::Buffer, version)` where
149//! the key is an attribute id or an interleaved buffer id — which also makes
150//! every attribute refreshable on `set_needs_update`, not just the first
151//! three (a limit `refresh_geometry` documents today).
152//!
153//! `LineSegmentsGeometry` is the first consumer: `set_positions` builds an
154//! `InterleavedBuffer::new_instanced(array, 6, 1)` and sets `instanceStart`
155//! and `instanceEnd` as interleaved views at offsets 0 and 3 on the geometry,
156//! as `LineSegmentsGeometry.js` does; `set_colors` likewise builds
157//! `instanceColorStart` / `instanceColorEnd`. The dash distances
158//! (`computeLineDistances()`'s `instanceDistanceStart` / `instanceDistanceEnd`)
159//! are not ported, with the rest of `_useDash`.
160//! `Line2NodeMaterial` then reads them with plain `attribute("instanceStart")`
161//! and `SetupContext::line_segments`, `nodes::lines::LineSegmentsAttributes`
162//! and the Line2 use of `Node::InstancedAttribute` go. `instance_count` on the
163//! geometry is the interleaved buffer's `count` — `array.len() / stride` — set
164//! by the geometry as three does. The WGSL must stay byte-identical to the
165//! `webgpu_lines_fat` fixtures: same one `stepMode: 'instance'` buffer of
166//! stride 24, two entries at offsets 0 and 12. `InstancedMesh`'s
167//! `instanceMatrix` (`InstancedInterleavedBuffer( array, 16, 1 )` in three) is
168//! the natural second consumer and stays on `InstanceBuffer` in this PR.
169//!
170//! ## 6. `StorageBufferAttribute` names a `StorageArray`'s buffer
171//!
172//! Node-side `StorageArray` (`instancedArray` / `attributeArray`) already owns
173//! a `BufferId` the renderer keys the GPU buffer on. [`StorageBufferAttribute`]
174//! is the attribute-side handle to the same id: `StorageBufferAttribute::new(
175//! count_or_array, item_size, TypedArray kind )` mints a `BufferId` and holds
176//! the initial contents; `storage(&attribute, ty, count)` builds a
177//! `StorageArray` over **that** id (`BufferSource::StorageData` with the
178//! attribute's bytes as `init`), and `attribute.to_attribute()` /
179//! `geometry.set_attribute(name, attribute.into())` reads it as a vertex
180//! buffer with `stepMode: 'vertex'`, or `'instance'` for
181//! `StorageInstancedBufferAttribute` (`new_instanced`). A kernel writing the
182//! storage view and a draw reading the attribute view meet on one buffer, as
183//! `IndirectStorageBufferAttribute` already arranges for indirect args. The
184//! renderer looks a `BufferAttribute` whose backing is `Storage(id)` up in its
185//! storage-buffer map rather than uploading it. `createAttribute()` treats
186//! the storage array as any other first — a non-normalized 8- or 16-bit
187//! integer array is widened to 32 bits — and then pads `itemSize === 3` to a
188//! `vec4` stride; the attribute view of the buffer uses that widened, padded
189//! stride, and a `storage()` node over it reads the same 32-bit words.
190//!
191//! ## Not in this PR
192//!
193//! TSL `bufferAttribute()` / `dynamicBufferAttribute()` (a `BufferAttributeNode`
194//! over an attribute not on the geometry), `usage`/`updateRanges`,
195//! `onUpload`, `toJSON`, and `InstancedMesh` on an interleaved buffer. Each is a
196//! follow-on with this module as its base.
197
198use std::cell::{Cell, Ref, RefCell, RefMut};
199use std::collections::HashMap;
200use std::rc::Rc;
201
202use crate::extras::{from_half_float, to_half_float};
203use crate::math::{Matrix3, Matrix4, Vector3};
204use crate::nodes::node::BufferId;
205use crate::nodes::Type;
206
207/// `BufferAttribute.id` — three.js' `_id ++` on the attribute class. The same
208/// never-reused counter shape as [`GeometryId`](super::GeometryId), for the
209/// same reason.
210///
211/// The renderer keys a geometry's vertex buffers on this (or, for an
212/// interleaved attribute, on its [`InterleavedBuffer::id`], which comes from
213/// the same counter so the two can never collide).
214#[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
215pub struct AttributeId(usize);
216
217impl AttributeId {
218    pub(crate) fn next() -> Self {
219        thread_local! {
220            static ATTRIBUTE_ID: Cell<usize> = const { Cell::new(0) };
221        }
222        ATTRIBUTE_ID.with(|id| {
223            let next = id.get();
224            id.set(next + 1);
225            AttributeId(next)
226        })
227    }
228
229    /// The number itself, for keying on.
230    pub fn get(&self) -> usize {
231        self.0
232    }
233}
234
235/// A fresh id, never a copy — see [`GeometryId`](super::GeometryId).
236impl Clone for AttributeId {
237    fn clone(&self) -> Self {
238        Self::next()
239    }
240}
241
242impl Default for AttributeId {
243    fn default() -> Self {
244        Self::next()
245    }
246}
247
248/// The element type of a [`TypedArray`] — the JavaScript array constructor
249/// (`Float32Array`, `Uint8Array`, …) without the data.
250#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
251pub enum ArrayKind {
252    /// `Float32Array`.
253    F32,
254    /// `Float16BufferAttribute`'s `Uint16Array` of binary16 bits.
255    F16,
256    /// `Int8Array`.
257    I8,
258    /// `Uint8Array`.
259    U8,
260    /// `Uint8ClampedArray`.
261    U8Clamped,
262    /// `Int16Array`.
263    I16,
264    /// `Uint16Array`.
265    U16,
266    /// `Int32Array`.
267    I32,
268    /// `Uint32Array`.
269    U32,
270}
271
272impl ArrayKind {
273    /// `TypedArray.BYTES_PER_ELEMENT`.
274    pub fn bytes_per_element(self) -> usize {
275        match self {
276            ArrayKind::I8 | ArrayKind::U8 | ArrayKind::U8Clamped => 1,
277            ArrayKind::F16 | ArrayKind::I16 | ArrayKind::U16 => 2,
278            ArrayKind::F32 | ArrayKind::I32 | ArrayKind::U32 => 4,
279        }
280    }
281
282    /// The array `WebGPUAttributeUtils.createAttribute()` uploads: 8- and
283    /// 16-bit integers that are neither normalized nor interleaved are rebuilt
284    /// as `Int32Array`/`Uint32Array` ("patch for INT16 and UINT16"). `F16` is
285    /// not widened — see decision 3 in the module docs — nor is `U8Clamped`,
286    /// which three's patch does not list.
287    pub(crate) fn upload_kind(self, normalized: bool, interleaved: bool) -> ArrayKind {
288        if normalized || interleaved {
289            return self;
290        }
291        match self {
292            ArrayKind::I8 | ArrayKind::I16 => ArrayKind::I32,
293            ArrayKind::U8 | ArrayKind::U16 => ArrayKind::U32,
294            kind => kind,
295        }
296    }
297
298    /// The table of decision 3: `WebGPUAttributeUtils._getVertexFormat()`
299    /// applied to the array `createAttribute()` uploads, returning the format
300    /// and the padded item size (the components per element in the uploaded
301    /// bytes, `item_size` rounded up so the byte stride is a multiple of 4).
302    ///
303    /// # Panics
304    ///
305    /// On the rows three has no format for, with three's message: item size 1
306    /// of an 8- or 16-bit array that is normalized or interleaved (or of
307    /// `F16`), a normalized `F32`/`I32`/`U32`/`F16` with item size above 1,
308    /// and any `U8Clamped` that reaches the table unwidened — which is every
309    /// one, since `Uint8ClampedArray` is in neither prefix map. Three logs
310    /// and returns `undefined` here instead, leaving the failure to pipeline
311    /// validation; panicking is a deliberate divergence (decision 3 in the
312    /// module docs).
313    pub fn vertex_format(
314        self,
315        item_size: usize,
316        normalized: bool,
317        interleaved: bool,
318    ) -> (wgpu::VertexFormat, usize) {
319        use wgpu::VertexFormat as F;
320
321        let unsupported = || -> ! {
322            panic!(
323                "THREE.WebGPUAttributeUtils: Vertex format not supported yet. \
324                 ({self:?}, itemSize {item_size}, normalized {normalized}, interleaved {interleaved})"
325            )
326        };
327        assert!(
328            (1..=4).contains(&item_size),
329            "three-rs: a vertex attribute has 1 to 4 components, not {item_size}"
330        );
331
332        let kind = self.upload_kind(normalized, interleaved);
333        if item_size == 1 {
334            let format = match kind {
335                ArrayKind::I32 => F::Sint32,
336                ArrayKind::U32 => F::Uint32,
337                ArrayKind::F32 => F::Float32,
338                _ => unsupported(),
339            };
340            return (format, 1);
341        }
342
343        let bpe = kind.bytes_per_element();
344        let padded = (bpe * item_size).div_ceil(4) * 4 / bpe;
345        let format = match (kind, normalized, padded) {
346            (ArrayKind::F32, false, 2) => F::Float32x2,
347            (ArrayKind::F32, false, 3) => F::Float32x3,
348            (ArrayKind::F32, false, 4) => F::Float32x4,
349            (ArrayKind::I32, false, 2) => F::Sint32x2,
350            (ArrayKind::I32, false, 3) => F::Sint32x3,
351            (ArrayKind::I32, false, 4) => F::Sint32x4,
352            (ArrayKind::U32, false, 2) => F::Uint32x2,
353            (ArrayKind::U32, false, 3) => F::Uint32x3,
354            (ArrayKind::U32, false, 4) => F::Uint32x4,
355            (ArrayKind::F16, false, 2) => F::Float16x2,
356            (ArrayKind::F16, false, 4) => F::Float16x4,
357            (ArrayKind::I16, false, 2) => F::Sint16x2,
358            (ArrayKind::I16, false, 4) => F::Sint16x4,
359            (ArrayKind::I16, true, 2) => F::Snorm16x2,
360            (ArrayKind::I16, true, 4) => F::Snorm16x4,
361            (ArrayKind::U16, false, 2) => F::Uint16x2,
362            (ArrayKind::U16, false, 4) => F::Uint16x4,
363            (ArrayKind::U16, true, 2) => F::Unorm16x2,
364            (ArrayKind::U16, true, 4) => F::Unorm16x4,
365            (ArrayKind::I8, false, 4) => F::Sint8x4,
366            (ArrayKind::I8, true, 4) => F::Snorm8x4,
367            (ArrayKind::U8, false, 4) => F::Uint8x4,
368            (ArrayKind::U8, true, 4) => F::Unorm8x4,
369            _ => unsupported(),
370        };
371        (format, padded)
372    }
373
374    /// `NodeBuilder.getTypeFromAttribute()`: the type the vertex input is
375    /// declared in. `normalized` or `F16` reads as floats; otherwise signed
376    /// integers as `i32`, unsigned as `u32`, `F32` (and `U8Clamped`, which
377    /// three's `typeFromArray` map lacks, so its `'float'` default applies) as
378    /// `f32`. The vector width is the attribute's own item size, unpadded.
379    pub fn shader_type(self, item_size: usize, normalized: bool) -> Type {
380        let component = if normalized {
381            Type::F32
382        } else {
383            match self {
384                ArrayKind::I8 | ArrayKind::I16 | ArrayKind::I32 => Type::I32,
385                ArrayKind::U8 | ArrayKind::U16 | ArrayKind::U32 => Type::U32,
386                ArrayKind::F32 | ArrayKind::F16 | ArrayKind::U8Clamped => Type::F32,
387            }
388        };
389        if item_size == 1 {
390            component
391        } else {
392            Type::vector_of(component, item_size)
393        }
394    }
395
396    /// `MathUtils.denormalize( value, array )`. `F16` is three's
397    /// `Uint16Array` and gets its range.
398    fn denormalize(self, value: f64) -> f64 {
399        match self {
400            ArrayKind::F32 => value,
401            ArrayKind::U32 => value / 4294967295.0,
402            ArrayKind::U16 | ArrayKind::F16 => value / 65535.0,
403            ArrayKind::U8 | ArrayKind::U8Clamped => value / 255.0,
404            ArrayKind::I32 => (value / 2147483647.0).max(-1.0),
405            ArrayKind::I16 => (value / 32767.0).max(-1.0),
406            ArrayKind::I8 => (value / 127.0).max(-1.0),
407        }
408    }
409
410    /// `MathUtils.normalize( value, array )` — `Math.round( value * max )`.
411    fn normalize(self, value: f64) -> f64 {
412        let scale = match self {
413            ArrayKind::F32 => return value,
414            ArrayKind::U32 => 4294967295.0,
415            ArrayKind::U16 | ArrayKind::F16 => 65535.0,
416            ArrayKind::U8 | ArrayKind::U8Clamped => 255.0,
417            ArrayKind::I32 => 2147483647.0,
418            ArrayKind::I16 => 32767.0,
419            ArrayKind::I8 => 127.0,
420        };
421        js_round(value * scale)
422    }
423}
424
425/// `createAttribute()`'s `paddedItemSize` for an upload whose elements are
426/// `kind` (already widened): a storage attribute of item size 3 is padded to
427/// 4 ("WGSL does not support packed vec3 data in storage buffers"); otherwise
428/// an item of more than one element whose byte stride is not a multiple of 4
429/// is padded up to one. `item_size` when no padding applies.
430fn padded_item_size(kind: ArrayKind, item_size: usize, storage: bool) -> usize {
431    if storage && item_size == 3 {
432        return 4;
433    }
434    let bpe = kind.bytes_per_element();
435    if item_size > 1 && !(item_size * bpe).is_multiple_of(4) {
436        (item_size * bpe).div_ceil(4) * 4 / bpe
437    } else {
438        item_size
439    }
440}
441
442/// `Math.round` — halves round towards +∞.
443fn js_round(x: f64) -> f64 {
444    (x + 0.5).floor()
445}
446
447/// The ECMAScript `ToInt8`/`ToUint16`/… conversions a typed-array store does:
448/// non-finite is 0, otherwise truncate and wrap modulo `2^bits`.
449fn js_wrap(value: f64, bits: i32) -> u64 {
450    if !value.is_finite() {
451        return 0;
452    }
453    value.trunc().rem_euclid(2f64.powi(bits)) as u64
454}
455
456/// The data of a [`BufferAttribute`] or [`InterleavedBuffer`]: one variant per
457/// JavaScript typed array three puts behind an attribute.
458#[derive(Clone, Debug, PartialEq)]
459pub enum TypedArray {
460    /// `Float32Array` — what [`BufferAttribute::new`] makes.
461    F32(Vec<f32>),
462    /// `Float16BufferAttribute`'s array: IEEE binary16 **bits** in a
463    /// `Uint16Array`, read and written through `fromHalfFloat` /
464    /// `toHalfFloat` by the attribute's accessors.
465    F16(Vec<u16>),
466    /// `Int8Array`.
467    I8(Vec<i8>),
468    /// `Uint8Array`.
469    U8(Vec<u8>),
470    /// `Uint8ClampedArray` — stores clamp to `0..=255` and round half to even
471    /// instead of wrapping.
472    U8Clamped(Vec<u8>),
473    /// `Int16Array`.
474    I16(Vec<i16>),
475    /// `Uint16Array`.
476    U16(Vec<u16>),
477    /// `Int32Array`.
478    I32(Vec<i32>),
479    /// `Uint32Array`.
480    U32(Vec<u32>),
481}
482
483macro_rules! each_array {
484    ($array:expr, $v:ident => $body:expr) => {
485        match $array {
486            TypedArray::F32($v) => $body,
487            TypedArray::F16($v) => $body,
488            TypedArray::I8($v) => $body,
489            TypedArray::U8($v) => $body,
490            TypedArray::U8Clamped($v) => $body,
491            TypedArray::I16($v) => $body,
492            TypedArray::U16($v) => $body,
493            TypedArray::I32($v) => $body,
494            TypedArray::U32($v) => $body,
495        }
496    };
497}
498
499impl TypedArray {
500    /// `new ArrayType( len )` — `len` zeros of `kind`.
501    pub(crate) fn zeros(kind: ArrayKind, len: usize) -> Self {
502        match kind {
503            ArrayKind::F32 => TypedArray::F32(vec![0.0; len]),
504            ArrayKind::F16 => TypedArray::F16(vec![0; len]),
505            ArrayKind::I8 => TypedArray::I8(vec![0; len]),
506            ArrayKind::U8 => TypedArray::U8(vec![0; len]),
507            ArrayKind::U8Clamped => TypedArray::U8Clamped(vec![0; len]),
508            ArrayKind::I16 => TypedArray::I16(vec![0; len]),
509            ArrayKind::U16 => TypedArray::U16(vec![0; len]),
510            ArrayKind::I32 => TypedArray::I32(vec![0; len]),
511            ArrayKind::U32 => TypedArray::U32(vec![0; len]),
512        }
513    }
514
515    /// `new ArrayType( values )` — each value converted the way a JavaScript
516    /// typed-array store converts a number (see [`set`](Self::set)).
517    pub(crate) fn from_f64(kind: ArrayKind, values: &[f64]) -> Self {
518        let mut array = Self::zeros(kind, values.len());
519        for (i, v) in values.iter().enumerate() {
520            array.set(i, *v);
521        }
522        array
523    }
524
525    /// `new ArrayType( arrayBuffer )` — a view of little-endian `bytes` as
526    /// `kind`, copied out. A `Float16` array keeps the raw bits, as the
527    /// `Uint16Array` behind a `Float16BufferAttribute` does.
528    ///
529    /// # Panics
530    ///
531    /// If `bytes.len()` is not a multiple of the element size, where
532    /// JavaScript throws a `RangeError`.
533    pub(crate) fn from_le_bytes(kind: ArrayKind, bytes: &[u8]) -> Self {
534        let bpe = kind.bytes_per_element();
535        assert!(
536            bytes.len().is_multiple_of(bpe),
537            "three-rs: byte length of {kind:?} should be a multiple of {bpe}, got {}",
538            bytes.len()
539        );
540        fn words<const N: usize, T>(bytes: &[u8], f: impl Fn([u8; N]) -> T) -> Vec<T> {
541            bytes.as_chunks::<N>().0.iter().map(|w| f(*w)).collect()
542        }
543        match kind {
544            ArrayKind::F32 => TypedArray::F32(words(bytes, f32::from_le_bytes)),
545            ArrayKind::F16 => TypedArray::F16(words(bytes, u16::from_le_bytes)),
546            ArrayKind::I8 => TypedArray::I8(bytes.iter().map(|&b| b as i8).collect()),
547            ArrayKind::U8 => TypedArray::U8(bytes.to_vec()),
548            ArrayKind::U8Clamped => TypedArray::U8Clamped(bytes.to_vec()),
549            ArrayKind::I16 => TypedArray::I16(words(bytes, i16::from_le_bytes)),
550            ArrayKind::U16 => TypedArray::U16(words(bytes, u16::from_le_bytes)),
551            ArrayKind::I32 => TypedArray::I32(words(bytes, i32::from_le_bytes)),
552            ArrayKind::U32 => TypedArray::U32(words(bytes, u32::from_le_bytes)),
553        }
554    }
555
556    /// The element type.
557    pub fn kind(&self) -> ArrayKind {
558        match self {
559            TypedArray::F32(_) => ArrayKind::F32,
560            TypedArray::F16(_) => ArrayKind::F16,
561            TypedArray::I8(_) => ArrayKind::I8,
562            TypedArray::U8(_) => ArrayKind::U8,
563            TypedArray::U8Clamped(_) => ArrayKind::U8Clamped,
564            TypedArray::I16(_) => ArrayKind::I16,
565            TypedArray::U16(_) => ArrayKind::U16,
566            TypedArray::I32(_) => ArrayKind::I32,
567            TypedArray::U32(_) => ArrayKind::U32,
568        }
569    }
570
571    /// `array.length`, in elements.
572    pub fn len(&self) -> usize {
573        each_array!(self, v => v.len())
574    }
575
576    /// `array.length === 0`.
577    pub fn is_empty(&self) -> bool {
578        self.len() == 0
579    }
580
581    /// `array[ index ]` as a JavaScript number. For `F16` that is the raw
582    /// bits, as three's `Uint16Array` holds them.
583    pub fn get(&self, index: usize) -> f64 {
584        match self {
585            TypedArray::F32(v) => v[index] as f64,
586            TypedArray::F16(v) => v[index] as f64,
587            TypedArray::I8(v) => v[index] as f64,
588            TypedArray::U8(v) => v[index] as f64,
589            TypedArray::U8Clamped(v) => v[index] as f64,
590            TypedArray::I16(v) => v[index] as f64,
591            TypedArray::U16(v) => v[index] as f64,
592            TypedArray::I32(v) => v[index] as f64,
593            TypedArray::U32(v) => v[index] as f64,
594        }
595    }
596
597    /// `array[ index ] = value`, with the store's conversion: `F32` rounds to
598    /// the nearest `f32`; the integer arrays truncate and wrap (non-finite is
599    /// 0); `U8Clamped` clamps to `0..=255` and rounds half to even (NaN is 0).
600    pub fn set(&mut self, index: usize, value: f64) {
601        match self {
602            TypedArray::F32(v) => v[index] = value as f32,
603            TypedArray::F16(v) | TypedArray::U16(v) => v[index] = js_wrap(value, 16) as u16,
604            TypedArray::I8(v) => v[index] = js_wrap(value, 8) as u8 as i8,
605            TypedArray::U8(v) => v[index] = js_wrap(value, 8) as u8,
606            TypedArray::U8Clamped(v) => {
607                v[index] = if value.is_nan() {
608                    0
609                } else {
610                    value.clamp(0.0, 255.0).round_ties_even() as u8
611                }
612            }
613            TypedArray::I16(v) => v[index] = js_wrap(value, 16) as u16 as i16,
614            TypedArray::I32(v) => v[index] = js_wrap(value, 32) as u32 as i32,
615            TypedArray::U32(v) => v[index] = js_wrap(value, 32) as u32,
616        }
617    }
618
619    /// `array[ to ] = other[ from ]` — an element copy, with the store's
620    /// conversion when the two arrays differ in type.
621    fn copy_element(&mut self, to: usize, other: &TypedArray, from: usize) {
622        self.set(to, other.get(from));
623    }
624
625    /// [`ArrayKind::vertex_format`] for this array's kind — the table of
626    /// decision 3 in the module docs.
627    pub fn vertex_format(
628        &self,
629        item_size: usize,
630        normalized: bool,
631        interleaved: bool,
632    ) -> (wgpu::VertexFormat, usize) {
633        self.kind()
634            .vertex_format(item_size, normalized, interleaved)
635    }
636
637    /// The `Float32Array` itself, or `None` for any other kind.
638    pub fn as_f32(&self) -> Option<&Vec<f32>> {
639        match self {
640            TypedArray::F32(v) => Some(v),
641            _ => None,
642        }
643    }
644
645    /// The `Float32Array` itself, mutably, or `None` for any other kind.
646    pub fn as_f32_mut(&mut self) -> Option<&mut Vec<f32>> {
647        match self {
648            TypedArray::F32(v) => Some(v),
649            _ => None,
650        }
651    }
652
653    /// Element `index` as little-endian bytes of `kind` — `kind` is this
654    /// array's own kind or the 32-bit integer one it widens to.
655    fn push_bytes(&self, index: usize, kind: ArrayKind, out: &mut Vec<u8>) {
656        match (self, kind) {
657            (TypedArray::F32(v), _) => out.extend_from_slice(&v[index].to_le_bytes()),
658            (TypedArray::I8(v), ArrayKind::I32) => {
659                out.extend_from_slice(&(v[index] as i32).to_le_bytes())
660            }
661            (TypedArray::I16(v), ArrayKind::I32) => {
662                out.extend_from_slice(&(v[index] as i32).to_le_bytes())
663            }
664            (TypedArray::U8(v), ArrayKind::U32) => {
665                out.extend_from_slice(&(v[index] as u32).to_le_bytes())
666            }
667            (TypedArray::U16(v), ArrayKind::U32) => {
668                out.extend_from_slice(&(v[index] as u32).to_le_bytes())
669            }
670            (TypedArray::F16(v) | TypedArray::U16(v), _) => {
671                out.extend_from_slice(&v[index].to_le_bytes())
672            }
673            (TypedArray::I8(v), _) => out.push(v[index] as u8),
674            (TypedArray::U8(v) | TypedArray::U8Clamped(v), _) => out.push(v[index]),
675            (TypedArray::I16(v), _) => out.extend_from_slice(&v[index].to_le_bytes()),
676            (TypedArray::I32(v), _) => out.extend_from_slice(&v[index].to_le_bytes()),
677            (TypedArray::U32(v), _) => out.extend_from_slice(&v[index].to_le_bytes()),
678        }
679    }
680
681    /// The array as little-endian bytes, `kind` per element (see
682    /// [`push_bytes`](Self::push_bytes)), `item_size` elements per item laid
683    /// out `padded_item_size` apart with zeros between, and the total rounded
684    /// up to a multiple of 4 — `createAttribute()`'s `paddedArray` and its
685    /// `size` rounding.
686    pub(crate) fn to_bytes(
687        &self,
688        kind: ArrayKind,
689        item_size: usize,
690        padded_item_size: usize,
691    ) -> Vec<u8> {
692        let bpe = kind.bytes_per_element();
693        let count = self.len() / item_size.max(1);
694        let mut out = Vec::with_capacity(count * padded_item_size * bpe + 4);
695        if padded_item_size == item_size {
696            for i in 0..self.len() {
697                self.push_bytes(i, kind, &mut out);
698            }
699        } else {
700            for item in 0..count {
701                for c in 0..item_size {
702                    self.push_bytes(item * item_size + c, kind, &mut out);
703                }
704                out.resize(out.len() + (padded_item_size - item_size) * bpe, 0);
705            }
706        }
707        out.resize(out.len().div_ceil(4) * 4, 0);
708        out
709    }
710}
711
712impl From<Vec<f32>> for TypedArray {
713    fn from(v: Vec<f32>) -> Self {
714        TypedArray::F32(v)
715    }
716}
717
718impl From<Vec<i8>> for TypedArray {
719    fn from(v: Vec<i8>) -> Self {
720        TypedArray::I8(v)
721    }
722}
723
724impl From<Vec<u8>> for TypedArray {
725    fn from(v: Vec<u8>) -> Self {
726        TypedArray::U8(v)
727    }
728}
729
730impl From<Vec<i16>> for TypedArray {
731    fn from(v: Vec<i16>) -> Self {
732        TypedArray::I16(v)
733    }
734}
735
736impl From<Vec<u16>> for TypedArray {
737    fn from(v: Vec<u16>) -> Self {
738        TypedArray::U16(v)
739    }
740}
741
742impl From<Vec<i32>> for TypedArray {
743    fn from(v: Vec<i32>) -> Self {
744        TypedArray::I32(v)
745    }
746}
747
748impl From<Vec<u32>> for TypedArray {
749    fn from(v: Vec<u32>) -> Self {
750        TypedArray::U32(v)
751    }
752}
753
754/// `Ref<TypedArray>` → `Ref<Vec<f32>>`, panicking the way decision 2 says.
755fn f32_ref(array: Ref<'_, TypedArray>) -> Ref<'_, Vec<f32>> {
756    Ref::map(array, |a| match a {
757        TypedArray::F32(v) => v,
758        other => panic_not_f32(other.kind()),
759    })
760}
761
762/// The `RefMut` twin of [`f32_ref`].
763fn f32_ref_mut(array: RefMut<'_, TypedArray>) -> RefMut<'_, Vec<f32>> {
764    RefMut::map(array, |a| match a {
765        TypedArray::F32(v) => v,
766        other => panic_not_f32(other.kind()),
767    })
768}
769
770fn panic_not_f32(kind: ArrayKind) -> ! {
771    panic!(
772        "three-rs: array() is the Float32Array view, and this attribute's array is {kind:?}; \
773         read it with data()"
774    )
775}
776
777/// three.js' `InterleavedBuffer` / `InstancedInterleavedBuffer`: one typed
778/// array holding several attributes' items side by side, `stride` elements
779/// per vertex (or per instance). Attributes are views over it — see
780/// [`BufferAttribute::interleaved`]. Shared as `Rc<InterleavedBuffer>`; the
781/// renderer uploads it once, as one vertex buffer, keyed on [`id`](Self::id).
782#[derive(Debug)]
783pub struct InterleavedBuffer {
784    id: AttributeId,
785    array: RefCell<TypedArray>,
786    stride: usize,
787    version: Cell<u32>,
788    instanced: bool,
789    mesh_per_attribute: usize,
790}
791
792impl InterleavedBuffer {
793    /// `new InterleavedBuffer( array, stride )`.
794    pub fn new(array: impl Into<TypedArray>, stride: usize) -> Self {
795        Self {
796            id: AttributeId::next(),
797            array: RefCell::new(array.into()),
798            stride,
799            version: Cell::new(0),
800            instanced: false,
801            mesh_per_attribute: 1,
802        }
803    }
804
805    /// `new InstancedInterleavedBuffer( array, stride, meshPerAttribute )` —
806    /// its views step once per instance.
807    pub fn new_instanced(
808        array: impl Into<TypedArray>,
809        stride: usize,
810        mesh_per_attribute: usize,
811    ) -> Self {
812        Self {
813            instanced: true,
814            mesh_per_attribute,
815            ..Self::new(array, stride)
816        }
817    }
818
819    /// The identity the renderer's GPU buffer is keyed on. Drawn from the
820    /// [`AttributeId`] counter, so it never equals an attribute's id.
821    pub fn id(&self) -> usize {
822        self.id.get()
823    }
824
825    /// `interleavedBuffer.array` as the `Float32Array` it usually is.
826    ///
827    /// # Panics
828    ///
829    /// If the array is another kind; read it with [`data`](Self::data).
830    pub fn array(&self) -> Ref<'_, Vec<f32>> {
831        f32_ref(self.array.borrow())
832    }
833
834    /// [`array`](Self::array), for writing. Follow it with
835    /// [`set_needs_update`](Self::set_needs_update).
836    pub fn array_mut(&self) -> RefMut<'_, Vec<f32>> {
837        f32_ref_mut(self.array.borrow_mut())
838    }
839
840    /// `interleavedBuffer.array`, whatever its kind.
841    pub fn data(&self) -> Ref<'_, TypedArray> {
842        self.array.borrow()
843    }
844
845    /// [`data`](Self::data), for writing.
846    pub fn data_mut(&self) -> RefMut<'_, TypedArray> {
847        self.array.borrow_mut()
848    }
849
850    /// `InterleavedBuffer.stride`, in elements.
851    pub fn stride(&self) -> usize {
852        self.stride
853    }
854
855    /// `InterleavedBuffer.count` — `array.length / stride`.
856    pub fn count(&self) -> usize {
857        self.array.borrow().len() / self.stride
858    }
859
860    /// `InterleavedBuffer.version`.
861    pub fn version(&self) -> u32 {
862        self.version.get()
863    }
864
865    /// `interleavedBuffer.needsUpdate = true`. Every view of it re-uploads.
866    pub fn set_needs_update(&self) {
867        self.version.set(self.version.get() + 1);
868    }
869
870    /// `isInstancedInterleavedBuffer`.
871    pub fn is_instanced(&self) -> bool {
872        self.instanced
873    }
874
875    /// `InstancedInterleavedBuffer.meshPerAttribute` (1 on a plain buffer).
876    pub fn mesh_per_attribute(&self) -> usize {
877        self.mesh_per_attribute
878    }
879
880    /// `InterleavedBuffer.copyAt( index1, interleavedBuffer, index2 )` —
881    /// copies one vertex's `stride` elements.
882    pub fn copy_at(&self, index1: usize, other: &InterleavedBuffer, index2: usize) -> &Self {
883        let index1 = index1 * self.stride;
884        let index2 = index2 * other.stride;
885        if std::ptr::eq(self, other) {
886            let mut array = self.array.borrow_mut();
887            for i in 0..self.stride {
888                let v = array.get(index2 + i);
889                array.set(index1 + i, v);
890            }
891        } else {
892            let source = other.array.borrow();
893            let mut array = self.array.borrow_mut();
894            for i in 0..self.stride {
895                array.copy_element(index1 + i, &source, index2 + i);
896            }
897        }
898        self
899    }
900
901    /// `InterleavedBuffer.set( value, offset )`.
902    pub fn set(&self, value: &[f32], offset: usize) -> &Self {
903        let mut array = self.array.borrow_mut();
904        for (i, v) in value.iter().enumerate() {
905            array.set(offset + i, *v as f64);
906        }
907        self
908    }
909
910    /// `InterleavedBuffer.copy( source )` — the array (a copy of it, as
911    /// `new source.array.constructor( source.array )`) and the stride; on an
912    /// instanced buffer, `InstancedInterleavedBuffer.copy` also takes
913    /// `meshPerAttribute`.
914    pub fn copy(&mut self, source: &InterleavedBuffer) -> &mut Self {
915        *self.array.get_mut() = source.array.borrow().clone();
916        self.stride = source.stride;
917        if self.instanced {
918            self.mesh_per_attribute = source.mesh_per_attribute;
919        }
920        self
921    }
922}
923
924/// `InterleavedBuffer.clone()` / `InstancedInterleavedBuffer.clone()`: a copy
925/// of the array under a fresh id, `version` 0, `meshPerAttribute` kept.
926impl Clone for InterleavedBuffer {
927    fn clone(&self) -> Self {
928        Self {
929            id: AttributeId::next(),
930            array: RefCell::new(self.array.borrow().clone()),
931            stride: self.stride,
932            version: Cell::new(0),
933            instanced: self.instanced,
934            mesh_per_attribute: self.mesh_per_attribute,
935        }
936    }
937}
938
939/// What [`StorageBufferAttribute::new`] is given: three's `count` (a number,
940/// for a zero-filled array of `count * itemSize`) or a typed array.
941#[derive(Clone, Debug)]
942pub enum StorageContents {
943    /// `new StorageBufferAttribute( count, itemSize, typeClass )`.
944    Count(usize),
945    /// `new StorageBufferAttribute( array, itemSize )`.
946    Array(TypedArray),
947}
948
949impl From<usize> for StorageContents {
950    fn from(count: usize) -> Self {
951        StorageContents::Count(count)
952    }
953}
954
955impl From<TypedArray> for StorageContents {
956    fn from(array: TypedArray) -> Self {
957        StorageContents::Array(array)
958    }
959}
960
961impl From<Vec<f32>> for StorageContents {
962    fn from(array: Vec<f32>) -> Self {
963        StorageContents::Array(TypedArray::F32(array))
964    }
965}
966
967/// three.js' `StorageBufferAttribute` / `StorageInstancedBufferAttribute`
968/// (`src/renderers/common/`): an attribute whose GPU buffer is also a storage
969/// buffer, so a compute kernel can write what a draw reads as vertices.
970///
971/// A handle, as [`IndirectStorageBufferAttribute`](super::IndirectStorageBufferAttribute)
972/// is: clones are the same attribute, and the renderer keys the one GPU buffer
973/// on [`id`](Self::id), which `storage( &attribute, ty, count )` (in
974/// `nodes::tsl`) carries too. Turn it into a geometry attribute with
975/// `.into()`. The array is the buffer's initial contents only; it is uploaded
976/// once, padded to `vec4` stride when the item size is 3.
977#[derive(Clone, Debug)]
978pub struct StorageBufferAttribute {
979    id: BufferId,
980    array: Rc<RefCell<TypedArray>>,
981    /// `BufferAttribute.itemSize`, unpadded.
982    pub item_size: usize,
983    instanced: bool,
984}
985
986impl StorageBufferAttribute {
987    /// `new StorageBufferAttribute( count | array, itemSize, typeClass )`. With
988    /// a count, the array is `count * item_size` zeros of `kind`; with an
989    /// array, `kind` is ignored as three ignores `typeClass`.
990    pub fn new(contents: impl Into<StorageContents>, item_size: usize, kind: ArrayKind) -> Self {
991        let array = match contents.into() {
992            StorageContents::Count(count) => TypedArray::zeros(kind, count * item_size),
993            StorageContents::Array(array) => array,
994        };
995        Self {
996            id: BufferId::next(),
997            array: Rc::new(RefCell::new(array)),
998            item_size,
999            instanced: false,
1000        }
1001    }
1002
1003    /// `new StorageInstancedBufferAttribute( count | array, itemSize, typeClass )`
1004    /// — read as a vertex attribute, it steps once per instance.
1005    pub fn new_instanced(
1006        contents: impl Into<StorageContents>,
1007        item_size: usize,
1008        kind: ArrayKind,
1009    ) -> Self {
1010        Self {
1011            instanced: true,
1012            ..Self::new(contents, item_size, kind)
1013        }
1014    }
1015
1016    /// The identity the renderer's GPU buffer is keyed on.
1017    pub fn id(&self) -> BufferId {
1018        self.id
1019    }
1020
1021    /// `BufferAttribute.count` — `array.length / itemSize`.
1022    pub fn count(&self) -> usize {
1023        self.array.borrow().len() / self.item_size
1024    }
1025
1026    /// `attribute.array` — the initial contents.
1027    pub fn data(&self) -> Ref<'_, TypedArray> {
1028        self.array.borrow()
1029    }
1030
1031    /// `isStorageInstancedBufferAttribute`.
1032    pub fn is_instanced(&self) -> bool {
1033        self.instanced
1034    }
1035
1036    /// The kind of the uploaded elements: the array's own, or — for 8- and
1037    /// 16-bit integers that are not `normalized` — the 32-bit one
1038    /// `createAttribute()`'s "patch for INT16 and UINT16" widens it to, which
1039    /// it applies to a storage attribute as to any other.
1040    pub(crate) fn upload_kind(&self, normalized: bool) -> ArrayKind {
1041        self.array.borrow().kind().upload_kind(normalized, false)
1042    }
1043
1044    /// Components per element in the GPU buffer, after widening: 4 for an
1045    /// item size of 3, otherwise `item_size` rounded up to a 4-byte stride.
1046    pub(crate) fn padded_item_size(&self, normalized: bool) -> usize {
1047        padded_item_size(self.upload_kind(normalized), self.item_size, true)
1048    }
1049
1050    /// The GPU buffer's initial contents as 32-bit words, widened and at the
1051    /// padded stride — what `createAttribute()` uploads for a storage
1052    /// attribute. `normalized` is the attribute view's (`false` for a
1053    /// `storage()` node, as three's `StorageBufferAttribute` never sets it).
1054    pub(crate) fn init_words(&self, normalized: bool) -> Vec<u32> {
1055        let kind = self.upload_kind(normalized);
1056        let padded = self.padded_item_size(normalized);
1057        let array = self.array.borrow();
1058        let bytes = array.to_bytes(kind, self.item_size, padded);
1059        bytes
1060            .as_chunks::<4>()
1061            .0
1062            .iter()
1063            .map(|w| u32::from_le_bytes(*w))
1064            .collect()
1065    }
1066}
1067
1068impl From<StorageBufferAttribute> for BufferAttribute {
1069    fn from(storage: StorageBufferAttribute) -> Self {
1070        let instanced = storage.instanced;
1071        let item_size = storage.item_size;
1072        Self {
1073            id: AttributeId::next(),
1074            storage: Backing::Storage(storage),
1075            item_size,
1076            normalized: false,
1077            version: Cell::new(0),
1078            instanced,
1079        }
1080    }
1081}
1082
1083/// Where a [`BufferAttribute`]'s elements live.
1084#[derive(Debug)]
1085enum Backing {
1086    /// Its own typed array.
1087    Own(RefCell<TypedArray>),
1088    /// A view into an [`InterleavedBuffer`], `offset` elements into each
1089    /// stride.
1090    Interleaved {
1091        data: Rc<InterleavedBuffer>,
1092        offset: usize,
1093    },
1094    /// A [`StorageBufferAttribute`]'s buffer.
1095    Storage(StorageBufferAttribute),
1096}
1097
1098/// three.js' `BufferAttribute`, its typed subclasses (`Uint8BufferAttribute`,
1099/// …, `Float16BufferAttribute`), `InstancedBufferAttribute` and
1100/// `InterleavedBufferAttribute`: one named vertex attribute, `item_size`
1101/// values per vertex. See the module docs for the shape.
1102#[derive(Debug)]
1103pub struct BufferAttribute {
1104    /// `BufferAttribute.id`. Read-only in spirit; see [`AttributeId`].
1105    pub id: AttributeId,
1106    /// The data, behind a `RefCell` because a geometry is shared as
1107    /// `Rc<BufferGeometry>` and three.js mutates attribute data in place
1108    /// (issue #47).
1109    storage: Backing,
1110    /// `BufferAttribute.itemSize` — the number of values per vertex.
1111    pub item_size: usize,
1112    /// `BufferAttribute.normalized` — integer data read as `0..1` (or
1113    /// `-1..1`) floats, by the GPU and by the `get_*`/`set_*` accessors.
1114    pub normalized: bool,
1115    /// `BufferAttribute.version` — bumped by
1116    /// [`set_needs_update`](Self::set_needs_update). An interleaved view uses
1117    /// its buffer's instead.
1118    version: Cell<u32>,
1119    /// `isInstancedBufferAttribute` — the attribute steps once per instance,
1120    /// not per vertex. Only meaningful on an instanced geometry; see
1121    /// [`BufferGeometry::instance_count`](super::BufferGeometry::instance_count).
1122    /// An interleaved view uses its buffer's instead.
1123    instanced: bool,
1124}
1125
1126/// `BufferAttribute`'s typed constructors: `new Uint8BufferAttribute( array,
1127/// itemSize, normalized )` is `BufferAttribute::uint8( array, item_size,
1128/// normalized )`, and so on.
1129macro_rules! typed_constructors {
1130    ($($(#[$doc:meta])* $name:ident($elem:ty) => $variant:ident;)*) => {
1131        $(
1132            $(#[$doc])*
1133            pub fn $name(array: Vec<$elem>, item_size: usize, normalized: bool) -> Self {
1134                Self::from_typed(TypedArray::$variant(array), item_size, normalized)
1135            }
1136        )*
1137    };
1138}
1139
1140impl BufferAttribute {
1141    /// `new BufferAttribute( array, itemSize )` over a `Float32Array` —
1142    /// `Float32BufferAttribute`, three's default.
1143    pub fn new(array: Vec<f32>, item_size: usize) -> Self {
1144        Self::from_typed(TypedArray::F32(array), item_size, false)
1145    }
1146
1147    /// `new BufferAttribute( array, itemSize, normalized )` — the base
1148    /// constructor every typed one calls.
1149    pub fn from_typed(array: TypedArray, item_size: usize, normalized: bool) -> Self {
1150        Self {
1151            id: AttributeId::next(),
1152            storage: Backing::Own(RefCell::new(array)),
1153            item_size,
1154            normalized,
1155            version: Cell::new(0),
1156            instanced: false,
1157        }
1158    }
1159
1160    typed_constructors! {
1161        /// `new Int8BufferAttribute( array, itemSize, normalized )`.
1162        int8(i8) => I8;
1163        /// `new Uint8BufferAttribute( array, itemSize, normalized )`.
1164        uint8(u8) => U8;
1165        /// `new Uint8ClampedBufferAttribute( array, itemSize, normalized )`.
1166        uint8_clamped(u8) => U8Clamped;
1167        /// `new Int16BufferAttribute( array, itemSize, normalized )`.
1168        int16(i16) => I16;
1169        /// `new Uint16BufferAttribute( array, itemSize, normalized )`.
1170        uint16(u16) => U16;
1171        /// `new Int32BufferAttribute( array, itemSize, normalized )`.
1172        int32(i32) => I32;
1173        /// `new Uint32BufferAttribute( array, itemSize, normalized )`.
1174        uint32(u32) => U32;
1175    }
1176
1177    /// `new Float16BufferAttribute( array, itemSize, normalized )` — `array`
1178    /// is binary16 bits, as three's `Uint16Array` is. Build it from floats
1179    /// with [`to_half_float`], or with [`set_x`](Self::set_x) and friends,
1180    /// which convert.
1181    pub fn float16(array: Vec<u16>, item_size: usize, normalized: bool) -> Self {
1182        Self::from_typed(TypedArray::F16(array), item_size, normalized)
1183    }
1184
1185    /// `new InstancedBufferAttribute( array, itemSize )` — one element per
1186    /// instance. See [`is_instanced`](Self::is_instanced).
1187    pub fn new_instanced(array: Vec<f32>, item_size: usize) -> Self {
1188        Self::from_typed_instanced(TypedArray::F32(array), item_size, false)
1189    }
1190
1191    /// `new InstancedBufferAttribute( array, itemSize, normalized )` over any
1192    /// typed array.
1193    pub fn from_typed_instanced(array: TypedArray, item_size: usize, normalized: bool) -> Self {
1194        Self {
1195            instanced: true,
1196            ..Self::from_typed(array, item_size, normalized)
1197        }
1198    }
1199
1200    /// `new InterleavedBufferAttribute( interleavedBuffer, itemSize, offset,
1201    /// normalized )` — a view of `item_size` elements, `offset` elements into
1202    /// each of `data`'s strides.
1203    pub fn interleaved(
1204        data: Rc<InterleavedBuffer>,
1205        item_size: usize,
1206        offset: usize,
1207        normalized: bool,
1208    ) -> Self {
1209        Self {
1210            id: AttributeId::next(),
1211            storage: Backing::Interleaved { data, offset },
1212            item_size,
1213            normalized,
1214            version: Cell::new(0),
1215            instanced: false,
1216        }
1217    }
1218
1219    /// `attribute.isInstancedBufferAttribute`, or for an interleaved view
1220    /// `attribute.data.isInstancedInterleavedBuffer`.
1221    pub fn is_instanced(&self) -> bool {
1222        match &self.storage {
1223            Backing::Interleaved { data, .. } => data.is_instanced(),
1224            _ => self.instanced,
1225        }
1226    }
1227
1228    /// `attribute.isInterleavedBufferAttribute`.
1229    pub fn is_interleaved(&self) -> bool {
1230        matches!(self.storage, Backing::Interleaved { .. })
1231    }
1232
1233    /// `InterleavedBufferAttribute.data` — `None` for an attribute with its
1234    /// own array.
1235    pub fn data_buffer(&self) -> Option<&Rc<InterleavedBuffer>> {
1236        match &self.storage {
1237            Backing::Interleaved { data, .. } => Some(data),
1238            _ => None,
1239        }
1240    }
1241
1242    /// `InterleavedBufferAttribute.offset`, in elements (0 for an attribute
1243    /// with its own array).
1244    pub fn offset(&self) -> usize {
1245        match &self.storage {
1246            Backing::Interleaved { offset, .. } => *offset,
1247            _ => 0,
1248        }
1249    }
1250
1251    /// The [`StorageBufferAttribute`] this attribute reads, if it is one.
1252    pub(crate) fn storage_buffer(&self) -> Option<&StorageBufferAttribute> {
1253        match &self.storage {
1254            Backing::Storage(storage) => Some(storage),
1255            _ => None,
1256        }
1257    }
1258
1259    /// The cell holding the elements: this attribute's own, the interleaved
1260    /// buffer's, or the storage attribute's.
1261    fn cell(&self) -> &RefCell<TypedArray> {
1262        match &self.storage {
1263            Backing::Own(array) => array,
1264            Backing::Interleaved { data, .. } => &data.array,
1265            Backing::Storage(storage) => &storage.array,
1266        }
1267    }
1268
1269    /// `(stride, offset)` in elements: how item `i`'s first element is found,
1270    /// at `offset + i * stride`.
1271    fn layout(&self) -> (usize, usize) {
1272        match &self.storage {
1273            Backing::Interleaved { data, offset } => (data.stride, *offset),
1274            _ => (self.item_size, 0),
1275        }
1276    }
1277
1278    /// The element type.
1279    pub fn kind(&self) -> ArrayKind {
1280        self.cell().borrow().kind()
1281    }
1282
1283    /// `attribute.array` as the `Float32Array` it usually is, for reading. A
1284    /// `Ref`, so the borrow has to be held for as long as the slice is used.
1285    /// On an interleaved view it is the **whole** shared array, as three's
1286    /// `InterleavedBufferAttribute.array` getter returns.
1287    ///
1288    /// # Panics
1289    ///
1290    /// If the array is another kind (`Uint8Array`, …); read it with
1291    /// [`data`](Self::data).
1292    pub fn array(&self) -> Ref<'_, Vec<f32>> {
1293        f32_ref(self.cell().borrow())
1294    }
1295
1296    /// `attribute.array`, for writing — through a shared `&self`, so it works
1297    /// on an attribute of a geometry already handed to a mesh as an `Rc`.
1298    ///
1299    /// Writing alone changes nothing on screen: follow it with
1300    /// [`set_needs_update`](Self::set_needs_update), exactly as three.js needs
1301    /// `attribute.needsUpdate = true`.
1302    ///
1303    /// # Panics
1304    ///
1305    /// As [`array`](Self::array).
1306    pub fn array_mut(&self) -> RefMut<'_, Vec<f32>> {
1307        f32_ref_mut(self.cell().borrow_mut())
1308    }
1309
1310    /// `attribute.array`, whatever its kind.
1311    pub fn data(&self) -> Ref<'_, TypedArray> {
1312        self.cell().borrow()
1313    }
1314
1315    /// [`data`](Self::data), for writing.
1316    pub fn data_mut(&self) -> RefMut<'_, TypedArray> {
1317        self.cell().borrow_mut()
1318    }
1319
1320    /// `BufferAttribute.version` (an interleaved view's is its buffer's).
1321    pub fn version(&self) -> u32 {
1322        match &self.storage {
1323            Backing::Interleaved { data, .. } => data.version(),
1324            _ => self.version.get(),
1325        }
1326    }
1327
1328    /// `attribute.needsUpdate = true` — `version ++`. The next render that
1329    /// sees this geometry re-writes this attribute's GPU buffer (an
1330    /// interleaved view's buffer, shared by all its views), and only it.
1331    pub fn set_needs_update(&self) {
1332        match &self.storage {
1333            Backing::Interleaved { data, .. } => data.set_needs_update(),
1334            _ => self.version.set(self.version.get() + 1),
1335        }
1336    }
1337
1338    /// `BufferAttribute.count` — the number of vertices, `array.length /
1339    /// item_size` (`data.count` for an interleaved view).
1340    pub fn count(&self) -> usize {
1341        match &self.storage {
1342            Backing::Interleaved { data, .. } => data.count(),
1343            _ => self.cell().borrow().len() / self.item_size,
1344        }
1345    }
1346
1347    /// `BufferAttribute.getComponent( index, component )` and the shared body
1348    /// of `getX..getW`: the element widened to `f64`, `fromHalfFloat` on a
1349    /// `Float16BufferAttribute`, `denormalize`d when `normalized`.
1350    pub fn get_component(&self, index: usize, component: usize) -> f64 {
1351        let (stride, offset) = self.layout();
1352        let array = self.cell().borrow();
1353        let kind = array.kind();
1354        let mut value = array.get(offset + index * stride + component);
1355        if kind == ArrayKind::F16 {
1356            value = from_half_float(value as u16) as f64;
1357        }
1358        if self.normalized {
1359            value = kind.denormalize(value);
1360        }
1361        value
1362    }
1363
1364    /// `BufferAttribute.setComponent( index, component, value )` and the
1365    /// shared body of `setX..setXYZW`: `normalize`d when `normalized`,
1366    /// `toHalfFloat` on a `Float16BufferAttribute`, then stored with the
1367    /// typed array's conversion.
1368    pub fn set_component(&mut self, index: usize, component: usize, value: f64) -> &mut Self {
1369        self.store(index, component, value);
1370        self
1371    }
1372
1373    /// [`set_component`](Self::set_component) through `&self`, for crate
1374    /// code holding the attribute behind a shared geometry (the array is in
1375    /// a `RefCell`). Does not bump the version.
1376    pub(crate) fn store(&self, index: usize, component: usize, value: f64) {
1377        let (stride, offset) = self.layout();
1378        let mut array = self.cell().borrow_mut();
1379        let kind = array.kind();
1380        let mut value = value;
1381        if self.normalized {
1382            value = kind.normalize(value);
1383        }
1384        if kind == ArrayKind::F16 {
1385            value = to_half_float(value) as f64;
1386        }
1387        array.set(offset + index * stride + component, value);
1388    }
1389
1390    /// `BufferAttribute.getX()`.
1391    pub fn get_x(&self, index: usize) -> f64 {
1392        self.get_component(index, 0)
1393    }
1394
1395    /// `BufferAttribute.getY()`.
1396    pub fn get_y(&self, index: usize) -> f64 {
1397        self.get_component(index, 1)
1398    }
1399
1400    /// `BufferAttribute.getZ()`.
1401    pub fn get_z(&self, index: usize) -> f64 {
1402        self.get_component(index, 2)
1403    }
1404
1405    /// `BufferAttribute.getW()`.
1406    pub fn get_w(&self, index: usize) -> f64 {
1407        self.get_component(index, 3)
1408    }
1409
1410    /// `BufferAttribute.setX()`.
1411    pub fn set_x(&mut self, index: usize, x: f64) -> &mut Self {
1412        self.set_component(index, 0, x)
1413    }
1414
1415    /// `BufferAttribute.setY()`.
1416    pub fn set_y(&mut self, index: usize, y: f64) -> &mut Self {
1417        self.set_component(index, 1, y)
1418    }
1419
1420    /// `BufferAttribute.setZ()`.
1421    pub fn set_z(&mut self, index: usize, z: f64) -> &mut Self {
1422        self.set_component(index, 2, z)
1423    }
1424
1425    /// `BufferAttribute.setW()`.
1426    pub fn set_w(&mut self, index: usize, w: f64) -> &mut Self {
1427        self.set_component(index, 3, w)
1428    }
1429
1430    /// `BufferAttribute.setXY()`.
1431    pub fn set_xy(&mut self, index: usize, x: f64, y: f64) -> &mut Self {
1432        self.store(index, 0, x);
1433        self.store(index, 1, y);
1434        self
1435    }
1436
1437    /// `BufferAttribute.setXYZ()` — narrows on the way in, which is where
1438    /// three.js loses precision too.
1439    pub fn set_xyz(&mut self, index: usize, x: f64, y: f64, z: f64) {
1440        self.store(index, 0, x);
1441        self.store(index, 1, y);
1442        self.store(index, 2, z);
1443    }
1444
1445    /// `BufferAttribute.setXYZW()`.
1446    pub fn set_xyzw(&mut self, index: usize, x: f64, y: f64, z: f64, w: f64) -> &mut Self {
1447        self.store(index, 0, x);
1448        self.store(index, 1, y);
1449        self.store(index, 2, z);
1450        self.store(index, 3, w);
1451        self
1452    }
1453
1454    /// `BufferAttribute.copyAt()` — copies one item's raw elements from
1455    /// `attribute` (no normalization; the store's conversion if the kinds
1456    /// differ).
1457    pub fn copy_at(&mut self, index1: usize, attribute: &Self, index2: usize) -> &mut Self {
1458        let (stride1, offset1) = self.layout();
1459        let (stride2, offset2) = attribute.layout();
1460        let base1 = offset1 + index1 * stride1;
1461        let base2 = offset2 + index2 * stride2;
1462        if std::ptr::eq(self.cell(), attribute.cell()) {
1463            let mut array = self.cell().borrow_mut();
1464            for i in 0..self.item_size {
1465                let v = array.get(base2 + i);
1466                array.set(base1 + i, v);
1467            }
1468        } else {
1469            let source = attribute.cell().borrow();
1470            let mut array = self.cell().borrow_mut();
1471            for i in 0..self.item_size {
1472                array.copy_element(base1 + i, &source, base2 + i);
1473            }
1474        }
1475        self
1476    }
1477
1478    /// `BufferAttribute.copyArray()` — `this.array.set( array )`: `array`
1479    /// over the start of the attribute's array, element by element with the
1480    /// store's conversion. A shorter `array` leaves the rest as it was.
1481    ///
1482    /// # Panics
1483    ///
1484    /// If `array` is longer than the attribute's array — `TypedArray.set()`'s
1485    /// `RangeError`.
1486    pub fn copy_array(&mut self, array: &[f32]) -> &mut Self {
1487        let mut target = self.cell().borrow_mut();
1488        assert!(
1489            array.len() <= target.len(),
1490            "three-rs: copy_array(): offset is out of bounds ({} elements into {})",
1491            array.len(),
1492            target.len()
1493        );
1494        if let Some(v) = target.as_f32_mut() {
1495            v[..array.len()].copy_from_slice(array);
1496        } else {
1497            for (i, v) in array.iter().enumerate() {
1498                target.set(i, *v as f64);
1499            }
1500        }
1501        drop(target);
1502        self
1503    }
1504
1505    /// `BufferAttribute.set( value, offset )` — raw elements, with the store's
1506    /// conversion (so on a `Float16BufferAttribute` the values are bits, as in
1507    /// three).
1508    pub fn set(&mut self, value: &[f32], offset: usize) -> &mut Self {
1509        let mut target = self.cell().borrow_mut();
1510        if let Some(v) = target.as_f32_mut() {
1511            v[offset..offset + value.len()].copy_from_slice(value);
1512        } else {
1513            for (i, v) in value.iter().enumerate() {
1514                target.set(offset + i, *v as f64);
1515            }
1516        }
1517        drop(target);
1518        self
1519    }
1520
1521    /// `BufferAttribute.copy( source )` — array (copied), item size and
1522    /// `normalized`; not the id, not the version. An interleaved view copies
1523    /// its buffer reference and offset (`InterleavedBufferAttribute` has no
1524    /// `copy`, so this is what `BufferAttribute.copy` would leave it).
1525    pub fn copy(&mut self, source: &BufferAttribute) -> &mut Self {
1526        self.storage = match &source.storage {
1527            Backing::Own(array) => Backing::Own(RefCell::new(array.borrow().clone())),
1528            Backing::Interleaved { data, offset } => Backing::Interleaved {
1529                data: data.clone(),
1530                offset: *offset,
1531            },
1532            Backing::Storage(storage) => Backing::Own(RefCell::new(storage.array.borrow().clone())),
1533        };
1534        self.item_size = source.item_size;
1535        self.normalized = source.normalized;
1536        self.instanced = source.instanced;
1537        self
1538    }
1539
1540    /// The items as `f32`, `item_size` per item, de-interleaved and read
1541    /// through [`get_component`](Self::get_component) — so a normalized
1542    /// integer array denormalizes and a `Float16` one decodes. For code that
1543    /// hands three's values on as floats whatever the array is; an own
1544    /// `Float32Array` is copied as it is.
1545    pub(crate) fn to_f32_items(&self) -> Vec<f32> {
1546        if let Backing::Own(array) = &self.storage {
1547            if let Some(v) = array.borrow().as_f32() {
1548                return v.clone();
1549            }
1550        }
1551        (0..self.count())
1552            .flat_map(|i| (0..self.item_size).map(move |c| self.get_component(i, c) as f32))
1553            .collect()
1554    }
1555
1556    /// `Vector3.fromBufferAttribute( attribute, index )`.
1557    pub fn get_vector3(&self, index: usize) -> Vector3 {
1558        Vector3::new(self.get_x(index), self.get_y(index), self.get_z(index))
1559    }
1560
1561    /// `BufferAttribute.applyMatrix4()`.
1562    pub fn apply_matrix4(&mut self, m: &Matrix4) {
1563        for i in 0..self.count() {
1564            let mut v = self.get_vector3(i);
1565            v.apply_matrix4(m);
1566            self.set_xyz(i, v.x, v.y, v.z);
1567        }
1568    }
1569
1570    /// `BufferAttribute.applyNormalMatrix()`.
1571    pub fn apply_normal_matrix(&mut self, m: &Matrix3) {
1572        for i in 0..self.count() {
1573            let mut v = self.get_vector3(i);
1574            v.apply_normal_matrix(m);
1575            self.set_xyz(i, v.x, v.y, v.z);
1576        }
1577    }
1578
1579    /// This attribute's items in its own layout and kind, de-interleaved:
1580    /// `item_size` raw elements per item, for every item in `indices` (or all
1581    /// of them).
1582    fn gather_array(&self, indices: Option<&[usize]>) -> TypedArray {
1583        let (stride, offset) = self.layout();
1584        let source = self.cell().borrow();
1585        let n = self.item_size;
1586        let count = indices.map_or(self.count(), <[usize]>::len);
1587        let mut out = TypedArray::zeros(source.kind(), count * n);
1588        for k in 0..count {
1589            let item = indices.map_or(k, |indices| indices[k]);
1590            for c in 0..n {
1591                out.copy_element(k * n + c, &source, offset + item * stride + c);
1592            }
1593        }
1594        out
1595    }
1596
1597    /// `BufferGeometry.toNonIndexed()`'s `convertBufferAttribute()`: a plain
1598    /// attribute of the same kind, item size and `normalized` holding the
1599    /// items at `indices`, in order. An interleaved view is read through its
1600    /// stride, as three's `getComponent` would.
1601    pub(crate) fn gather(&self, indices: &[usize]) -> BufferAttribute {
1602        BufferAttribute::from_typed(
1603            self.gather_array(Some(indices)),
1604            self.item_size,
1605            self.normalized,
1606        )
1607    }
1608
1609    /// `BufferAttribute.clone()` with three's `clone( data )` cache: a view
1610    /// over an [`InterleavedBuffer`] already cloned for this geometry (keyed
1611    /// on its id) shares that clone, so two views stay one buffer — which is
1612    /// what `BufferGeometry.clone()` gets from passing one `data` object to
1613    /// every `attribute.clone( data )`.
1614    pub(crate) fn clone_with(
1615        &self,
1616        buffers: &mut HashMap<usize, Rc<InterleavedBuffer>>,
1617    ) -> BufferAttribute {
1618        match &self.storage {
1619            Backing::Interleaved { data, offset } => {
1620                let data = buffers
1621                    .entry(data.id())
1622                    .or_insert_with(|| Rc::new((**data).clone()))
1623                    .clone();
1624                BufferAttribute::interleaved(data, self.item_size, *offset, self.normalized)
1625            }
1626            _ => self.clone(),
1627        }
1628    }
1629
1630    /// The renderer's key for this attribute's GPU buffer: the attribute's
1631    /// own id, its interleaved buffer's, or its storage buffer's.
1632    pub(crate) fn buffer_key(&self) -> BufferKey {
1633        match &self.storage {
1634            Backing::Own(_) => BufferKey::Attribute(self.id.get()),
1635            Backing::Interleaved { data, .. } => BufferKey::Interleaved(data.id()),
1636            Backing::Storage(storage) => BufferKey::Storage(storage.id()),
1637        }
1638    }
1639
1640    /// The bytes `WebGPUAttributeUtils.createAttribute()` writes for this
1641    /// attribute's GPU buffer: an interleaved buffer's array as it is; an own
1642    /// array widened and padded per decision 3; a storage attribute's padded
1643    /// initial contents.
1644    pub(crate) fn upload_bytes(&self) -> Vec<u8> {
1645        match &self.storage {
1646            Backing::Interleaved { data, .. } => {
1647                let array = data.array.borrow();
1648                array.to_bytes(array.kind(), 1, 1)
1649            }
1650            Backing::Own(array) => {
1651                let array = array.borrow();
1652                let kind = array.kind().upload_kind(self.normalized, false);
1653                let padded = padded_item_size(kind, self.item_size, false);
1654                array.to_bytes(kind, self.item_size, padded)
1655            }
1656            Backing::Storage(storage) => storage
1657                .init_words(self.normalized)
1658                .iter()
1659                .flat_map(|w| w.to_le_bytes())
1660                .collect(),
1661        }
1662    }
1663
1664    /// The vertex-input description of this attribute under `name`, for the
1665    /// node builder — see [`AttributeDesc`]. `group` is the geometry-local
1666    /// index naming this attribute's vertex buffer.
1667    pub(crate) fn desc(&self, name: &str, group: usize) -> AttributeDesc {
1668        let layout = match &self.storage {
1669            Backing::Own(_) => AttributeLayout::Own,
1670            Backing::Interleaved { data, offset } => AttributeLayout::Interleaved {
1671                buffer: group,
1672                stride: data.stride,
1673                offset: *offset,
1674            },
1675            Backing::Storage(storage) => AttributeLayout::Storage {
1676                padded_item_size: storage.padded_item_size(self.normalized),
1677            },
1678        };
1679        AttributeDesc {
1680            name: name.to_string(),
1681            kind: self.kind(),
1682            item_size: self.item_size,
1683            normalized: self.normalized,
1684            instanced: self.is_instanced(),
1685            layout,
1686        }
1687    }
1688}
1689
1690/// `BufferAttribute.clone()` — `new this.constructor( this.array, this.itemSize
1691/// ).copy( this )`: a fresh id, version 0, a copy of the array.
1692///
1693/// An interleaved view is three's `InterleavedBufferAttribute.clone()` with no
1694/// `data` argument, which **de-interleaves**: the clone is a plain attribute
1695/// of the same kind holding just this view's items (three logs a warning; so
1696/// does nothing here). Clone a whole geometry to keep the interleaving — see
1697/// `BufferGeometry`'s `Clone`. A storage attribute's clone is a new storage
1698/// attribute (a new GPU buffer) with a copy of the initial contents.
1699impl Clone for BufferAttribute {
1700    fn clone(&self) -> Self {
1701        let storage = match &self.storage {
1702            Backing::Own(array) => Backing::Own(RefCell::new(array.borrow().clone())),
1703            Backing::Interleaved { .. } => Backing::Own(RefCell::new(self.gather_array(None))),
1704            Backing::Storage(storage) => Backing::Storage(StorageBufferAttribute {
1705                id: BufferId::next(),
1706                array: Rc::new(RefCell::new(storage.array.borrow().clone())),
1707                item_size: storage.item_size,
1708                instanced: storage.instanced,
1709            }),
1710        };
1711        Self {
1712            id: AttributeId::next(),
1713            storage,
1714            item_size: self.item_size,
1715            normalized: self.normalized,
1716            version: Cell::new(0),
1717            instanced: self.instanced,
1718        }
1719    }
1720}
1721
1722/// What the renderer keys a vertex buffer on — see
1723/// [`BufferAttribute::buffer_key`].
1724#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1725pub(crate) enum BufferKey {
1726    /// An attribute with its own array, by [`AttributeId`].
1727    Attribute(usize),
1728    /// An [`InterleavedBuffer`], by its id.
1729    Interleaved(usize),
1730    /// A [`StorageBufferAttribute`]'s storage buffer.
1731    Storage(BufferId),
1732}
1733
1734/// How a [`AttributeDesc`]'s elements are laid out in its vertex buffer.
1735#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1736#[doc(hidden)]
1737pub enum AttributeLayout {
1738    /// Its own buffer, packed, padded per item to a 4-byte stride.
1739    Own,
1740    /// A view into an [`InterleavedBuffer`]. `buffer` is a geometry-local
1741    /// group number — the position in the geometry's attribute list of the
1742    /// first view of the same buffer — so geometries with the same layout
1743    /// hash to the same program; `stride` and `offset` are in elements.
1744    Interleaved {
1745        /// Group number of the shared vertex buffer.
1746        buffer: usize,
1747        /// `InterleavedBuffer.stride`.
1748        stride: usize,
1749        /// `InterleavedBufferAttribute.offset`.
1750        offset: usize,
1751    },
1752    /// A [`StorageBufferAttribute`]'s buffer, `padded_item_size` elements per
1753    /// item.
1754    Storage {
1755        /// Components per element in the GPU buffer.
1756        padded_item_size: usize,
1757    },
1758}
1759
1760/// One geometry attribute as the node builder sees it — `SetupContext::
1761/// geometry_attributes`, decision 4 in the module docs: enough to declare the
1762/// vertex input in the attribute's own type and to lay out its vertex buffer.
1763#[derive(Clone, Debug, PartialEq, Eq, Hash)]
1764#[doc(hidden)]
1765pub struct AttributeDesc {
1766    /// The attribute's name on the geometry.
1767    pub name: String,
1768    /// Element type.
1769    pub kind: ArrayKind,
1770    /// `itemSize`.
1771    pub item_size: usize,
1772    /// `normalized`.
1773    pub normalized: bool,
1774    /// Steps per instance rather than per vertex.
1775    pub instanced: bool,
1776    /// Buffer layout.
1777    pub layout: AttributeLayout,
1778}
1779
1780impl AttributeDesc {
1781    /// `getTypeFromAttribute()` — see [`ArrayKind::shader_type`].
1782    pub fn shader_type(&self) -> Type {
1783        self.kind.shader_type(self.item_size, self.normalized)
1784    }
1785
1786    /// The vertex format — [`ArrayKind::vertex_format`].
1787    pub fn vertex_format(&self) -> wgpu::VertexFormat {
1788        let interleaved = matches!(self.layout, AttributeLayout::Interleaved { .. });
1789        self.kind
1790            .vertex_format(self.item_size, self.normalized, interleaved)
1791            .0
1792    }
1793
1794    /// `arrayStride` of its vertex buffer, in bytes
1795    /// (`createShaderVertexBuffers()`).
1796    pub fn array_stride(&self) -> u64 {
1797        let stride = match self.layout {
1798            AttributeLayout::Own => {
1799                let kind = self.kind.upload_kind(self.normalized, false);
1800                (self.item_size * kind.bytes_per_element()).div_ceil(4) * 4
1801            }
1802            AttributeLayout::Interleaved { stride, .. } => stride * self.kind.bytes_per_element(),
1803            AttributeLayout::Storage { padded_item_size } => {
1804                let kind = self.kind.upload_kind(self.normalized, false);
1805                padded_item_size * kind.bytes_per_element()
1806            }
1807        };
1808        stride as u64
1809    }
1810
1811    /// The attribute's byte offset within each stride.
1812    pub fn offset(&self) -> u64 {
1813        match self.layout {
1814            AttributeLayout::Interleaved { offset, .. } => {
1815                (offset * self.kind.bytes_per_element()) as u64
1816            }
1817            _ => 0,
1818        }
1819    }
1820}