1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
//! Port of `three.js/src/objects/InstancedMesh.js` +
//! `src/core/InstancedBufferAttribute.js` (rung 2 subset).
//!
//! `InstancedMesh` extends `Mesh` in three.js; here it holds the `Mesh` payload
//! it extends, and the node's [`Payload`] variant keeps the two apart for the
//! renderer.
use std::rc::Rc;
use crate::core::{BufferGeometry, Node, Object3D};
use crate::materials::MeshBasicNodeMaterial;
use crate::math::{Color, Matrix4, Sphere};
use crate::objects::{Mesh, Payload};
/// `new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 )`.
#[derive(Clone)]
pub struct InstancedBufferAttribute {
/// The `Float32Array` — `count * item_size` values.
pub array: Vec<f32>,
/// `BufferAttribute.itemSize`.
pub item_size: usize,
}
impl InstancedBufferAttribute {
/// `new InstancedBufferAttribute( array, itemSize )`.
pub fn new(array: Vec<f32>, item_size: usize) -> Self {
Self { array, item_size }
}
/// `BufferAttribute.count` — `array.length / itemSize`.
pub fn count(&self) -> usize {
self.array.len() / self.item_size
}
}
/// `InstancedMesh extends Mesh`: one geometry and material, drawn `count`
/// times with a per-instance transform (and optionally colour).
#[derive(Clone)]
pub struct InstancedMesh {
/// The `Mesh` half: geometry, material and morph state.
pub mesh: Mesh,
/// `InstancedMesh.count` — the number of instances the renderer draws.
pub count: usize,
/// `InstancedMesh.instanceMatrix`.
pub instance_matrix: InstancedBufferAttribute,
/// `InstancedMesh.instanceColor`, `null` until `setColorAt()` is called.
pub instance_color: Option<InstancedBufferAttribute>,
/// `InstancedMesh.boundingSphere` — the object's *own* bounding sphere, in
/// object space, over all of its instances.
///
/// `Frustum.intersectsObject` prefers it to the geometry's whenever the
/// object declares one (`object.boundingSphere !== undefined` in three.js),
/// which is the only thing that keeps an instanced draw whose instances are
/// spread out from being culled as a point at the object's origin.
/// `None` is three.js' `null`: nothing has computed it yet, so the
/// geometry's sphere is used instead.
pub bounding_sphere: Option<Sphere>,
}
impl InstancedMesh {
/// `new InstancedMesh( geometry, material, count )`, as a scene-graph [`Node`].
#[allow(clippy::new_ret_no_self)] // `new` mirrors three.js's constructor and returns a scene-graph `Node`, not `Self`; public API, not changing.
pub fn new(
geometry: Rc<BufferGeometry>,
material: MeshBasicNodeMaterial,
count: usize,
) -> Node {
let mut object = Object3D {
object_type: "InstancedMesh",
..Default::default()
};
let mut instanced = Self {
mesh: Mesh {
geometry,
material: Some(material),
materials: Vec::new(),
morph_target_influences: Vec::new(),
line_segments: None,
count: None,
},
count,
instance_matrix: InstancedBufferAttribute::new(vec![0.0; count * 16], 16),
instance_color: None,
bounding_sphere: None,
};
// `for ( let i = 0; i < count; i ++ ) this.setMatrixAt( i, _identity );`
// — the constructor's last step. A mesh whose instances are never placed
// still draws at the origin, not collapsed to a zero matrix.
let identity = Matrix4::identity();
for i in 0..count {
instanced.set_matrix_at(i, &identity);
}
object.payload = Payload::InstancedMesh(instanced);
object.into_node()
}
/// `InstancedMesh.getMatrixAt( index, matrix )` —
/// `matrix.fromArray( this.instanceMatrix.array, index * 16 )`.
pub fn matrix_at(&self, index: usize) -> Matrix4 {
let offset = index * 16;
let mut matrix = Matrix4::identity();
for (e, &a) in matrix
.elements
.iter_mut()
.zip(&self.instance_matrix.array[offset..offset + 16])
{
*e = a as f64;
}
matrix
}
/// `InstancedMesh.computeBoundingSphere()` — the geometry's sphere pushed
/// through every instance matrix, unioned. `count` instances, not the
/// array's capacity, exactly as three.js does.
///
/// A geometry with no position attribute has no sphere to spread, so this
/// leaves [`InstancedMesh::bounding_sphere`] alone; three.js would throw.
pub fn compute_bounding_sphere(&mut self) {
let Some(geometry_sphere) = self.mesh.geometry.compute_bounding_sphere() else {
return;
};
let mut bounding_sphere = Sphere::default();
bounding_sphere.make_empty();
for i in 0..self.count {
let mut sphere = Sphere::new(geometry_sphere.center, geometry_sphere.radius);
sphere.apply_matrix4(&self.matrix_at(i));
bounding_sphere.union(&sphere);
}
self.bounding_sphere = Some(bounding_sphere);
}
/// `InstancedMesh.raycast( raycaster, intersects )` — the object's own
/// bounding sphere first, then `Mesh.raycast()` once per instance with
/// `matrixWorld × instanceMatrix`, each hit tagged with its `instanceId`.
///
/// three.js raycasts each instance through a scratch `Mesh` that has no
/// `morphTargetInfluences`, so morph targets are ignored here too.
pub fn raycast(
&mut self,
matrix_world: &Matrix4,
object: &crate::core::Node,
raycaster: &crate::core::Raycaster,
intersects: &mut Vec<crate::core::Intersection>,
) {
// Test with the bounding sphere first.
if self.bounding_sphere.is_none() {
self.compute_bounding_sphere();
}
let Some(mut sphere) = self.bounding_sphere else {
return;
};
sphere.apply_matrix4(matrix_world);
if !raycaster.ray.intersects_sphere(&sphere) {
return;
}
let geometry = &self.mesh.geometry;
let Some(geometry_sphere) = geometry.compute_bounding_sphere() else {
return;
};
let geometry_sphere = Sphere::new(geometry_sphere.center, geometry_sphere.radius);
let side = self
.mesh
.material
.as_ref()
.map_or(crate::materials::Side::Front, |m| m.side);
// Now test each instance.
let mut instance_intersects = Vec::new();
for instance_id in 0..self.count {
// The world matrix of this instance; the mesh represents it alone.
let mut instance_world_matrix = Matrix4::identity();
instance_world_matrix.multiply_matrices(matrix_world, &self.matrix_at(instance_id));
let target = crate::objects::mesh::MeshRaycast {
geometry,
side,
matrix_world: instance_world_matrix,
draw_start: geometry.draw_range.start,
draw_count: geometry.draw_range.count,
vertex_position: &|index| {
crate::objects::mesh::vertex_position(geometry, &[], index)
},
};
target.raycast(
&geometry_sphere,
None,
object,
raycaster,
&mut instance_intersects,
);
for mut intersect in instance_intersects.drain(..) {
intersect.instance_id = Some(instance_id);
intersects.push(intersect);
}
}
}
/// `InstancedMesh.setColorAt( index, color )`.
///
/// The array is allocated on the first call and **filled with 1**, not 0,
/// so an instance that is never given a colour keeps the material's own —
/// `new Float32Array( count * 3 ).fill( 1 )` in three.js.
///
/// The colour is stored in the working (linear-sRGB) space the `Color`
/// already holds; three.js writes `color.toArray()`, which is the same.
pub fn set_color_at(&mut self, index: usize, color: &Color) {
let colors = self.instance_color.get_or_insert_with(|| {
InstancedBufferAttribute::new(vec![1.0; self.instance_matrix.count() * 3], 3)
});
let offset = index * 3;
colors.array[offset] = color.r as f32;
colors.array[offset + 1] = color.g as f32;
colors.array[offset + 2] = color.b as f32;
}
/// `InstancedMesh.setMatrixAt( index, matrix )` —
/// `matrix.toArray( this.instanceMatrix.array, index * 16 )`.
pub fn set_matrix_at(&mut self, index: usize, matrix: &Matrix4) {
let offset = index * 16;
let elements = matrix.to_f32_array();
self.instance_matrix.array[offset..offset + 16].copy_from_slice(&elements);
}
}
/// The array is `count * item_size` floats — sixteen per instance for the
/// instance matrix. Debug prints its length, as the textures do.
impl std::fmt::Debug for InstancedBufferAttribute {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("InstancedBufferAttribute")
.field("array", &format_args!("{} floats", self.array.len()))
.field("item_size", &self.item_size)
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::geometries::plane_geometry;
use crate::objects::Payload;
/// Two instances ten units either side of the origin: the object's own
/// sphere has to span both, where the geometry's spans one unit plane at
/// the origin. This is the difference that decides whether a spread-out
/// instanced draw survives the frustum cull.
#[test]
fn compute_bounding_sphere_spans_the_instances() {
let node = InstancedMesh::new(
Rc::new(plane_geometry(1.0, 1.0, 1, 1)),
MeshBasicNodeMaterial::default(),
2,
);
let half_diagonal = (0.5f64 * 0.5 + 0.5 * 0.5).sqrt();
{
let mut object = node.borrow_mut();
let instanced = object
.payload
.instanced_mesh_mut()
.expect("InstancedMesh::new makes an InstancedMesh payload");
let mut left = Matrix4::identity();
left.set_position(-10.0, 0.0, 0.0);
let mut right = Matrix4::identity();
right.set_position(10.0, 0.0, 0.0);
instanced.set_matrix_at(0, &left);
instanced.set_matrix_at(1, &right);
// Before `computeBoundingSphere`, `boundingSphere` is null and the
// geometry's sphere stands in — the unit plane at the origin.
assert!(instanced.bounding_sphere.is_none());
instanced.compute_bounding_sphere();
let sphere = instanced
.bounding_sphere
.expect("compute_bounding_sphere sets it for a geometry with positions");
assert!(sphere.center.x.abs() < 1e-12);
assert!((sphere.radius - (10.0 + half_diagonal)).abs() < 1e-12);
}
// And the payload hands that sphere to the cull, not the geometry's.
let object = node.borrow();
let sphere = object
.payload
.bounding_sphere_in(&object.matrix_world)
.expect("a plane has a bounding sphere");
assert!((sphere.radius - (10.0 + half_diagonal)).abs() < 1e-12);
// The same payload with no sphere of its own falls back to the
// geometry's, as three.js does.
let plain = InstancedMesh::new(
Rc::new(plane_geometry(1.0, 1.0, 1, 1)),
MeshBasicNodeMaterial::default(),
2,
);
let plain = plain.borrow();
let Payload::InstancedMesh(instanced) = &plain.payload else {
panic!("InstancedMesh::new makes an InstancedMesh payload");
};
assert!(instanced.bounding_sphere.is_none());
let sphere = plain
.payload
.bounding_sphere_in(&plain.matrix_world)
.expect("a plane has a bounding sphere");
assert!((sphere.radius - half_diagonal).abs() < 1e-12);
}
}