pub mod card;
pub mod field;
pub mod placement;
pub mod shell;
use crcbl_hal::{
BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BufferDesc, BufferHandle,
BufferUsage, ClearValue, ColorTargetState, CompareOp, ComputePipelineHandle, DepthBias,
DepthStencilState, Device, DrawIndirect, FilterMode, Format, GraphicsPipelineDesc,
GraphicsPipelineHandle, HalError, ImageViewHandle, ImageViewType, LoadOp, MemoryLocation,
MultisampleState, PipelineLayoutDesc, PipelineLayoutHandle, PrimitiveTopology, ResourceState,
SampleType, SamplerAddressMode, SamplerDesc, SamplerHandle, ShaderEntry, ShaderModuleDesc,
ShaderStages, StoreOp, check_portable_storage_buffers,
};
use crcbl_shaders::grass::{
BLADE_FAR_DRAW, BLADE_NEAR_DRAW, BLADE_STRIDE, CARD_DRAW, DRAW_ARGS_SIZE, FIELD_BLOCK_SIZE,
FIN_DRAW, GEN_PARAMS_SIZE, GenParams, INSTANCE_STRIDE, PARAMS_SIZE, Params, SHELL_DRAW,
SLOT_ARGS_SIZE, TILE_SIZE, Tile, WORKGROUP_SIZE,
};
use crcbl_shaders::wind::{PARAMS_SIZE as WIND_PARAMS_SIZE, WindParams};
use crcbl_shaders::{GRASS, GRASS_GEN, Stage};
use crate::draw_gen::compute_pipeline_entry;
use crate::graph::{BufferId, ImageId, ImportedBuffer, RenderGraph};
use crate::partial::Partial;
use crate::pipeline_batch;
use crate::ssao::cached_group;
use crate::texture::{
PendingUpload, UploadBatch, UploadedTexture, upload_texture, upload_texture_mip_layers,
};
pub use field::{
BladeLod, BladeLook, BladeNormal, BladeShape, BladeStyle, BladeType, CELLS_PER_TILE, Clumping,
CoverMap, GrassError, GrassField, Heightfield, MAX_BLADES, MAX_TILES, SLOT_CAPACITY, Shells,
};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WindLayer {
pub texels: [u32; 2],
pub rgba8: Vec<u8>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WindLayers {
pub direction: WindLayer,
pub intensity: WindLayer,
}
const CALM_DIRECTION: [u8; 4] = [255, 128, 0, 255];
const CALM_INTENSITY: [u8; 4] = [0, 0, 0, 255];
#[derive(Debug, thiserror::Error)]
pub enum WindLayerError {
#[error("a {width}x{height} wind layer has no texels")]
Empty {
width: u32,
height: u32,
},
#[error("a {width}x{height} wind layer is {expected} bytes of RGBA8, and {found} arrived")]
Size {
width: u32,
height: u32,
expected: usize,
found: usize,
},
#[error("a wind layer could not be uploaded: {0}")]
Hal(#[from] HalError),
}
impl WindLayer {
fn check(&self) -> Result<(), WindLayerError> {
let [width, height] = self.texels;
if width == 0 || height == 0 {
return Err(WindLayerError::Empty { width, height });
}
let expected = width as usize * height as usize * 4;
if self.rgba8.len() != expected {
return Err(WindLayerError::Size {
width,
height,
expected,
found: self.rgba8.len(),
});
}
Ok(())
}
}
#[derive(Clone, Copy, Debug)]
pub struct GrassBuffers {
pub instances: crcbl_hal::BufferHandle,
pub cells: crcbl_hal::BufferHandle,
pub args: crcbl_hal::BufferHandle,
pub slots: u32,
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct GrassFrame {
pub(crate) instances: BufferHandle,
pub(crate) cells: BufferHandle,
pub(crate) args: BufferHandle,
pub(crate) blades: BufferHandle,
pub(crate) tiles: BufferHandle,
pub(crate) field_block: BufferHandle,
pub(crate) ground: ImageViewHandle,
pub(crate) cover: ImageViewHandle,
pub(crate) card: ImageViewHandle,
pub(crate) wind_direction: ImageViewHandle,
pub(crate) wind_intensity: ImageViewHandle,
pub(crate) slots: u32,
pub(crate) shells: bool,
pub(crate) fins: bool,
pub(crate) mesh_blades: bool,
pub(crate) generation: GenParams,
}
impl GrassFrame {
pub(crate) const fn draws_per_slot(&self) -> u32 {
1 + self.shells as u32 + (self.shells && self.fins) as u32 + 2 * self.mesh_blades as u32
}
pub(crate) const fn rows(&self) -> u32 {
self.generation.limits[1]
}
pub(crate) fn gen_params(&self, camera: glam::Vec3) -> GenParams {
let mut params = self.generation;
params.camera = [camera.x, camera.y, camera.z, self.generation.camera[3]];
params
}
}
#[derive(Debug)]
pub(crate) struct GrassScene {
field: Option<GrassField>,
live: Option<Resident>,
wind: Wind,
retired: Vec<(u64, Retired)>,
frames: u64,
depth: u64,
}
#[derive(Debug)]
struct Resident {
instances: BufferHandle,
cells: BufferHandle,
args: BufferHandle,
blades: BufferHandle,
tiles: BufferHandle,
field_block: BufferHandle,
ground: UploadedTexture,
cover: UploadedTexture,
card: UploadedTexture,
slots: u32,
shells: bool,
fins: bool,
mesh_blades: bool,
generation: GenParams,
}
#[derive(Debug)]
struct Wind {
direction: UploadedTexture,
intensity: UploadedTexture,
}
#[derive(Debug)]
enum Retired {
Field(Box<Resident>),
Wind(Box<Wind>),
}
impl GrassScene {
pub(crate) fn new(
device: &dyn Device,
uploads: &mut UploadBatch<'_>,
frames: usize,
) -> Result<Self, HalError> {
Ok(Self {
field: None,
live: None,
wind: Wind::calm(device, uploads)?,
retired: Vec::new(),
frames: 0,
depth: frames as u64,
})
}
pub(crate) fn field(&self) -> Option<&GrassField> {
self.field.as_ref()
}
pub(crate) fn set(
&mut self,
device: &dyn Device,
queue: crcbl_hal::QueueHandle,
field: Option<&GrassField>,
) -> Result<(), SetError> {
let resident = match field {
Some(field) => Some(Resident::upload(device, queue, field)?),
None => None,
};
if let Some(old) = self.live.take() {
self.retired
.push((self.frames, Retired::Field(Box::new(old))));
}
self.live = resident;
self.field = field.cloned();
Ok(())
}
pub(crate) fn set_wind_layers(
&mut self,
device: &dyn Device,
queue: crcbl_hal::QueueHandle,
layers: Option<&WindLayers>,
) -> Result<PendingUpload, WindLayerError> {
let mut uploads = UploadBatch::new(device, queue, "wind");
let wind = match layers {
Some(layers) => Wind::upload(device, &mut uploads, layers)?,
None => Wind::calm(device, &mut uploads)?,
};
let pending = match uploads.submit_deferred() {
Ok(pending) => pending,
Err(error) => {
wind.destroy(device);
return Err(error.into());
}
};
let old = core::mem::replace(&mut self.wind, wind);
self.retired
.push((self.frames, Retired::Wind(Box::new(old))));
Ok(pending)
}
pub(crate) fn begin_frame(&mut self, device: &dyn Device) {
self.frames += 1;
let depth = self.depth;
let now = self.frames;
let mut kept = Vec::new();
for (at, retired) in self.retired.drain(..) {
if now.saturating_sub(at) > depth {
match retired {
Retired::Field(resident) => resident.destroy(device),
Retired::Wind(wind) => wind.destroy(device),
}
} else {
kept.push((at, retired));
}
}
self.retired = kept;
}
pub(crate) fn buffers(&self) -> Option<GrassBuffers> {
let live = self.live.as_ref()?;
Some(GrassBuffers {
instances: live.instances,
cells: live.cells,
args: live.args,
slots: live.slots,
})
}
pub(crate) fn frame(&self) -> Option<GrassFrame> {
let live = self.live.as_ref()?;
Some(GrassFrame {
instances: live.instances,
cells: live.cells,
args: live.args,
blades: live.blades,
tiles: live.tiles,
field_block: live.field_block,
ground: live.ground.view,
cover: live.cover.view,
card: live.card.view,
wind_direction: self.wind.direction.view,
wind_intensity: self.wind.intensity.view,
slots: live.slots,
shells: live.shells,
fins: live.fins,
mesh_blades: live.mesh_blades,
generation: live.generation,
})
}
pub(crate) fn destroy(self, device: &dyn Device) {
for (_, retired) in self.retired {
match retired {
Retired::Field(resident) => resident.destroy(device),
Retired::Wind(wind) => wind.destroy(device),
}
}
if let Some(live) = self.live {
live.destroy(device);
}
self.wind.destroy(device);
}
}
#[derive(Debug, thiserror::Error)]
pub enum SetError {
#[error(transparent)]
Field(#[from] GrassError),
#[error("a grass field could not be uploaded: {0}")]
Hal(#[from] HalError),
}
impl Resident {
fn upload(
device: &dyn Device,
queue: crcbl_hal::QueueHandle,
field: &GrassField,
) -> Result<Self, SetError> {
let ground = field.ground();
let cover = field.cover();
let ground_image = upload_texture(
device,
queue,
"grass ground",
Format::R32Float,
ground.texels[0],
ground.texels[1],
&ground.to_bytes(),
)?;
let cover_image = match upload_texture(
device,
queue,
"grass cover",
Format::Rgba8Unorm,
cover.texels[0],
cover.texels[1],
&cover.to_bytes(),
) {
Ok(image) => image,
Err(error) => {
ground_image.destroy(device);
return Err(error.into());
}
};
let chain = card::coverage_chain(&card::blade_mask(card::CARD_EXTENT), card::CARD_EXTENT);
let levels: Vec<&[u8]> = chain.iter().map(Vec::as_slice).collect();
let card_image = match upload_texture_mip_layers(
device,
queue,
"grass card",
Format::R8Unorm,
card::CARD_EXTENT,
card::CARD_EXTENT,
&[&levels],
) {
Ok(image) => image,
Err(error) => {
cover_image.destroy(device);
ground_image.destroy(device);
return Err(error.into());
}
};
let slots = field.slots();
let descs = [
(
"grass instances",
field.instance_bytes(),
BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC,
MemoryLocation::DeviceLocal,
),
(
"grass draw args",
u64::from(slots) * SLOT_ARGS_SIZE as u64,
BufferUsage::STORAGE | BufferUsage::INDIRECT | BufferUsage::TRANSFER_SRC,
MemoryLocation::DeviceLocal,
),
(
"grass blades",
field.blade_bytes(),
BufferUsage::STORAGE,
MemoryLocation::HostUpload,
),
(
"grass tiles",
u64::from(slots) * u64::from(TILE_STRIDE),
BufferUsage::UNIFORM,
MemoryLocation::HostUpload,
),
(
"grass cells",
field.cell_bytes(),
BufferUsage::STORAGE | BufferUsage::TRANSFER_SRC,
MemoryLocation::DeviceLocal,
),
(
"grass field",
FIELD_BLOCK_SIZE as u64,
BufferUsage::UNIFORM,
MemoryLocation::HostUpload,
),
];
let mut created: Vec<BufferHandle> = Vec::with_capacity(descs.len());
for (label, size, usage, memory) in descs {
match device.create_buffer(&BufferDesc {
label: Some(label),
size,
usage,
memory,
}) {
Ok(buffer) => created.push(buffer),
Err(error) => {
for buffer in created {
device.destroy_buffer(buffer);
}
card_image.destroy(device);
cover_image.destroy(device);
ground_image.destroy(device);
return Err(error.into());
}
}
}
let resident = Self {
instances: created[0],
args: created[1],
blades: created[2],
tiles: created[3],
cells: created[4],
field_block: created[5],
ground: ground_image,
cover: cover_image,
card: card_image,
slots,
shells: field.draws_shells(),
fins: field.shells().fins,
mesh_blades: field.draws_blades(),
generation: gen_params_of(field),
};
if let Err(error) = resident.write_static(device, field) {
resident.destroy(device);
return Err(error.into());
}
Ok(resident)
}
fn write_static(&self, device: &dyn Device, field: &GrassField) -> Result<(), HalError> {
let blades: Vec<u8> = field
.blades()
.iter()
.flat_map(|blade| blade.row().to_bytes())
.collect();
device.write_buffer(self.blades, 0, &blades)?;
let mut tiles = vec![0u8; self.slots as usize * TILE_STRIDE as usize];
for slot in 0..self.slots {
let [x, z] = field.tile_origin(slot);
let block = Tile {
tile: [x, z, field.tile_size(), 0.0],
slot: [slot, slot % field.tiles()[0], slot / field.tiles()[0], 0],
};
let at = slot as usize * TILE_STRIDE as usize;
tiles[at..at + TILE_SIZE].copy_from_slice(&block.to_bytes());
}
device.write_buffer(self.tiles, 0, &tiles)?;
device.write_buffer(
self.field_block,
0,
&shell::field_block_of(field).to_bytes(),
)
}
fn destroy(&self, device: &dyn Device) {
for buffer in [
self.instances,
self.cells,
self.args,
self.blades,
self.tiles,
self.field_block,
] {
device.destroy_buffer(buffer);
}
self.card.destroy(device);
self.cover.destroy(device);
self.ground.destroy(device);
}
}
impl Wind {
fn calm(device: &dyn Device, uploads: &mut UploadBatch<'_>) -> Result<Self, HalError> {
let mut one = |label, texel: [u8; 4]| {
uploads.texture(
label,
Format::Rgba8Unorm,
(1, 1),
&[&[&texel]],
ImageViewType::D2,
)
};
let direction = one("wind direction", CALM_DIRECTION)?;
match one("wind intensity", CALM_INTENSITY) {
Ok(intensity) => Ok(Self {
direction,
intensity,
}),
Err(error) => {
uploads.abandon();
direction.destroy(device);
Err(error)
}
}
}
fn upload(
device: &dyn Device,
uploads: &mut UploadBatch<'_>,
layers: &WindLayers,
) -> Result<Self, WindLayerError> {
layers.direction.check()?;
layers.intensity.check()?;
let mut one = |label, layer: &WindLayer| {
uploads.texture(
label,
Format::Rgba8Unorm,
(layer.texels[0], layer.texels[1]),
&[&[&layer.rgba8]],
ImageViewType::D2,
)
};
let direction = one("wind direction", &layers.direction)?;
match one("wind intensity", &layers.intensity) {
Ok(intensity) => Ok(Self {
direction,
intensity,
}),
Err(error) => {
uploads.abandon();
direction.destroy(device);
Err(error.into())
}
}
}
fn destroy(&self, device: &dyn Device) {
self.intensity.destroy(device);
self.direction.destroy(device);
}
}
const TILE_STRIDE: u32 = 256;
fn gen_params_of(field: &GrassField) -> GenParams {
let ground = field.ground();
let cover = field.cover();
GenParams {
camera: [0.0, 0.0, 0.0, field.reach()],
ground: [
ground.origin[0],
ground.origin[1],
ground.metres_per_texel,
1.0 / ground.metres_per_texel,
],
cover: [
cover.origin[0],
cover.origin[1],
cover.metres_per_texel,
1.0 / cover.metres_per_texel,
],
maps: [
ground.texels[0],
ground.texels[1],
cover.texels[0],
cover.texels[1],
],
limits: [
SLOT_CAPACITY,
field.blades().len() as u32,
CELLS_PER_TILE,
field.slots(),
],
looks: [field.shells().count, u32::from(field.shells().fins), 0, 0],
lod: [field.blade_lod().distance, 0.0, 0.0, 0.0],
}
}
mod gen_binding {
pub(super) const WIND: u32 = 0;
pub(super) const WIND_DIRECTION: u32 = 1;
pub(super) const WIND_INTENSITY: u32 = 2;
pub(super) const WIND_SAMPLER: u32 = 3;
pub(super) const PARAMS: u32 = 4;
pub(super) const TILE: u32 = 5;
pub(super) const BLADES: u32 = 6;
pub(super) const GROUND: u32 = 7;
pub(super) const COVER: u32 = 8;
pub(super) const INSTANCES: u32 = 9;
pub(super) const ARGS: u32 = 10;
pub(super) const CELLS: u32 = 11;
}
mod binding {
pub(super) const FRAME: u32 = 0;
pub(super) const PARAMS: u32 = 1;
pub(super) const TILE: u32 = 2;
pub(super) const INSTANCES: u32 = 3;
pub(super) const BLADES: u32 = 4;
pub(super) const CARD: u32 = 5;
pub(super) const CARD_SAMPLER: u32 = 6;
pub(super) const SHADOW_ATLAS: u32 = 7;
pub(super) const SHADOW_SAMPLER: u32 = 8;
pub(super) const LIGHTS: u32 = 9;
pub(super) const CLUSTER_LIGHTS: u32 = 10;
pub(super) const FIELD: u32 = 11;
pub(super) const CELLS: u32 = 12;
pub(super) const GROUND: u32 = 13;
pub(super) const WIND: u32 = 14;
pub(super) const WIND_DIRECTION: u32 = 15;
pub(super) const WIND_INTENSITY: u32 = 16;
pub(super) const WIND_SAMPLER: u32 = 17;
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct GrassImages {
pub(crate) color: ImageId,
pub(crate) depth: ImageId,
pub(crate) shadow_atlas: ImageId,
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct GrassInputs {
pub(crate) frame_block: BufferHandle,
pub(crate) lights: BufferHandle,
pub(crate) cluster_lights: BufferHandle,
pub(crate) light_grid: BufferId,
pub(crate) field: GrassFrame,
}
#[derive(Clone, Copy)]
struct GenGroup {
layout: BindGroupLayoutHandle,
field: GrassFrame,
gen_params: BufferHandle,
wind_params: BufferHandle,
wind_sampler: SamplerHandle,
}
impl GenGroup {
fn build(
self,
device: &dyn Device,
named: &mut Option<Vec<BufferHandle>>,
cached: &mut Option<(Vec<ImageViewHandle>, BindGroupHandle)>,
) -> Option<BindGroupHandle> {
let field = self.field;
let now = vec![
field.instances,
field.cells,
field.args,
field.blades,
field.tiles,
];
if named.as_ref() != Some(&now) {
if let Some((_, stale)) = cached.take() {
device.destroy_bind_group(stale);
}
*named = Some(now);
}
let buffer = |binding, buffer| BindGroupEntry {
binding,
array_index: 0,
resource: BindingResource::whole_buffer(buffer),
};
let view = |binding, view| BindGroupEntry {
binding,
array_index: 0,
resource: BindingResource::ImageView(view),
};
let entries = [
buffer(gen_binding::WIND, self.wind_params),
view(gen_binding::WIND_DIRECTION, field.wind_direction),
view(gen_binding::WIND_INTENSITY, field.wind_intensity),
BindGroupEntry {
binding: gen_binding::WIND_SAMPLER,
array_index: 0,
resource: BindingResource::Sampler(self.wind_sampler),
},
buffer(gen_binding::PARAMS, self.gen_params),
BindGroupEntry {
binding: gen_binding::TILE,
array_index: 0,
resource: BindingResource::Buffer {
buffer: field.tiles,
offset: 0,
size: TILE_SIZE as u64,
},
},
buffer(gen_binding::BLADES, field.blades),
view(gen_binding::GROUND, field.ground),
view(gen_binding::COVER, field.cover),
buffer(gen_binding::INSTANCES, field.instances),
buffer(gen_binding::ARGS, field.args),
buffer(gen_binding::CELLS, field.cells),
];
cached_group(
cached,
device,
&[
(gen_binding::WIND_DIRECTION, field.wind_direction),
(gen_binding::WIND_INTENSITY, field.wind_intensity),
(gen_binding::GROUND, field.ground),
(gen_binding::COVER, field.cover),
],
"grass generate",
self.layout,
&entries,
)
}
}
type RasterCache = (
Option<Vec<BufferHandle>>,
Option<(Vec<ImageViewHandle>, BindGroupHandle)>,
);
#[derive(Debug)]
pub(crate) struct Grass {
gen_layout: BindGroupLayoutHandle,
gen_pipeline_layout: PipelineLayoutHandle,
clear_pipeline: ComputePipelineHandle,
generate_pipeline: ComputePipelineHandle,
raster_layout: BindGroupLayoutHandle,
raster_pipeline_layout: PipelineLayoutHandle,
raster_pipeline: GraphicsPipelineHandle,
shell_pipeline: GraphicsPipelineHandle,
fin_pipeline: GraphicsPipelineHandle,
blade_near_pipeline: GraphicsPipelineHandle,
blade_far_pipeline: GraphicsPipelineHandle,
gen_params: Vec<BufferHandle>,
wind_params: Vec<BufferHandle>,
raster_params: Vec<BufferHandle>,
clear_groups: Vec<RasterCache>,
gen_groups: Vec<RasterCache>,
raster_groups: Vec<RasterCache>,
card_sampler: SamplerHandle,
wind_sampler: SamplerHandle,
shadow_sampler: SamplerHandle,
}
impl Grass {
pub(crate) const PASSES: u32 = 3;
pub(crate) fn new(
device: &dyn Device,
frames: usize,
shadow_sampler: SamplerHandle,
) -> Result<Self, HalError> {
let compute = ShaderStages::COMPUTE;
let gen_entries = [
uniform(gen_binding::WIND, compute, false),
sampled(gen_binding::WIND_DIRECTION, compute, SampleType::Float),
sampled(gen_binding::WIND_INTENSITY, compute, SampleType::Float),
sampler(gen_binding::WIND_SAMPLER, compute),
uniform(gen_binding::PARAMS, compute, false),
uniform(gen_binding::TILE, compute, true),
storage(gen_binding::BLADES, compute, true, BLADE_STRIDE as u32),
BindGroupLayoutEntry {
binding: gen_binding::GROUND,
visibility: compute,
kind: BindingKind::SampledImage {
view_type: ImageViewType::D2,
sample_type: SampleType::UnfilterableFloat,
},
count: 1,
flags: BindingFlags::empty(),
},
sampled(gen_binding::COVER, compute, SampleType::Float),
storage(
gen_binding::INSTANCES,
compute,
false,
INSTANCE_STRIDE as u32,
),
storage(gen_binding::ARGS, compute, false, 4),
storage(gen_binding::CELLS, compute, false, INSTANCE_STRIDE as u32),
];
let gen_desc = BindGroupLayoutDesc {
label: Some("grass generate"),
entries: &gen_entries,
};
check_portable_storage_buffers(Some("grass generate"), &[&gen_desc])?;
let mut made = Partial::new(device);
let gen_layout = made.add(device.create_bind_group_layout(&gen_desc)?);
let gen_pipeline_layout = made.add(device.create_pipeline_layout(&PipelineLayoutDesc {
label: Some("grass generate"),
bind_group_layouts: &[gen_layout],
push_constants: None,
})?);
let clear_pipeline = made.add(compute_pipeline_entry(
device,
"grass clear",
&GRASS_GEN,
"clearMain",
gen_pipeline_layout,
WORKGROUP_SIZE,
)?);
let generate_pipeline = made.add(compute_pipeline_entry(
device,
"grass generate",
&GRASS_GEN,
"generateMain",
gen_pipeline_layout,
WORKGROUP_SIZE,
)?);
let both = ShaderStages::VERTEX.union(ShaderStages::FRAGMENT);
let raster_entries = [
uniform(binding::FRAME, both, false),
uniform(binding::PARAMS, both, false),
uniform(binding::TILE, both, true),
storage(binding::INSTANCES, both, true, INSTANCE_STRIDE as u32),
storage(binding::BLADES, both, true, BLADE_STRIDE as u32),
BindGroupLayoutEntry {
binding: binding::CARD,
visibility: both,
kind: BindingKind::SampledImage {
view_type: ImageViewType::D2Array,
sample_type: SampleType::Float,
},
count: 1,
flags: BindingFlags::empty(),
},
sampler(binding::CARD_SAMPLER, both),
sampled(binding::SHADOW_ATLAS, both, SampleType::Depth),
BindGroupLayoutEntry {
binding: binding::SHADOW_SAMPLER,
visibility: both,
kind: BindingKind::Sampler { comparison: true },
count: 1,
flags: BindingFlags::empty(),
},
storage(
binding::LIGHTS,
both,
true,
crcbl_shaders::light::LIGHT_STRIDE as u32,
),
storage(binding::CLUSTER_LIGHTS, both, true, 4),
uniform(binding::FIELD, both, false),
storage(binding::CELLS, both, true, INSTANCE_STRIDE as u32),
BindGroupLayoutEntry {
binding: binding::GROUND,
visibility: both,
kind: BindingKind::SampledImage {
view_type: ImageViewType::D2,
sample_type: SampleType::UnfilterableFloat,
},
count: 1,
flags: BindingFlags::empty(),
},
uniform(binding::WIND, both, false),
sampled(binding::WIND_DIRECTION, both, SampleType::Float),
sampled(binding::WIND_INTENSITY, both, SampleType::Float),
sampler(binding::WIND_SAMPLER, both),
];
let raster_desc = BindGroupLayoutDesc {
label: Some("grass"),
entries: &raster_entries,
};
check_portable_storage_buffers(Some("grass"), &[&raster_desc])?;
let raster_layout = made.add(device.create_bind_group_layout(&raster_desc)?);
let raster_pipeline_layout =
made.add(device.create_pipeline_layout(&PipelineLayoutDesc {
label: Some("grass"),
bind_group_layouts: &[raster_layout],
push_constants: None,
})?);
let list = PrimitiveTopology::TriangleList;
let strip = PrimitiveTopology::TriangleStrip;
let raster =
|entries, topology| build_raster(device, raster_pipeline_layout, entries, topology);
let results = pipeline_batch::create(
device,
&mut || {},
[
&|| raster(("vertexMain", "fragmentMain"), list),
&|| raster(("shellVertexMain", "shellFragmentMain"), list),
&|| raster(("finVertexMain", "shellFragmentMain"), list),
&|| raster(("bladeNearVertexMain", "bladeFragmentMain"), strip),
&|| raster(("bladeFarVertexMain", "bladeFragmentMain"), strip),
],
);
for pipeline in results.iter().flatten() {
made.add(*pipeline);
}
let [
raster_pipeline,
shell_pipeline,
fin_pipeline,
blade_near_pipeline,
blade_far_pipeline,
] = results;
let raster_pipeline = raster_pipeline?;
let shell_pipeline = shell_pipeline?;
let fin_pipeline = fin_pipeline?;
let blade_near_pipeline = blade_near_pipeline?;
let blade_far_pipeline = blade_far_pipeline?;
let card_sampler = made.add(device.create_sampler(&SamplerDesc {
label: Some("grass card"),
min_filter: FilterMode::Linear,
mag_filter: FilterMode::Linear,
mip_filter: FilterMode::Linear,
address_mode: [SamplerAddressMode::ClampToEdge; 3],
..SamplerDesc::default()
})?);
let wind_sampler = made.add(device.create_sampler(&SamplerDesc {
label: Some("wind layers"),
min_filter: FilterMode::Linear,
mag_filter: FilterMode::Linear,
mip_filter: FilterMode::Nearest,
address_mode: [SamplerAddressMode::Repeat; 3],
..SamplerDesc::default()
})?);
let mut gen_params = Vec::with_capacity(frames);
let mut wind_params = Vec::with_capacity(frames);
let mut raster_params = Vec::with_capacity(frames);
for _ in 0..frames {
raster_params.push(made.add(device.create_buffer(&BufferDesc {
label: Some("grass params"),
size: PARAMS_SIZE as u64,
usage: BufferUsage::UNIFORM,
memory: MemoryLocation::HostUpload,
})?));
gen_params.push(made.add(device.create_buffer(&BufferDesc {
label: Some("grass generate params"),
size: GEN_PARAMS_SIZE as u64,
usage: BufferUsage::UNIFORM,
memory: MemoryLocation::HostUpload,
})?));
wind_params.push(made.add(device.create_buffer(&BufferDesc {
label: Some("grass wind params"),
size: WIND_PARAMS_SIZE as u64,
usage: BufferUsage::UNIFORM,
memory: MemoryLocation::HostUpload,
})?));
}
made.keep();
Ok(Self {
gen_layout,
gen_pipeline_layout,
clear_pipeline,
generate_pipeline,
raster_layout,
raster_pipeline_layout,
raster_pipeline,
shell_pipeline,
fin_pipeline,
blade_near_pipeline,
blade_far_pipeline,
gen_params,
wind_params,
raster_params,
clear_groups: (0..frames).map(|_| (None, None)).collect(),
gen_groups: (0..frames).map(|_| (None, None)).collect(),
raster_groups: (0..frames).map(|_| (None, None)).collect(),
card_sampler,
wind_sampler,
shadow_sampler,
})
}
pub(crate) fn begin_frame(
&self,
device: &dyn Device,
frame: usize,
generation: GenParams,
wind: WindParams,
raster: Params,
) -> Result<(), HalError> {
device.write_buffer(self.gen_params[frame], 0, &generation.to_bytes())?;
device.write_buffer(self.raster_params[frame], 0, &raster.to_bytes())?;
device.write_buffer(self.wind_params[frame], 0, &wind.to_bytes())
}
pub(crate) fn add_passes<'a>(
&'a mut self,
graph: &mut RenderGraph<'a>,
frame: usize,
images: GrassImages,
inputs: GrassInputs,
) {
let GrassImages {
color,
depth,
shadow_atlas,
} = images;
let GrassInputs {
frame_block,
lights,
cluster_lights,
light_grid,
field,
} = inputs;
let mut imported = |label: &str, buffer| {
graph.import_buffer(
label,
ImportedBuffer {
buffer,
initial: ResourceState::ShaderReadWrite,
final_state: ResourceState::ShaderReadWrite,
},
)
};
let instances_id = imported("grass-instances", field.instances);
let args_id = imported("grass-draw-args", field.args);
let slots = field.slots;
let gen_layout = self.gen_layout;
let gen_pipeline_layout = self.gen_pipeline_layout;
let clear_pipeline = self.clear_pipeline;
let generate_pipeline = self.generate_pipeline;
let gen_params = self.gen_params[frame];
let wind_params = self.wind_params[frame];
let wind_sampler = self.wind_sampler;
let group_of = GenGroup {
layout: gen_layout,
field,
gen_params,
wind_params,
wind_sampler,
};
let (clear_named, clear_cached) = &mut self.clear_groups[frame];
graph
.add_compute_pass("grass-clear")
.use_buffer(args_id, ResourceState::ShaderReadWrite)
.execute(move |ctx| {
let device = ctx.device();
let Some(group) = group_of.build(device, clear_named, clear_cached) else {
return;
};
let encoder = ctx.encoder();
encoder.bind_compute_pipeline(clear_pipeline);
encoder.bind_group(0, group, &[0], gen_pipeline_layout);
encoder.dispatch(slots.div_ceil(WORKGROUP_SIZE), 1, 1);
});
let (gen_named, gen_cached) = &mut self.gen_groups[frame];
graph
.add_compute_pass("grass-generate")
.use_buffer(args_id, ResourceState::ShaderReadWrite)
.use_buffer(instances_id, ResourceState::ShaderReadWrite)
.execute(move |ctx| {
let device = ctx.device();
let Some(group) = group_of.build(device, gen_named, gen_cached) else {
return;
};
let encoder = ctx.encoder();
encoder.bind_compute_pipeline(generate_pipeline);
for slot in 0..slots {
encoder.bind_group(0, group, &[slot * TILE_STRIDE], gen_pipeline_layout);
encoder.dispatch(
(CELLS_PER_TILE * CELLS_PER_TILE).div_ceil(WORKGROUP_SIZE),
1,
1,
);
}
});
let raster_pipeline = self.raster_pipeline;
let shell_pipeline = self.shell_pipeline;
let fin_pipeline = self.fin_pipeline;
let blade_near_pipeline = self.blade_near_pipeline;
let blade_far_pipeline = self.blade_far_pipeline;
let raster_pipeline_layout = self.raster_pipeline_layout;
let raster_layout = self.raster_layout;
let card_sampler = self.card_sampler;
let shadow_sampler = self.shadow_sampler;
let raster_params = self.raster_params[frame];
let (raster_named, raster_cached) = &mut self.raster_groups[frame];
graph
.add_render_pass("grass")
.color(color, LoadOp::Load, StoreOp::Store, ClearValue::default())
.depth(depth, LoadOp::Load, StoreOp::Store, ClearValue::default())
.read_image(shadow_atlas)
.read_buffer(instances_id)
.read_buffer(light_grid)
.use_buffer(args_id, ResourceState::IndirectArgument)
.execute(move |ctx| {
let atlas_view = ctx.image_view(shadow_atlas);
let device = ctx.device();
let now = vec![
field.instances,
field.cells,
field.blades,
field.tiles,
field.field_block,
lights,
];
if raster_named.as_ref() != Some(&now) {
if let Some((_, stale)) = raster_cached.take() {
device.destroy_bind_group(stale);
}
*raster_named = Some(now);
}
let buffer = |binding, buffer| BindGroupEntry {
binding,
array_index: 0,
resource: BindingResource::whole_buffer(buffer),
};
let entries = [
buffer(binding::FRAME, frame_block),
buffer(binding::PARAMS, raster_params),
BindGroupEntry {
binding: binding::TILE,
array_index: 0,
resource: BindingResource::Buffer {
buffer: field.tiles,
offset: 0,
size: TILE_SIZE as u64,
},
},
buffer(binding::INSTANCES, field.instances),
buffer(binding::BLADES, field.blades),
BindGroupEntry {
binding: binding::CARD,
array_index: 0,
resource: BindingResource::ImageView(field.card),
},
BindGroupEntry {
binding: binding::CARD_SAMPLER,
array_index: 0,
resource: BindingResource::Sampler(card_sampler),
},
BindGroupEntry {
binding: binding::SHADOW_ATLAS,
array_index: 0,
resource: BindingResource::ImageView(atlas_view),
},
BindGroupEntry {
binding: binding::SHADOW_SAMPLER,
array_index: 0,
resource: BindingResource::Sampler(shadow_sampler),
},
buffer(binding::LIGHTS, lights),
buffer(binding::CLUSTER_LIGHTS, cluster_lights),
buffer(binding::FIELD, field.field_block),
buffer(binding::CELLS, field.cells),
BindGroupEntry {
binding: binding::GROUND,
array_index: 0,
resource: BindingResource::ImageView(field.ground),
},
buffer(binding::WIND, wind_params),
BindGroupEntry {
binding: binding::WIND_DIRECTION,
array_index: 0,
resource: BindingResource::ImageView(field.wind_direction),
},
BindGroupEntry {
binding: binding::WIND_INTENSITY,
array_index: 0,
resource: BindingResource::ImageView(field.wind_intensity),
},
BindGroupEntry {
binding: binding::WIND_SAMPLER,
array_index: 0,
resource: BindingResource::Sampler(wind_sampler),
},
];
let Some(group) = cached_group(
raster_cached,
device,
&[
(binding::CARD, field.card),
(binding::SHADOW_ATLAS, atlas_view),
(binding::GROUND, field.ground),
(binding::WIND_DIRECTION, field.wind_direction),
(binding::WIND_INTENSITY, field.wind_intensity),
],
"grass",
raster_layout,
&entries,
) else {
return;
};
let encoder = ctx.encoder();
let looks = [
Some((raster_pipeline, CARD_DRAW)),
field.shells.then_some((shell_pipeline, SHELL_DRAW)),
(field.shells && field.fins).then_some((fin_pipeline, FIN_DRAW)),
field
.mesh_blades
.then_some((blade_near_pipeline, BLADE_NEAR_DRAW)),
field
.mesh_blades
.then_some((blade_far_pipeline, BLADE_FAR_DRAW)),
];
for (pipeline, draw) in looks.into_iter().flatten() {
encoder.bind_graphics_pipeline(pipeline);
for slot in 0..slots {
encoder.bind_group(0, group, &[slot * TILE_STRIDE], raster_pipeline_layout);
encoder.draw_indirect(&DrawIndirect {
args: field.args,
offset: u64::from(slot) * SLOT_ARGS_SIZE as u64
+ u64::from(draw) * DRAW_ARGS_SIZE as u64,
draw_count: 1,
stride: DRAW_ARGS_SIZE as u32,
});
}
}
});
}
pub(crate) fn destroy(self, device: &dyn Device) {
for (_, group) in self
.clear_groups
.into_iter()
.filter_map(|(_, cached)| cached)
.chain(self.gen_groups.into_iter().filter_map(|(_, cached)| cached))
.chain(
self.raster_groups
.into_iter()
.filter_map(|(_, cached)| cached),
)
{
device.destroy_bind_group(group);
}
device.destroy_graphics_pipeline(self.blade_far_pipeline);
device.destroy_graphics_pipeline(self.blade_near_pipeline);
device.destroy_graphics_pipeline(self.fin_pipeline);
device.destroy_graphics_pipeline(self.shell_pipeline);
device.destroy_graphics_pipeline(self.raster_pipeline);
device.destroy_pipeline_layout(self.raster_pipeline_layout);
device.destroy_bind_group_layout(self.raster_layout);
device.destroy_compute_pipeline(self.generate_pipeline);
device.destroy_compute_pipeline(self.clear_pipeline);
device.destroy_pipeline_layout(self.gen_pipeline_layout);
device.destroy_bind_group_layout(self.gen_layout);
device.destroy_sampler(self.wind_sampler);
device.destroy_sampler(self.card_sampler);
for buffer in self
.gen_params
.into_iter()
.chain(self.wind_params)
.chain(self.raster_params)
{
device.destroy_buffer(buffer);
}
}
}
fn build_raster(
device: &dyn Device,
layout: PipelineLayoutHandle,
(vertex, fragment): (&'static str, &'static str),
topology: PrimitiveTopology,
) -> Result<GraphicsPipelineHandle, HalError> {
let vertex = crate::forward::named_entry(&GRASS, vertex, Stage::Vertex)?;
let fragment = crate::forward::named_entry(&GRASS, fragment, Stage::Fragment)?;
let module = device.create_shader_module(&ShaderModuleDesc {
label: Some(GRASS.source()),
spirv: GRASS.spirv(),
wgsl: GRASS.wgsl(),
msl: GRASS.msl(),
dxil: &GRASS.dxil_containers(),
})?;
let pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
label: Some(vertex),
layout,
vertex: ShaderEntry {
module,
entry_point: vertex,
},
fragment: Some(ShaderEntry {
module,
entry_point: fragment,
}),
primitive: crcbl_hal::PrimitiveState {
topology,
..crcbl_hal::PrimitiveState::default()
},
depth_stencil: Some(DepthStencilState {
format: crate::forward::SCENE_DEPTH_FORMAT,
depth_write: true,
depth_compare: CompareOp::Greater,
stencil: None,
bias: DepthBias::default(),
}),
multisample: MultisampleState::default(),
color_targets: &[ColorTargetState::opaque(Format::Rgba16Float)],
});
device.destroy_shader_module(module);
pipeline
}
const fn uniform(binding: u32, visibility: ShaderStages, dynamic: bool) -> BindGroupLayoutEntry {
BindGroupLayoutEntry {
binding,
visibility,
kind: BindingKind::UniformBuffer { dynamic },
count: 1,
flags: BindingFlags::empty(),
}
}
const fn storage(
binding: u32,
visibility: ShaderStages,
read_only: bool,
stride: u32,
) -> BindGroupLayoutEntry {
BindGroupLayoutEntry {
binding,
visibility,
kind: BindingKind::StorageBuffer {
read_only,
dynamic: false,
stride,
},
count: 1,
flags: BindingFlags::empty(),
}
}
const fn sampled(
binding: u32,
visibility: ShaderStages,
sample_type: SampleType,
) -> BindGroupLayoutEntry {
BindGroupLayoutEntry {
binding,
visibility,
kind: BindingKind::SampledImage {
view_type: ImageViewType::D2,
sample_type,
},
count: 1,
flags: BindingFlags::empty(),
}
}
const fn sampler(binding: u32, visibility: ShaderStages) -> BindGroupLayoutEntry {
BindGroupLayoutEntry {
binding,
visibility,
kind: BindingKind::Sampler { comparison: false },
count: 1,
flags: BindingFlags::empty(),
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests;