use std::rc::Rc;
use crate::core::{AttributeId, BufferGeometry, Object3D, ObjectRef};
use crate::materials::MeshBasicNodeMaterial;
use crate::math::{Color, Matrix4, Sphere};
use crate::objects::{Mesh, Payload};
#[derive(Clone)]
pub struct InstancedBufferAttribute {
id: AttributeId,
array: Rc<Vec<f32>>,
pub item_size: usize,
version: u32,
}
impl InstancedBufferAttribute {
pub fn new(array: Vec<f32>, item_size: usize) -> Self {
Self {
id: AttributeId::default(),
array: Rc::new(array),
item_size,
version: 0,
}
}
pub fn id(&self) -> usize {
self.id.get()
}
pub fn array(&self) -> &[f32] {
&self.array
}
pub fn array_mut(&mut self) -> &mut [f32] {
self.version += 1;
Rc::make_mut(&mut self.array).as_mut_slice()
}
pub fn version(&self) -> u32 {
self.version
}
pub fn set_needs_update(&mut self) {
self.version += 1;
}
pub fn count(&self) -> usize {
self.array.len() / self.item_size
}
fn write(&mut self, offset: usize, values: &[f32]) {
let range = offset..offset + values.len();
if self.array[range.clone()] != *values {
self.array_mut()[range].copy_from_slice(values);
}
}
pub(crate) fn snapshot(&self) -> InstanceData {
InstanceData {
id: self.id(),
version: self.version,
array: self.array.clone(),
item_size: self.item_size,
}
}
}
#[derive(Clone)]
pub(crate) struct InstanceData {
pub id: usize,
pub version: u32,
pub array: Rc<Vec<f32>>,
pub item_size: usize,
}
impl InstanceData {
pub fn count(&self) -> usize {
self.array.len() / self.item_size
}
}
#[derive(Clone)]
pub struct InstancedMesh {
pub mesh: Mesh,
pub count: usize,
pub instance_matrix: InstancedBufferAttribute,
pub instance_color: Option<InstancedBufferAttribute>,
pub bounding_sphere: Option<Sphere>,
}
impl InstancedMesh {
#[allow(clippy::new_ret_no_self)] pub fn new(
geometry: Rc<BufferGeometry>,
material: MeshBasicNodeMaterial,
count: usize,
) -> ObjectRef {
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,
};
let identity = Matrix4::identity();
for i in 0..count {
instanced.set_matrix_at(i, &identity);
}
object.payload = Payload::InstancedMesh(instanced);
object.into_node()
}
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
}
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);
}
pub fn raycast(
&mut self,
matrix_world: &Matrix4,
object: &crate::core::ObjectRef,
raycaster: &crate::core::Raycaster,
intersects: &mut Vec<crate::core::Intersection>,
) {
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);
let mut instance_intersects = Vec::new();
for instance_id in 0..self.count {
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);
}
}
}
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)
});
colors.write(index * 3, &[color.r as f32, color.g as f32, color.b as f32]);
}
pub fn set_matrix_at(&mut self, index: usize, matrix: &Matrix4) {
self.instance_matrix
.write(index * 16, &matrix.to_f32_array());
}
}
impl std::fmt::Debug for InstancedBufferAttribute {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("InstancedBufferAttribute")
.field("id", &self.id())
.field("array", &format_args!("{} floats", self.array.len()))
.field("item_size", &self.item_size)
.field("version", &self.version)
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::geometries::plane_geometry;
use crate::objects::Payload;
#[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);
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);
}
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);
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);
}
}