arc-graphics3d 0.4.0

Experimental standalone wgpu 3D renderer with orbit camera, OBJ geometry, multi-mesh scenes, picking and framing.
Documentation
//! 本地设计:多网格资源与对象引用。几何资源可复用,拾取索引始终对应 objects。

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 {
    /// 渲染前校验资源引用和三角形数据,错误不会传入 GPU。
    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)
    }

    /// None 为全场景;Some 为单对象,避免误用立方体包围盒。
    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
    }
}

/// 在借用形式上做拾取,避免调用方为了查询而克隆整份网格。
///
/// `PickHit3d::instance_index` 始终对应 `objects` 下标;遍历顺序不影响结果,
/// 网格级 BVH 在 `Mesh3d` 内部缓存,重复拾取不会重建。
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
}