use crate::{Composer, FieldBuffer, GridParams, Result};
const WORKGROUP: u32 = 64;
const SAMPLED_BASE_ID: u32 = 4;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GpuField {
Sphere,
Torus,
BoxExact,
Gyroid,
}
impl GpuField {
pub const ALL: [Self; 4] = [Self::Sphere, Self::Torus, Self::BoxExact, Self::Gyroid];
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::Sphere => "sphere",
Self::Torus => "torus",
Self::BoxExact => "box_exact",
Self::Gyroid => "gyroid",
}
}
#[must_use]
pub const fn id(self) -> u32 {
match self {
Self::Sphere => 0,
Self::Torus => 1,
Self::BoxExact => 2,
Self::Gyroid => 3,
}
}
#[must_use]
pub fn sample_on_cpu(self, p: [f32; 3]) -> f32 {
use isomesh::Sdf;
use isomesh::fields::{BoxExact, Gyroid, Sphere, Torus};
match self {
Self::Sphere => Sphere::<f32>::canonical().sample(p),
Self::Torus => Torus::<f32>::canonical().sample(p),
Self::BoxExact => BoxExact::<f32>::canonical().sample(p),
Self::Gyroid => Gyroid::<f32>::canonical().sample(p),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GpuShape {
Sphere {
center: [f32; 3],
radius: f32,
},
BoxExact {
center: [f32; 3],
half_extents: [f32; 3],
},
Capsule {
a: [f32; 3],
b: [f32; 3],
radius: f32,
},
}
impl isomesh::Sdf for GpuShape {
type Scalar = f32;
fn sample(&self, p: [f32; 3]) -> f32 {
use isomesh::brush::Capsule;
use isomesh::fields::{BoxExact, Sphere};
match *self {
Self::Sphere { center, radius } => Sphere { center, radius }.sample(p),
Self::BoxExact {
center,
half_extents,
} => BoxExact {
center,
half_extents,
}
.sample(p),
Self::Capsule { a, b, radius } => Capsule { a, b, radius }.sample(p),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GpuOp {
Add,
Subtract,
SmoothAdd {
k: f32,
},
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GpuBrush {
pub shape: GpuShape,
pub op: GpuOp,
}
impl GpuBrush {
pub const STRIDE: u64 = 64;
#[must_use]
pub fn to_cpu(self) -> isomesh::brush::Brush<GpuShape> {
use isomesh::brush::{Brush, BrushOp};
Brush {
shape: self.shape,
op: match self.op {
GpuOp::Add => BrushOp::Add,
GpuOp::Subtract => BrushOp::Subtract,
GpuOp::SmoothAdd { k } => BrushOp::SmoothAdd { k: f64::from(k) },
},
}
}
#[must_use]
pub fn to_std140(self) -> [u8; Self::STRIDE as usize] {
let (kind, a, a_w, b, b_w) = match self.shape {
GpuShape::Sphere { center, radius } => (0u32, center, radius, [0.0f32; 3], 0.0f32),
GpuShape::BoxExact {
center,
half_extents,
} => (1, center, 0.0, half_extents, 0.0),
GpuShape::Capsule { a, b, radius } => (2, a, radius, b, 0.0),
};
let (op, k) = match self.op {
GpuOp::Add => (0u32, 0.0f32),
GpuOp::Subtract => (1, 0.0),
GpuOp::SmoothAdd { k } => (2, k),
};
let mut out = [0u8; Self::STRIDE as usize];
let words: [[u8; 4]; 16] = [
kind.to_le_bytes(),
op.to_le_bytes(),
0u32.to_le_bytes(),
0u32.to_le_bytes(),
a[0].to_le_bytes(),
a[1].to_le_bytes(),
a[2].to_le_bytes(),
a_w.to_le_bytes(),
b[0].to_le_bytes(),
b[1].to_le_bytes(),
b[2].to_le_bytes(),
b_w.to_le_bytes(),
k.to_le_bytes(),
0f32.to_le_bytes(),
0f32.to_le_bytes(),
0f32.to_le_bytes(),
];
for (slot, word) in out.as_chunks_mut::<4>().0.iter_mut().zip(words) {
slot.copy_from_slice(&word);
}
out
}
}
#[derive(Debug)]
pub struct FieldSampler {
pipeline: wgpu::ComputePipeline,
layout: wgpu::BindGroupLayout,
unused_base: wgpu::Buffer,
}
impl FieldSampler {
pub fn new(device: &wgpu::Device) -> Result<Self> {
let source = Composer::with_builtins().compose("field", &[])?;
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("isomesh field sampler"),
source: wgpu::ShaderSource::Wgsl(source.into()),
});
let entry = |binding: u32, ty: wgpu::BufferBindingType| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
};
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("isomesh field sampler bindings"),
entries: &[
entry(0, wgpu::BufferBindingType::Uniform),
entry(1, wgpu::BufferBindingType::Uniform),
entry(2, wgpu::BufferBindingType::Storage { read_only: false }),
entry(3, wgpu::BufferBindingType::Storage { read_only: true }),
entry(4, wgpu::BufferBindingType::Storage { read_only: true }),
],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("isomesh field sampler layout"),
bind_group_layouts: &[Some(&layout)],
immediate_size: 0,
});
Ok(Self {
pipeline: device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("isomesh field sampler"),
layout: Some(&pipeline_layout),
module: &module,
entry_point: Some("sample_field"),
compilation_options: wgpu::PipelineCompilationOptions::default(),
cache: None,
}),
layout,
unused_base: device.create_buffer(&wgpu::BufferDescriptor {
label: Some("isomesh field sampler unused base"),
size: 4,
usage: wgpu::BufferUsages::STORAGE,
mapped_at_creation: false,
}),
})
}
pub fn sample(
&self,
device: &wgpu::Device,
queue: &wgpu::Queue,
params: GridParams,
field: GpuField,
) -> Result<FieldBuffer> {
self.sample_stack(device, queue, params, field, &[])
}
pub fn sample_stack(
&self,
device: &wgpu::Device,
queue: &wgpu::Queue,
params: GridParams,
field: GpuField,
brushes: &[GpuBrush],
) -> Result<FieldBuffer> {
let out = FieldBuffer::new(device, params);
self.run(device, queue, field.id(), brushes, &out, &self.unused_base)?;
Ok(out)
}
pub fn fold_into(
&self,
device: &wgpu::Device,
queue: &wgpu::Queue,
base: &FieldBuffer,
out: &FieldBuffer,
brushes: &[GpuBrush],
) -> Result<()> {
let expected = base.params().sample_count();
let got = out.params().sample_count();
if expected != got {
return Err(crate::Error::SampleCountMismatch { expected, got });
}
self.run(device, queue, SAMPLED_BASE_ID, brushes, out, base.buffer())
}
fn run(
&self,
device: &wgpu::Device,
queue: &wgpu::Queue,
field_id: u32,
brushes: &[GpuBrush],
out: &FieldBuffer,
base: &wgpu::Buffer,
) -> Result<()> {
let params = out.params();
let samples = params.sample_count();
let groups = samples.div_ceil(u64::from(WORKGROUP));
if groups > u64::from(device.limits().max_compute_workgroups_per_dimension) {
return Err(crate::Error::GridTooLarge {
samples: params.samples(),
});
}
let grid = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("isomesh grid params"),
size: GridParams::UNIFORM_SIZE,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
queue.write_buffer(&grid, 0, ¶ms.to_std140());
let select = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("isomesh field select"),
size: 16,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let mut bytes = [0u8; 16];
bytes[..4].copy_from_slice(&field_id.to_le_bytes());
let count = u32::try_from(brushes.len()).map_err(|_| crate::Error::GridTooLarge {
samples: params.samples(),
})?;
bytes[4..8].copy_from_slice(&count.to_le_bytes());
queue.write_buffer(&select, 0, &bytes);
let log = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("isomesh brush log"),
size: GpuBrush::STRIDE * brushes.len().max(1) as u64,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
if !brushes.is_empty() {
let mut packed = Vec::with_capacity(brushes.len() * GpuBrush::STRIDE as usize);
for brush in brushes {
packed.extend_from_slice(&brush.to_std140());
}
queue.write_buffer(&log, 0, &packed);
}
fn entry(binding: u32, buffer: &wgpu::Buffer) -> wgpu::BindGroupEntry<'_> {
wgpu::BindGroupEntry {
binding,
resource: buffer.as_entire_binding(),
}
}
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("isomesh field sampler"),
layout: &self.layout,
entries: &[
entry(0, &grid),
entry(1, &select),
entry(2, out.buffer()),
entry(3, &log),
entry(4, base),
],
});
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("isomesh field sampler"),
});
{
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("isomesh field sampler"),
timestamp_writes: None,
});
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, &bind_group, &[]);
pass.dispatch_workgroups(groups as u32, 1, 1);
}
queue.submit(Some(encoder.finish()));
Ok(())
}
}
#[cfg(test)]
mod tests;