use crate::{Bounds3d, Instance3d, Mesh3d, PickHit3d, Ray3d, pick_mesh};
#[derive(Clone, Debug)]
pub struct Object3d {
pub name: String,
pub mesh_index: usize,
pub instance: Instance3d,
}
impl Object3d {
pub(crate) fn valid_instance(&self) -> bool {
let m = self.instance.model;
m.iter().flatten().all(|v| v.is_finite())
&& m[0][3] == 0.0
&& m[1][3] == 0.0
&& m[2][3] == 0.0
&& m[3][3] == 1.0
&& self.instance.color.iter().all(|v| v.is_finite())
}
}
#[derive(Clone, Debug, Default)]
pub struct Scene3d {
pub meshes: Vec<Mesh3d>,
pub objects: Vec<Object3d>,
}
impl Scene3d {
pub fn validate(&self) -> Result<(), String> {
for (index, mesh) in self.meshes.iter().enumerate() {
if mesh.vertices.is_empty() || mesh.indices.is_empty() {
return Err(format!("网格 {index} 必须包含完整三角形"));
}
if !mesh.indices.len().is_multiple_of(3) {
return Err(format!("网格 {index} 的索引数量必须是 3 的倍数"));
}
if let Some(bad) = mesh
.indices
.iter()
.find(|&&vertex| vertex as usize >= mesh.vertices.len())
{
return Err(format!(
"网格 {index} 的索引 {bad} 越界(共 {} 个顶点)",
mesh.vertices.len()
));
}
if mesh.vertices.iter().any(|v| {
!v.position.into_iter().chain(v.normal).all(f32::is_finite)
|| v.normal.iter().map(|n| n * n).sum::<f32>() <= 1e-16
}) {
return Err(format!("网格 {index} 包含非有限坐标或无效法线"));
}
}
for (index, object) in self.objects.iter().enumerate() {
if object.mesh_index >= self.meshes.len() {
return Err(format!(
"对象 {index} 引用了不存在的网格 {}",
object.mesh_index
));
}
if !object.valid_instance() {
return Err(format!("对象 {index} 包含无效变换或颜色"));
}
}
Ok(())
}
pub fn pick(&self, ray: Ray3d) -> Option<PickHit3d> {
pick_objects(&self.meshes, &self.objects, ray)
}
pub fn bounds(&self, object_index: Option<usize>) -> Option<Bounds3d> {
let mut result: Option<Bounds3d> = None;
for (index, object) in self.objects.iter().enumerate() {
if object_index.is_some_and(|selected| selected != index) {
continue;
}
let Some(mesh) = self.meshes.get(object.mesh_index) else {
continue;
};
if let Some(bounds) = Bounds3d::from_instances(mesh, &[object.instance]) {
result = Some(match result {
None => bounds,
Some(old) => old.union(bounds),
});
}
}
result
}
}
pub fn pick_objects(meshes: &[Mesh3d], objects: &[Object3d], ray: Ray3d) -> Option<PickHit3d> {
let mut closest: Option<PickHit3d> = None;
for (index, object) in objects.iter().enumerate() {
let Some(mesh) = meshes.get(object.mesh_index) else {
continue;
};
if let Some(mut hit) = pick_mesh(mesh, &[object.instance], ray)
&& closest.is_none_or(|previous| hit.distance < previous.distance)
{
hit.instance_index = index;
closest = Some(hit);
}
}
closest
}