use bytemuck::{Pod, Zeroable};
use wgpu::util::DeviceExt;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Camera3d {
pub eye: [f32; 3],
pub target: [f32; 3],
pub up: [f32; 3],
pub fov_y_radians: f32,
pub near: f32,
pub far: f32,
}
impl Default for Camera3d {
fn default() -> Self {
Self {
eye: [2.8, 2.2, 4.8],
target: [0.0, 0.5, 0.0],
up: [0.0, 1.0, 0.0],
fov_y_radians: 0.75,
near: 0.1,
far: 100.0,
}
}
}
impl Camera3d {
pub fn orbit(target: [f32; 3], yaw: f32, pitch: f32, distance: f32) -> Self {
let cos_pitch = pitch.cos();
let eye = [
target[0] + distance * cos_pitch * yaw.sin(),
target[1] + distance * pitch.sin(),
target[2] + distance * cos_pitch * yaw.cos(),
];
Self {
eye,
target,
up: [0.0, 1.0, 0.0],
..Self::default()
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DirectionalLight {
pub direction: [f32; 3],
pub color: [f32; 3],
pub intensity: f32,
}
impl Default for DirectionalLight {
fn default() -> Self {
Self {
direction: [-0.5, -1.0, -0.4],
color: [1.0, 1.0, 1.0],
intensity: 1.0,
}
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Pod, Zeroable)]
pub struct Vertex3d {
pub position: [f32; 3],
pub normal: [f32; 3],
}
impl Vertex3d {
pub const ATTRIBS: [wgpu::VertexAttribute; 2] = wgpu::vertex_attr_array![
0 => Float32x3,
1 => Float32x3,
];
pub fn layout<'a>() -> wgpu::VertexBufferLayout<'a> {
wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<Self>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &Self::ATTRIBS,
}
}
}
#[derive(Clone, Debug, Default)]
pub struct Mesh3d {
pub vertices: Vec<Vertex3d>,
pub indices: Vec<u32>,
accel: std::sync::Arc<MeshAccel>,
}
#[derive(Debug, Default)]
struct MeshAccel {
bounds: Option<Bounds3d>,
bvh: std::sync::OnceLock<std::sync::Arc<super::bvh::Bvh3d>>,
}
impl MeshAccel {
fn new(vertices: &[Vertex3d]) -> Self {
Self {
bounds: local_bounds(vertices),
bvh: std::sync::OnceLock::new(),
}
}
fn bvh(&self, vertices: &[Vertex3d], indices: &[u32]) -> &std::sync::Arc<super::bvh::Bvh3d> {
self.bvh
.get_or_init(|| std::sync::Arc::new(super::bvh::Bvh3d::build(vertices, indices)))
}
}
impl PartialEq for Mesh3d {
fn eq(&self, other: &Self) -> bool {
self.vertices == other.vertices && self.indices == other.indices
}
}
impl Mesh3d {
pub fn new(vertices: Vec<Vertex3d>) -> Self {
let indices = if vertices.len().is_multiple_of(3) {
(0..vertices.len() as u32).collect()
} else {
Vec::new()
};
Self::indexed(vertices, indices)
}
pub fn indexed(vertices: Vec<Vertex3d>, indices: Vec<u32>) -> Self {
Self {
accel: std::sync::Arc::new(MeshAccel::new(&vertices)),
vertices,
indices,
}
}
pub fn triangle_count(&self) -> usize {
self.indices.len() / 3
}
pub fn local_bounds(&self) -> Option<Bounds3d> {
self.accel.bounds
}
pub fn bvh(&self) -> &super::bvh::Bvh3d {
self.accel.bvh(&self.vertices, &self.indices)
}
pub fn update_vertices(&mut self, vertices: Vec<Vertex3d>) -> bool {
let same_shape = vertices.len() == self.vertices.len();
let mut refitted = false;
if same_shape && let Some(existing) = self.accel.bvh.get() {
let mut tree = (**existing).clone();
if tree.refit(&vertices, &self.indices) {
self.accel = std::sync::Arc::new(MeshAccel {
bounds: local_bounds(&vertices),
bvh: std::sync::OnceLock::from(std::sync::Arc::new(tree)),
});
refitted = true;
}
}
if !refitted {
self.accel = std::sync::Arc::new(MeshAccel::new(&vertices));
}
self.vertices = vertices;
refitted
}
}
impl Mesh3d {
pub fn cube() -> Self {
const FACES: [([f32; 3], [f32; 3], [f32; 3]); 6] = [
([1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]),
([-1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]),
([0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]),
([0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]),
([0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]),
([0.0, 0.0, -1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]),
];
let mut vertices = Vec::with_capacity(24);
let mut indices = Vec::with_capacity(36);
for &(n, t, b) in &FACES {
let center = [n[0] * 0.5, n[1] * 0.5, n[2] * 0.5];
let corner = |st: f32, sb: f32| -> [f32; 3] {
[
center[0] + (t[0] * st + b[0] * sb) * 0.5,
center[1] + (t[1] * st + b[1] * sb) * 0.5,
center[2] + (t[2] * st + b[2] * sb) * 0.5,
]
};
let base = vertices.len() as u32;
for (st, sb) in [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)] {
vertices.push(Vertex3d {
position: corner(st, sb),
normal: n,
});
}
indices.extend([base, base + 1, base + 2, base, base + 2, base + 3]);
}
Self::indexed(vertices, indices)
}
pub fn triangle() -> Self {
Self::indexed(
vec![
Vertex3d {
position: [-1.0, -1.0, 0.0],
normal: [0.0, 0.0, 1.0],
},
Vertex3d {
position: [1.0, -1.0, 0.0],
normal: [0.0, 0.0, 1.0],
},
Vertex3d {
position: [0.0, 1.0, 0.0],
normal: [0.0, 0.0, 1.0],
},
],
vec![0, 1, 2],
)
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct Instance3d {
pub model: [[f32; 4]; 4],
pub color: [f32; 4],
}
impl Default for Instance3d {
fn default() -> Self {
Self {
model: identity(),
color: [0.22, 0.50, 0.94, 1.0],
}
}
}
impl Instance3d {
pub fn trs(pos: [f32; 3], yaw: f32, pitch: f32, scale: [f32; 3], base_color: [f32; 4]) -> Self {
Self {
model: trs_matrix(pos, yaw, pitch, scale),
color: base_color,
}
}
}
pub fn trs_matrix(pos: [f32; 3], yaw: f32, pitch: f32, scale: [f32; 3]) -> [[f32; 4]; 4] {
let (sy, cy) = yaw.sin_cos();
let (sp, cp) = pitch.sin_cos();
let col0 = [cy, 0.0, -sy];
let col1 = [sy * sp, cp, cy * sp];
let col2 = [sy * cp, -sp, cy * cp];
[
[
col0[0] * scale[0],
col0[1] * scale[0],
col0[2] * scale[0],
0.0,
],
[
col1[0] * scale[1],
col1[1] * scale[1],
col1[2] * scale[1],
0.0,
],
[
col2[0] * scale[2],
col2[1] * scale[2],
col2[2] * scale[2],
0.0,
],
[pos[0], pos[1], pos[2], 1.0],
]
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Material3d {
pub base_color: [f32; 4],
}
impl Default for Material3d {
fn default() -> Self {
Self {
base_color: [0.22, 0.50, 0.94, 1.0],
}
}
}
#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
struct CameraUniform {
view_proj: [[f32; 4]; 4],
light_direction: [f32; 4],
light_color: [f32; 4],
}
#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
struct InstanceGpu {
model: [[f32; 4]; 4],
normal: [[f32; 4]; 3],
color: [f32; 4],
}
#[derive(Clone, Debug, PartialEq)]
struct DrawBatch {
vertices: std::ops::Range<u32>,
instances: std::ops::Range<u32>,
}
pub struct Renderer3d {
device: wgpu::Device,
queue: wgpu::Queue,
format: wgpu::TextureFormat,
pipeline: wgpu::RenderPipeline,
camera_buffer: wgpu::Buffer,
camera_bind_group: wgpu::BindGroup,
vertex_buffer: wgpu::Buffer,
index_buffer: wgpu::Buffer,
instance_buffer: wgpu::Buffer,
instance_bind_group: wgpu::BindGroup,
depth_format: wgpu::TextureFormat,
index_count: u32,
instance_count: u32,
batches: Vec<DrawBatch>,
instance_bounds: Vec<Bounds3d>,
mesh_bounds: Vec<Option<Bounds3d>>,
single_bounds: Option<Bounds3d>,
mesh_ranges: Vec<std::ops::Range<u32>>,
}
impl Renderer3d {
pub async fn new(
device: wgpu::Device,
queue: wgpu::Queue,
format: wgpu::TextureFormat,
mesh: &Mesh3d,
max_instances: usize,
) -> Self {
let depth_format = wgpu::TextureFormat::Depth32Float;
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("arc-graphics3d.shader"),
source: wgpu::ShaderSource::Wgsl(SHADER.into()),
});
let camera_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("arc-graphics3d.camera"),
size: std::mem::size_of::<CameraUniform>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let camera_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("arc-graphics3d.camera-layout"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: wgpu::BufferSize::new(
std::mem::size_of::<CameraUniform>() as u64
),
},
count: None,
}],
});
let camera_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("arc-graphics3d.camera-bind-group"),
layout: &camera_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: camera_buffer.as_entire_binding(),
}],
});
let instance_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("arc-graphics3d.instance-layout"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: wgpu::BufferSize::new(
std::mem::size_of::<InstanceGpu>() as u64
),
},
count: None,
}],
});
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("arc-graphics3d.pipeline-layout"),
bind_group_layouts: &[Some(&camera_layout), Some(&instance_layout)],
immediate_size: 0,
});
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("arc-graphics3d.pipeline"),
layout: Some(&layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
compilation_options: Default::default(),
buffers: &[Some(Vertex3d::layout())],
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
primitive: wgpu::PrimitiveState {
cull_mode: Some(wgpu::Face::Back),
..Default::default()
},
depth_stencil: Some(wgpu::DepthStencilState {
format: depth_format,
depth_write_enabled: Some(true),
depth_compare: Some(wgpu::CompareFunction::Less),
stencil: Default::default(),
bias: Default::default(),
}),
multisample: Default::default(),
multiview_mask: None,
cache: None,
});
let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("arc-graphics3d.vertices"),
contents: bytemuck::cast_slice(if mesh.vertices.is_empty() {
&[Vertex3d {
position: [0.0; 3],
normal: [0.0, 1.0, 0.0],
}]
} else {
&mesh.vertices
}),
usage: wgpu::BufferUsages::VERTEX,
});
let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("arc-graphics3d.indices"),
contents: bytemuck::cast_slice(if mesh.indices.is_empty() {
&[0u32]
} else {
&mesh.indices
}),
usage: wgpu::BufferUsages::INDEX,
});
let instance_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("arc-graphics3d.instances"),
size: (max_instances.max(1) * std::mem::size_of::<InstanceGpu>()) as u64,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let instance_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("arc-graphics3d.instance-bind-group"),
layout: &instance_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: instance_buffer.as_entire_binding(),
}],
});
Self {
device,
queue,
format,
pipeline,
camera_buffer,
camera_bind_group,
vertex_buffer,
index_buffer,
instance_buffer,
instance_bind_group,
depth_format,
index_count: mesh.indices.len() as u32,
instance_count: 0,
batches: Vec::new(),
instance_bounds: Vec::new(),
mesh_bounds: Vec::new(),
single_bounds: mesh.local_bounds(),
mesh_ranges: Vec::new(),
}
}
pub fn set_camera(&self, camera: Camera3d, light: DirectionalLight, aspect: f32) {
let view = look_at(camera.eye, camera.target, camera.up);
let projection = perspective(
camera.fov_y_radians,
aspect.max(0.001),
camera.near,
camera.far,
);
let uniform = CameraUniform {
view_proj: mul4(projection, view),
light_direction: [
light.direction[0],
light.direction[1],
light.direction[2],
0.0,
],
light_color: [
light.color[0],
light.color[1],
light.color[2],
light.intensity,
],
};
self.queue
.write_buffer(&self.camera_buffer, 0, bytemuck::bytes_of(&uniform));
}
pub fn frustum(&self, camera: Camera3d, aspect: f32) -> Frustum3d {
Frustum3d::from_view_projection(mul4(
perspective(
camera.fov_y_radians,
aspect.max(0.001),
camera.near,
camera.far,
),
look_at(camera.eye, camera.target, camera.up),
))
}
pub fn set_scene(&mut self, scene: &crate::Scene3d) -> Result<(), String> {
scene.validate()?;
let mut vertices: Vec<Vertex3d> = Vec::new();
let mut indices: Vec<u32> = Vec::new();
let mut ranges = Vec::with_capacity(scene.meshes.len());
for mesh in &scene.meshes {
let base = vertices.len() as u32;
if u32::MAX - base < mesh.vertices.len() as u32 {
return Err("场景顶点超出绘制范围".into());
}
let start = indices.len() as u32;
vertices.extend_from_slice(&mesh.vertices);
indices.extend(mesh.indices.iter().map(|index| index + base));
ranges.push(start..indices.len() as u32);
}
let fallback = [Vertex3d {
position: [0.0; 3],
normal: [0.0, 1.0, 0.0],
}];
self.vertex_buffer = self
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("arc-graphics3d.scene-vertices"),
contents: bytemuck::cast_slice(if vertices.is_empty() {
&fallback
} else {
&vertices
}),
usage: wgpu::BufferUsages::VERTEX,
});
self.index_buffer = self
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("arc-graphics3d.scene-indices"),
contents: bytemuck::cast_slice(if indices.is_empty() {
&[0u32]
} else {
&indices
}),
usage: wgpu::BufferUsages::INDEX,
});
self.mesh_ranges = ranges;
self.mesh_bounds = scene.meshes.iter().map(Mesh3d::local_bounds).collect();
self.index_count = indices.len() as u32;
self.update_scene_objects(&scene.objects)
}
pub fn update_scene_objects(&mut self, objects: &[crate::Object3d]) -> Result<(), String> {
if objects.iter().any(|o| !o.valid_instance()) {
return Err("对象包含无效变换或颜色".into());
}
if objects
.iter()
.any(|o| o.mesh_index >= self.mesh_ranges.len())
{
return Err("对象引用了不存在的 GPU 网格".into());
}
let mut order: Vec<usize> = (0..objects.len()).collect();
order.sort_by_key(|index| objects[*index].mesh_index);
let mut instances = Vec::with_capacity(objects.len());
let mut bounds = Vec::with_capacity(objects.len());
for &index in &order {
let object = &objects[index];
instances.push(object.instance);
bounds.push(
self.mesh_world_bounds(object.mesh_index, &object.instance)
.unwrap_or(Bounds3d {
min: [0.0; 3],
max: [0.0; 3],
}),
);
}
self.batches = Self::build_batches(&order, objects, &self.mesh_ranges);
self.instance_bounds = bounds;
self.upload_instances(&instances);
Ok(())
}
fn build_batches(
order: &[usize],
objects: &[crate::Object3d],
mesh_ranges: &[std::ops::Range<u32>],
) -> Vec<DrawBatch> {
let mut batches: Vec<DrawBatch> = Vec::new();
let mut start = 0u32;
while (start as usize) < order.len() {
let mesh_index = objects[order[start as usize]].mesh_index;
let mut end = start as usize + 1;
while end < order.len() && objects[order[end]].mesh_index == mesh_index {
end += 1;
}
if let Some(vertices) = mesh_ranges.get(mesh_index) {
batches.push(DrawBatch {
vertices: vertices.clone(),
instances: start..end as u32,
});
}
start = end as u32;
}
batches
}
fn mesh_world_bounds(&self, mesh_index: usize, instance: &Instance3d) -> Option<Bounds3d> {
let local = self
.mesh_bounds
.get(mesh_index)
.copied()
.flatten()
.or(self.single_bounds)?;
local.transformed(instance.model)
}
pub fn update_instances(&mut self, instances: &[Instance3d]) {
self.batches = vec![DrawBatch {
vertices: 0..self.index_count,
instances: 0..instances.len() as u32,
}];
self.instance_bounds = instances
.iter()
.map(|instance| {
self.single_bounds
.and_then(|local| local.transformed(instance.model))
.unwrap_or(Bounds3d {
min: [0.0; 3],
max: [0.0; 3],
})
})
.collect();
self.upload_instances(instances);
}
fn upload_instances(&mut self, instances: &[Instance3d]) {
let required = (instances.len().max(1) * std::mem::size_of::<InstanceGpu>()) as u64;
if required > self.instance_buffer.size() {
self.instance_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("arc-graphics3d.instances-grown"),
size: required,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
self.instance_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("arc-graphics3d.instance-bind-group"),
layout: &self.pipeline.get_bind_group_layout(1),
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: self.instance_buffer.as_entire_binding(),
}],
});
}
let gpu: Vec<_> = instances
.iter()
.map(|instance| InstanceGpu {
model: instance.model,
normal: normal_matrix(instance.model),
color: instance.color,
})
.collect();
self.queue
.write_buffer(&self.instance_buffer, 0, bytemuck::cast_slice(&gpu));
self.instance_count = gpu.len() as u32;
}
pub fn batch_count(&self) -> usize {
self.batches.len()
}
pub fn plan_draws(
&self,
frustum: Option<&Frustum3d>,
) -> Vec<(std::ops::Range<u32>, std::ops::Range<u32>)> {
let mut plan = Vec::with_capacity(self.batches.len());
for batch in &self.batches {
let Some(frustum) = frustum else {
plan.push((batch.vertices.clone(), batch.instances.clone()));
continue;
};
let mut run: Option<u32> = None;
for index in batch.instances.clone() {
let visible = self
.instance_bounds
.get(index as usize)
.is_none_or(|bounds| bounds.is_visible(frustum));
match (visible, run) {
(true, None) => run = Some(index),
(false, Some(begin)) => {
plan.push((batch.vertices.clone(), begin..index));
run = None;
}
_ => {}
}
}
if let Some(begin) = run {
plan.push((batch.vertices.clone(), begin..batch.instances.end));
}
}
plan
}
pub fn create_offscreen_target(
&self,
width: u32,
height: u32,
) -> (wgpu::Texture, wgpu::TextureView, wgpu::TextureView) {
let color = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("arc-graphics3d.color"),
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: self.format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let depth = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("arc-graphics3d.depth"),
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: self.depth_format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
});
let color_view = color.create_view(&Default::default());
(color, color_view, depth.create_view(&Default::default()))
}
pub fn render(&self, color: &wgpu::TextureView, depth: &wgpu::TextureView, clear: wgpu::Color) {
self.render_visible(color, depth, clear, None);
}
pub fn render_visible(
&self,
color: &wgpu::TextureView,
depth: &wgpu::TextureView,
clear: wgpu::Color,
frustum: Option<&Frustum3d>,
) {
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("arc-graphics3d.frame"),
});
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("arc-graphics3d.pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: color,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(clear),
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: depth,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
if self.instance_count > 0 {
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, &self.camera_bind_group, &[]);
pass.set_bind_group(1, &self.instance_bind_group, &[]);
pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
for (vertices, instances) in self.plan_draws(frustum) {
if !instances.is_empty() {
pass.draw_indexed(vertices, 0, instances);
}
}
}
drop(pass);
self.queue.submit(Some(encoder.finish()));
}
pub fn device_queue(&self) -> (&wgpu::Device, &wgpu::Queue) {
(&self.device, &self.queue)
}
}
pub fn capture_rgba(
device: &wgpu::Device,
queue: &wgpu::Queue,
texture: &wgpu::Texture,
width: u32,
height: u32,
) -> (Vec<u8>, u32) {
let bytes_per_row = width.div_ceil(64) * 256;
let readback = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("arc-graphics3d.readback"),
size: (bytes_per_row * height) as u64,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("arc-graphics3d.readback-enc"),
});
encoder.copy_texture_to_buffer(
texture.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &readback,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(bytes_per_row),
rows_per_image: None,
},
},
wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
);
queue.submit(Some(encoder.finish()));
let slice = readback.slice(..);
slice.map_async(wgpu::MapMode::Read, |_| {});
device
.poll(wgpu::PollType::wait_indefinitely())
.expect("读取回传失败");
let mapped = slice.get_mapped_range().expect("映射回传缓冲失败");
let data = mapped.to_vec();
drop(mapped); readback.unmap();
(data, bytes_per_row)
}
const SHADER: &str = r#"
struct Camera { view_proj: mat4x4<f32>, light_direction: vec4<f32>, light_color: vec4<f32> };
@group(0) @binding(0) var<uniform> camera: Camera;
struct Instance { model: mat4x4<f32>, normal_matrix: mat3x3<f32>, color: vec4<f32> };
@group(1) @binding(0) var<storage, read> instances: array<Instance>;
struct In { @location(0) position: vec3<f32>, @location(1) normal: vec3<f32> };
struct Out { @builtin(position) position: vec4<f32>, @location(0) normal: vec3<f32>, @location(1) color: vec4<f32> };
@vertex fn vs_main(input: In, @builtin(instance_index) iid: u32) -> Out { let i = instances[iid]; let world = i.model * vec4<f32>(input.position, 1.0); var out: Out; out.position = camera.view_proj * world; out.normal = i.normal_matrix * input.normal; out.color = i.color; return out; }
@fragment fn fs_main(input: Out) -> @location(0) vec4<f32> { let light = normalize(-camera.light_direction.xyz); let diffuse = max(dot(normalize(input.normal), light), 0.0); let shade = 0.18 + diffuse * camera.light_color.w * 0.82; return vec4<f32>(input.color.rgb * shade, input.color.a); }
"#;
fn identity() -> [[f32; 4]; 4] {
[
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
]
}
pub fn normal_matrix(model: [[f32; 4]; 4]) -> [[f32; 4]; 3] {
let a = [
[model[0][0], model[1][0], model[2][0]],
[model[0][1], model[1][1], model[2][1]],
[model[0][2], model[1][2], model[2][2]],
];
let c00 = a[1][1] * a[2][2] - a[1][2] * a[2][1];
let c01 = -(a[1][0] * a[2][2] - a[1][2] * a[2][0]);
let c02 = a[1][0] * a[2][1] - a[1][1] * a[2][0];
let c10 = -(a[0][1] * a[2][2] - a[0][2] * a[2][1]);
let c11 = a[0][0] * a[2][2] - a[0][2] * a[2][0];
let c12 = -(a[0][0] * a[2][1] - a[0][1] * a[2][0]);
let c20 = a[0][1] * a[1][2] - a[0][2] * a[1][1];
let c21 = -(a[0][0] * a[1][2] - a[0][2] * a[1][0]);
let c22 = a[0][0] * a[1][1] - a[0][1] * a[1][0];
let det = a[0][0] * c00 + a[0][1] * c01 + a[0][2] * c02;
if !det.is_finite() || det.abs() < 1e-8 {
return [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
];
}
let nit = [
[c00 / det, c01 / det, c02 / det],
[c10 / det, c11 / det, c12 / det],
[c20 / det, c21 / det, c22 / det],
];
[
[nit[0][0], nit[1][0], nit[2][0], 0.0],
[nit[0][1], nit[1][1], nit[2][1], 0.0],
[nit[0][2], nit[1][2], nit[2][2], 0.0],
]
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Ray3d {
pub origin: [f32; 3],
pub direction: [f32; 3],
pub min_distance: f32,
pub max_distance: f32,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PickHit3d {
pub instance_index: usize,
pub triangle_index: usize,
pub distance: f32,
pub position: [f32; 3],
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Bounds3d {
pub min: [f32; 3],
pub max: [f32; 3],
}
impl Bounds3d {
pub fn from_instances(mesh: &Mesh3d, instances: &[Instance3d]) -> Option<Self> {
let local = mesh.local_bounds()?;
instances
.iter()
.filter(|instance| valid_model(instance.model))
.filter_map(|instance| local.transformed(instance.model))
.reduce(Self::union)
}
pub fn transformed(self, model: [[f32; 4]; 4]) -> Option<Self> {
if !valid_model(model) {
return None;
}
let mut min = [f32::INFINITY; 3];
let mut max = [f32::NEG_INFINITY; 3];
for corner in 0..8 {
let point = [
if corner & 1 == 0 {
self.min[0]
} else {
self.max[0]
},
if corner & 2 == 0 {
self.min[1]
} else {
self.max[1]
},
if corner & 4 == 0 {
self.min[2]
} else {
self.max[2]
},
];
let world = world_point(model, point);
if !world.iter().all(|v| v.is_finite()) {
return None;
}
for axis in 0..3 {
min[axis] = min[axis].min(world[axis]);
max[axis] = max[axis].max(world[axis]);
}
}
Some(Self { min, max })
}
pub fn union(self, other: Self) -> Self {
Self {
min: std::array::from_fn(|i| self.min[i].min(other.min[i])),
max: std::array::from_fn(|i| self.max[i].max(other.max[i])),
}
}
pub fn intersects_ray(self, ray: Ray3d) -> bool {
let mut near = ray.min_distance;
let mut far = ray.max_distance;
for axis in 0..3 {
let direction = ray.direction[axis];
if direction.abs() < 1e-12 {
if ray.origin[axis] < self.min[axis] || ray.origin[axis] > self.max[axis] {
return false;
}
continue;
}
let inverse = 1.0 / direction;
let mut t0 = (self.min[axis] - ray.origin[axis]) * inverse;
let mut t1 = (self.max[axis] - ray.origin[axis]) * inverse;
if t0 > t1 {
std::mem::swap(&mut t0, &mut t1);
}
near = near.max(t0);
far = far.min(t1);
if near > far {
return false;
}
}
true
}
pub fn is_visible(self, frustum: &Frustum3d) -> bool {
frustum.planes.iter().all(|plane| {
let farthest = [
if plane.normal[0] >= 0.0 {
self.max[0]
} else {
self.min[0]
},
if plane.normal[1] >= 0.0 {
self.max[1]
} else {
self.min[1]
},
if plane.normal[2] >= 0.0 {
self.max[2]
} else {
self.min[2]
},
];
plane.normal[0] * farthest[0]
+ plane.normal[1] * farthest[1]
+ plane.normal[2] * farthest[2]
+ plane.distance
>= 0.0
})
}
pub fn center(self) -> [f32; 3] {
std::array::from_fn(|i| self.min[i] * 0.5 + self.max[i] * 0.5)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Plane3d {
pub normal: [f32; 3],
pub distance: f32,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Frustum3d {
pub planes: [Plane3d; 6],
}
impl Frustum3d {
pub fn from_view_projection(matrix: [[f32; 4]; 4]) -> Self {
let row = |r: usize| [matrix[0][r], matrix[1][r], matrix[2][r], matrix[3][r]];
let (r0, r1, r2, r3) = (row(0), row(1), row(2), row(3));
let combine = |a: [f32; 4], b: [f32; 4], sign: f32| Plane3d {
normal: [a[0] + b[0] * sign, a[1] + b[1] * sign, a[2] + b[2] * sign],
distance: a[3] + b[3] * sign,
};
Self {
planes: [
combine(r2, r3, 0.0), combine(r3, r2, -1.0), combine(r3, r0, 1.0), combine(r3, r0, -1.0), combine(r3, r1, 1.0), combine(r3, r1, -1.0), ],
}
}
}
impl Camera3d {
pub fn screen_ray(self, position: [f32; 2], viewport: [f32; 2]) -> Option<Ray3d> {
let [width, height] = viewport;
if !width.is_finite()
|| !height.is_finite()
|| width <= 0.0
|| height <= 0.0
|| !position.iter().all(|v| v.is_finite())
|| position[0] < 0.0
|| position[1] < 0.0
|| position[0] > width
|| position[1] > height
|| !self.valid_projection()
{
return None;
}
let forward = unit(sub(self.target, self.eye))?;
let right = unit(cross(forward, self.up))?;
let up = cross(right, forward);
let tan = (self.fov_y_radians * 0.5).tan();
let x = (2.0 * position[0] / width - 1.0) * tan * width / height;
let y = (1.0 - 2.0 * position[1] / height) * tan;
let direction = unit(std::array::from_fn(|i| {
forward[i] + right[i] * x + up[i] * y
}))?;
let cosine = dot(direction, forward);
Some(Ray3d {
origin: self.eye,
direction,
min_distance: self.near / cosine,
max_distance: self.far / cosine,
})
}
pub fn frame_bounds(self, bounds: Bounds3d, aspect: f32) -> Option<Self> {
if !self.valid_projection()
|| !aspect.is_finite()
|| aspect <= 0.0
|| !(0..3).all(|i| {
bounds.min[i].is_finite()
&& bounds.max[i].is_finite()
&& bounds.min[i] <= bounds.max[i]
})
{
return None;
}
let direction = unit(sub(self.eye, self.target))?;
unit(cross(direction, self.up))?;
let center = bounds.center();
let half = sub(bounds.max, center);
let radius = dot(half, half).sqrt().max(0.01);
let half_fov =
(self.fov_y_radians * 0.5).min(((self.fov_y_radians * 0.5).tan() * aspect).atan());
let distance = radius * 1.1 / half_fov.sin();
let camera = Self {
eye: std::array::from_fn(|i| center[i] + direction[i] * distance),
target: center,
near: (distance - radius * 1.2).max(0.001),
far: distance + radius * 1.2,
..self
};
camera.valid_projection().then_some(camera)
}
fn valid_projection(self) -> bool {
self.eye
.into_iter()
.chain(self.target)
.chain(self.up)
.all(f32::is_finite)
&& self.fov_y_radians.is_finite()
&& self.fov_y_radians > 0.0
&& self.fov_y_radians < std::f32::consts::PI
&& self.near.is_finite()
&& self.far.is_finite()
&& self.near > 0.0
&& self.far > self.near
}
}
pub fn pick_mesh(mesh: &Mesh3d, instances: &[Instance3d], ray: Ray3d) -> Option<PickHit3d> {
if !ray
.origin
.into_iter()
.chain(ray.direction)
.all(f32::is_finite)
|| (dot(ray.direction, ray.direction) - 1.0).abs() > 1e-4
|| !ray.min_distance.is_finite()
|| !ray.max_distance.is_finite()
|| ray.min_distance < 0.0
|| ray.max_distance < ray.min_distance
{
return None;
}
let bvh = mesh.bvh();
if bvh.triangle_count() == 0 {
return None;
}
let local = mesh.local_bounds()?;
let mut closest: Option<PickHit3d> = None;
for (instance_index, instance) in instances.iter().enumerate() {
if !valid_model(instance.model) {
continue;
}
if local
.transformed(instance.model)
.is_none_or(|bounds| !bounds.intersects_ray(ray))
{
continue;
}
let Some(inverse) = inverse_affine(instance.model) else {
continue;
};
let sign = if determinant3(instance.model) < 0.0 {
-1.0
} else {
1.0
};
let origin = transform_point(inverse, ray.origin);
let direction = transform_direction(inverse, ray.direction);
if !origin.iter().chain(direction.iter()).all(|v| v.is_finite()) {
continue;
}
let Some(hit) = bvh.ray_cast(
&mesh.vertices,
&mesh.indices,
origin,
direction,
ray.min_distance,
ray.max_distance,
sign,
) else {
continue;
};
if closest.is_some_and(|previous| hit.t >= previous.distance) {
continue;
}
closest = Some(PickHit3d {
instance_index,
triangle_index: hit.triangle as usize,
distance: hit.t,
position: std::array::from_fn(|i| ray.origin[i] + ray.direction[i] * hit.t),
});
}
closest
}
fn local_bounds(vertices: &[Vertex3d]) -> Option<Bounds3d> {
let mut min = [f32::INFINITY; 3];
let mut max = [f32::NEG_INFINITY; 3];
for vertex in vertices {
for axis in 0..3 {
min[axis] = min[axis].min(vertex.position[axis]);
max[axis] = max[axis].max(vertex.position[axis]);
}
}
(min[0] <= max[0]).then_some(Bounds3d { min, max })
}
fn determinant3(model: [[f32; 4]; 4]) -> f32 {
model[0][0] * (model[1][1] * model[2][2] - model[1][2] * model[2][1])
- model[1][0] * (model[0][1] * model[2][2] - model[0][2] * model[2][1])
+ model[2][0] * (model[0][1] * model[1][2] - model[0][2] * model[1][1])
}
fn inverse_affine(model: [[f32; 4]; 4]) -> Option<[[f32; 4]; 4]> {
let a = [
[model[0][0], model[1][0], model[2][0]],
[model[0][1], model[1][1], model[2][1]],
[model[0][2], model[1][2], model[2][2]],
];
let c00 = a[1][1] * a[2][2] - a[1][2] * a[2][1];
let c01 = -(a[1][0] * a[2][2] - a[1][2] * a[2][0]);
let c02 = a[1][0] * a[2][1] - a[1][1] * a[2][0];
let c10 = -(a[0][1] * a[2][2] - a[0][2] * a[2][1]);
let c11 = a[0][0] * a[2][2] - a[0][2] * a[2][0];
let c12 = -(a[0][0] * a[2][1] - a[0][1] * a[2][0]);
let c20 = a[0][1] * a[1][2] - a[0][2] * a[1][1];
let c21 = -(a[0][0] * a[1][2] - a[0][2] * a[1][0]);
let c22 = a[0][0] * a[1][1] - a[0][1] * a[1][0];
let det = a[0][0] * c00 + a[0][1] * c01 + a[0][2] * c02;
if !det.is_finite() || det.abs() < 1e-12 {
return None;
}
let inv = [
[c00 / det, c10 / det, c20 / det],
[c01 / det, c11 / det, c21 / det],
[c02 / det, c12 / det, c22 / det],
];
let translation = [model[3][0], model[3][1], model[3][2]];
let shifted: [f32; 3] = std::array::from_fn(|row| {
-(inv[row][0] * translation[0]
+ inv[row][1] * translation[1]
+ inv[row][2] * translation[2])
});
Some([
[inv[0][0], inv[1][0], inv[2][0], 0.0],
[inv[0][1], inv[1][1], inv[2][1], 0.0],
[inv[0][2], inv[1][2], inv[2][2], 0.0],
[shifted[0], shifted[1], shifted[2], 1.0],
])
}
fn transform_point(model: [[f32; 4]; 4], point: [f32; 3]) -> [f32; 3] {
std::array::from_fn(|r| {
model[0][r] * point[0] + model[1][r] * point[1] + model[2][r] * point[2] + model[3][r]
})
}
fn transform_direction(model: [[f32; 4]; 4], direction: [f32; 3]) -> [f32; 3] {
std::array::from_fn(|r| {
model[0][r] * direction[0] + model[1][r] * direction[1] + model[2][r] * direction[2]
})
}
fn valid_model(model: [[f32; 4]; 4]) -> bool {
model.iter().flatten().all(|v| v.is_finite())
&& model[0][3] == 0.0
&& model[1][3] == 0.0
&& model[2][3] == 0.0
&& model[3][3] == 1.0
}
fn world_point(model: [[f32; 4]; 4], point: [f32; 3]) -> [f32; 3] {
std::array::from_fn(|r| {
model[0][r] * point[0] + model[1][r] * point[1] + model[2][r] * point[2] + model[3][r]
})
}
fn unit(vector: [f32; 3]) -> Option<[f32; 3]> {
let length = dot(vector, vector).sqrt();
(length.is_finite() && length > 1e-8).then(|| vector.map(|v| v / length))
}
fn sub(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
}
fn dot(a: [f32; 3], b: [f32; 3]) -> f32 {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
fn cross(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
[
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
]
}
fn norm(a: [f32; 3]) -> [f32; 3] {
let n = dot(a, a).sqrt().max(1e-6);
[a[0] / n, a[1] / n, a[2] / n]
}
fn look_at(eye: [f32; 3], target: [f32; 3], up: [f32; 3]) -> [[f32; 4]; 4] {
let f = norm(sub(target, eye));
let s = norm(cross(f, up));
let u = cross(s, f);
[
[s[0], u[0], -f[0], 0.0],
[s[1], u[1], -f[1], 0.0],
[s[2], u[2], -f[2], 0.0],
[-dot(s, eye), -dot(u, eye), dot(f, eye), 1.0],
]
}
fn perspective(fovy: f32, aspect: f32, near: f32, far: f32) -> [[f32; 4]; 4] {
let f = 1.0 / (fovy * 0.5).tan();
[
[f / aspect, 0.0, 0.0, 0.0],
[0.0, f, 0.0, 0.0],
[0.0, 0.0, far / (near - far), -1.0],
[0.0, 0.0, (near * far) / (near - far), 0.0],
]
}
fn mul4(a: [[f32; 4]; 4], b: [[f32; 4]; 4]) -> [[f32; 4]; 4] {
let mut out = [[0.0; 4]; 4];
for c in 0..4 {
for r in 0..4 {
out[c][r] = (0..4).map(|k| a[k][r] * b[c][k]).sum();
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn affine_inverse_round_trips_translation_rotation_and_scale() {
for model in [
trs_matrix([1.5, -2.0, 0.75], 0.4, 0.2, [1.8, 0.5, 1.0]),
trs_matrix([0.0, 3.0, -1.0], -0.9, 1.1, [-1.0, 2.0, 0.5]),
trs_matrix([0.0; 3], 0.0, 0.0, [1.0; 3]),
] {
let inverse = inverse_affine(model).expect("仿射矩阵可逆");
let identity = mul4(model, inverse);
for (column, values) in identity.iter().enumerate() {
for (row, value) in values.iter().enumerate() {
let expected = if column == row { 1.0 } else { 0.0 };
assert!(
(value - expected).abs() < 1e-5,
"M·M⁻¹ 第 {column} 列第 {row} 行 = {value}",
);
}
}
}
}
#[test]
fn singular_model_has_no_inverse() {
assert!(inverse_affine(trs_matrix([0.0; 3], 0.0, 0.0, [0.0; 3])).is_none());
assert!(inverse_affine(trs_matrix([0.0; 3], 0.0, 0.0, [1.0, 0.0, 2.0])).is_none());
}
#[test]
fn frustum_rejects_offscreen_bounds() {
let camera = Camera3d::orbit([0.0; 3], 0.0, 0.0, 5.0);
let view_proj = mul4(
perspective(camera.fov_y_radians, 4.0 / 3.0, camera.near, camera.far),
look_at(camera.eye, camera.target, camera.up),
);
let frustum = Frustum3d::from_view_projection(view_proj);
let centered = Bounds3d {
min: [-0.5; 3],
max: [0.5; 3],
};
assert!(centered.is_visible(&frustum));
let behind = Bounds3d {
min: [-0.5, -0.5, 20.0],
max: [0.5, 0.5, 21.0],
};
assert!(!behind.is_visible(&frustum), "相机背后的物体应被剔除");
let far_left = Bounds3d {
min: [80.0, -0.5, -0.5],
max: [81.0, 0.5, 0.5],
};
assert!(!far_left.is_visible(&frustum), "视野外的物体应被剔除");
}
#[test]
fn world_bounds_follow_instance_transform() {
let mesh = Mesh3d::cube();
let local = mesh.local_bounds().expect("立方体有包围盒");
let moved = local
.transformed(trs_matrix([2.0, 0.0, 0.0], 0.0, 0.0, [1.0; 3]))
.unwrap();
assert!((moved.min[0] - 1.5).abs() < 1e-6);
assert!((moved.max[0] - 2.5).abs() < 1e-6);
}
}