use std::cell::Cell;
use std::rc::Rc;
use crate::core::{BufferAttribute, BufferGeometry, ObjectRef};
use crate::materials::LineBasicNodeMaterial;
use crate::math::{Box3, Color};
use crate::objects::LineSegments;
thread_local! {
static BOX: Cell<Box3> = Cell::new(Box3::default());
}
pub struct BoxHelper {
pub node: ObjectRef,
pub object: Option<ObjectRef>,
}
impl BoxHelper {
pub fn new(object: Option<ObjectRef>, color: Color) -> Self {
#[rustfmt::skip]
let indices = [
0, 1, 1, 2, 2, 3, 3, 0,
4, 5, 5, 6, 6, 7, 7, 4,
0, 4, 1, 5, 2, 6, 3, 7,
];
let mut geometry = BufferGeometry::new();
geometry.set_index(&indices);
geometry.set_attribute("position", BufferAttribute::new(vec![0.0; 8 * 3], 3));
let node = LineSegments::new(Rc::new(geometry), LineBasicNodeMaterial::line(color));
{
let mut helper = node.borrow_mut();
helper.object_type = "BoxHelper";
helper.matrix_auto_update = false;
}
let helper = Self { node, object };
helper.update();
helper
}
pub fn update(&self) {
let mut bounds = BOX.with(Cell::get);
if let Some(object) = &self.object {
bounds.set_from_object(object, false);
BOX.with(|b| b.set(bounds));
}
if bounds.is_empty() {
return;
}
let (min, max) = (bounds.min, bounds.max);
#[rustfmt::skip]
let corners = [
max.x, max.y, max.z,
min.x, max.y, max.z,
min.x, min.y, max.z,
max.x, min.y, max.z,
max.x, max.y, min.z,
min.x, max.y, min.z,
min.x, min.y, min.z,
max.x, min.y, min.z,
];
let geometry = self
.node
.borrow()
.geometry()
.expect("three-rs: a BoxHelper is a LineSegments")
.clone();
let position = geometry
.get_attribute("position")
.expect("three-rs: the helper has a position attribute");
{
let mut array = position.array_mut();
for (slot, value) in array.iter_mut().zip(corners) {
*slot = value as f32;
}
}
position.set_needs_update();
}
pub fn set_from_object(&mut self, object: ObjectRef) -> &mut Self {
self.object = Some(object);
self.update();
self
}
}
impl Default for BoxHelper {
fn default() -> Self {
Self::new(None, Color::from_hex(0xffff00))
}
}