use core::fmt;
use crcbl_hal::{
Barriers, BufferBarrier, BufferHandle, BufferUsage, ClearValue, ColorAttachment,
CommandEncoder, ComputePassDesc, DepthStencilAttachment, Device, Format, HalError, ImageAspect,
ImageBarrier, ImageHandle, ImageSubresourceRange, ImageUsage, ImageViewHandle, LoadOp,
QueueHandle, QueueTransfer, Rect2d, RenderPassDesc, ResourceState, StoreOp, Viewport, depth,
};
use crate::timing::PassTimers;
use crate::transient::{TransientBufferDesc, TransientImageDesc, TransientPool, TransientUse};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ImageId(u32);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct BufferId(u32);
impl ImageId {
fn index(self) -> usize {
self.0 as usize
}
}
impl BufferId {
fn index(self) -> usize {
self.0 as usize
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InitialClaim {
Tracked,
Acquired,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ImportedImage {
pub image: ImageHandle,
pub view: ImageViewHandle,
pub format: Format,
pub extent: (u32, u32),
pub initial: ResourceState,
pub claim: InitialClaim,
pub final_state: ResourceState,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ImportedBuffer {
pub buffer: BufferHandle,
pub initial: ResourceState,
pub final_state: ResourceState,
}
#[derive(Clone, Copy, Debug)]
enum ImageSource {
Imported(ImportedImage),
Transient(TransientImageDesc),
}
#[derive(Clone, Copy, Debug)]
enum BufferSource {
Imported(ImportedBuffer),
Transient(TransientBufferDesc),
}
#[derive(Clone, Debug)]
struct ImageNode {
label: String,
source: ImageSource,
}
#[derive(Clone, Debug)]
struct BufferNode {
label: String,
source: BufferSource,
}
impl ImageNode {
fn format(&self) -> Format {
match self.source {
ImageSource::Imported(imported) => imported.format,
ImageSource::Transient(desc) => desc.format,
}
}
fn extent(&self) -> (u32, u32) {
match self.source {
ImageSource::Imported(imported) => imported.extent,
ImageSource::Transient(desc) => desc.extent,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Attachment {
Color {
index: u32,
load: LoadOp,
store: StoreOp,
clear: ClearValue,
},
Depth {
load: LoadOp,
store: StoreOp,
clear: ClearValue,
write: bool,
},
}
#[derive(Clone, Copy, Debug)]
struct ImageAccess {
image: ImageId,
state: ResourceState,
attachment: Option<Attachment>,
range: Option<ImageSubresourceRange>,
}
#[derive(Clone, Copy, Debug)]
struct BufferAccess {
buffer: BufferId,
state: ResourceState,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PassKind {
Render,
Compute,
Copy,
}
impl PassKind {
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::Render => "render",
Self::Compute => "compute",
Self::Copy => "copy",
}
}
}
type PassBody<'a> = Box<dyn FnOnce(&mut PassContext<'_>) + 'a>;
struct Pass<'a> {
label: String,
kind: PassKind,
queue: QueueHandle,
images: Vec<ImageAccess>,
buffers: Vec<BufferAccess>,
body: PassBody<'a>,
}
impl fmt::Debug for Pass<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Pass")
.field("label", &self.label)
.field("kind", &self.kind)
.field("images", &self.images)
.field("buffers", &self.buffers)
.finish_non_exhaustive()
}
}
pub struct RenderGraph<'a> {
images: Vec<ImageNode>,
buffers: Vec<BufferNode>,
passes: Vec<Pass<'a>>,
default_queue: QueueHandle,
import_conflict: Option<GraphError>,
}
impl fmt::Debug for RenderGraph<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RenderGraph")
.field("images", &self.images)
.field("buffers", &self.buffers)
.field("passes", &self.passes)
.field("import_conflict", &self.import_conflict)
.finish()
}
}
impl<'a> RenderGraph<'a> {
#[must_use]
pub fn new(queue: QueueHandle) -> Self {
Self {
images: Vec::new(),
buffers: Vec::new(),
passes: Vec::new(),
default_queue: queue,
import_conflict: None,
}
}
pub fn create_image(&mut self, label: impl Into<String>, desc: TransientImageDesc) -> ImageId {
let id = ImageId(u32::try_from(self.images.len()).expect("a frame has few resources"));
self.images.push(ImageNode {
label: label.into(),
source: ImageSource::Transient(desc),
});
id
}
pub fn create_buffer(
&mut self,
label: impl Into<String>,
desc: TransientBufferDesc,
) -> BufferId {
let id = BufferId(u32::try_from(self.buffers.len()).expect("a frame has few resources"));
self.buffers.push(BufferNode {
label: label.into(),
source: BufferSource::Transient(desc),
});
id
}
pub fn import_image(&mut self, label: impl Into<String>, imported: ImportedImage) -> ImageId {
let existing = self
.images
.iter()
.enumerate()
.find_map(|(index, node)| match node.source {
ImageSource::Imported(existing) if existing.image == imported.image => {
Some((index, existing))
}
_ => None,
});
if let Some((index, first)) = existing {
if let Some((field, first, second)) = image_import_conflict(&first, &imported) {
self.record_import_conflict(GraphError::ImportDeclarationConflict {
resource: self.images[index].label.clone(),
field,
first,
second,
});
}
return ImageId(u32::try_from(index).expect("a frame has few resources"));
}
let id = ImageId(u32::try_from(self.images.len()).expect("a frame has few resources"));
self.images.push(ImageNode {
label: label.into(),
source: ImageSource::Imported(imported),
});
id
}
pub fn import_buffer(
&mut self,
label: impl Into<String>,
imported: ImportedBuffer,
) -> BufferId {
let existing =
self.buffers
.iter()
.enumerate()
.find_map(|(index, node)| match node.source {
BufferSource::Imported(existing) if existing.buffer == imported.buffer => {
Some((index, existing))
}
_ => None,
});
if let Some((index, first)) = existing {
if let Some((field, first, second)) = buffer_import_conflict(&first, &imported) {
self.record_import_conflict(GraphError::BufferImportDeclarationConflict {
resource: self.buffers[index].label.clone(),
field,
first,
second,
});
}
return BufferId(u32::try_from(index).expect("a frame has few resources"));
}
let id = BufferId(u32::try_from(self.buffers.len()).expect("a frame has few resources"));
self.buffers.push(BufferNode {
label: label.into(),
source: BufferSource::Imported(imported),
});
id
}
fn record_import_conflict(&mut self, error: GraphError) {
if self.import_conflict.is_none() {
self.import_conflict = Some(error);
}
}
pub fn add_render_pass(&mut self, label: impl Into<String>) -> PassBuilder<'_, 'a> {
PassBuilder::new(self, PassKind::Render, label.into())
}
pub fn add_compute_pass(&mut self, label: impl Into<String>) -> PassBuilder<'_, 'a> {
PassBuilder::new(self, PassKind::Compute, label.into())
}
pub fn add_copy_pass(&mut self, label: impl Into<String>) -> PassBuilder<'_, 'a> {
PassBuilder::new(self, PassKind::Copy, label.into())
}
#[must_use]
pub fn pass_count(&self) -> usize {
self.passes.len()
}
#[must_use]
pub fn image_facts(&self, image: ImageId) -> Option<(Format, (u32, u32), Option<ImageUsage>)> {
let node = self.images.get(image.index())?;
let usage = match node.source {
ImageSource::Imported(_) => None,
ImageSource::Transient(desc) => Some(desc.usage),
};
Some((node.format(), node.extent(), usage))
}
pub fn compile(self, pool: &TransientPool) -> Result<CompiledGraph<'a>, GraphError> {
compile(self, pool)
}
}
#[must_use = "a pass reaches the graph only through `execute`"]
pub struct PassBuilder<'g, 'a> {
graph: &'g mut RenderGraph<'a>,
kind: PassKind,
label: String,
queue: QueueHandle,
images: Vec<ImageAccess>,
buffers: Vec<BufferAccess>,
next_color: u32,
}
impl fmt::Debug for PassBuilder<'_, '_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PassBuilder")
.field("label", &self.label)
.field("kind", &self.kind)
.finish_non_exhaustive()
}
}
impl<'g, 'a> PassBuilder<'g, 'a> {
fn new(graph: &'g mut RenderGraph<'a>, kind: PassKind, label: String) -> Self {
let queue = graph.default_queue;
Self {
graph,
kind,
label,
queue,
images: Vec::new(),
buffers: Vec::new(),
next_color: 0,
}
}
pub fn on_queue(mut self, queue: QueueHandle) -> Self {
self.queue = queue;
self
}
pub fn color(
mut self,
image: ImageId,
load: LoadOp,
store: StoreOp,
clear: ClearValue,
) -> Self {
let index = self.next_color;
self.next_color += 1;
self.images.push(ImageAccess {
image,
state: ResourceState::ColorAttachment,
attachment: Some(Attachment::Color {
index,
load,
store,
clear,
}),
range: None,
});
self
}
pub fn clear_color(self, image: ImageId, rgba: [f32; 4]) -> Self {
self.color(
image,
LoadOp::Clear,
StoreOp::Store,
ClearValue::color(rgba),
)
}
pub fn depth(
mut self,
image: ImageId,
load: LoadOp,
store: StoreOp,
clear: ClearValue,
) -> Self {
self.images.push(ImageAccess {
image,
state: ResourceState::DepthStencilWrite,
attachment: Some(Attachment::Depth {
load,
store,
clear,
write: true,
}),
range: None,
});
self
}
pub fn clear_depth(self, image: ImageId) -> Self {
self.depth(
image,
LoadOp::Clear,
StoreOp::Discard,
ClearValue {
depth: depth::CLEAR,
..ClearValue::default()
},
)
}
pub fn depth_read(mut self, image: ImageId) -> Self {
self.images.push(ImageAccess {
image,
state: ResourceState::DepthStencilRead,
attachment: Some(Attachment::Depth {
load: LoadOp::Load,
store: StoreOp::Store,
clear: ClearValue::default(),
write: false,
}),
range: None,
});
self
}
pub fn read_image(self, image: ImageId) -> Self {
self.use_image(image, ResourceState::ShaderRead)
}
pub fn read_subresource(self, image: ImageId, range: ImageSubresourceRange) -> Self {
self.use_subresource(image, ResourceState::ShaderRead, range)
}
pub fn use_image(mut self, image: ImageId, state: ResourceState) -> Self {
self.images.push(ImageAccess {
image,
state,
attachment: None,
range: None,
});
self
}
pub fn use_subresource(
mut self,
image: ImageId,
state: ResourceState,
range: ImageSubresourceRange,
) -> Self {
self.images.push(ImageAccess {
image,
state,
attachment: None,
range: Some(range),
});
self
}
pub fn read_buffer(self, buffer: BufferId) -> Self {
self.use_buffer(buffer, ResourceState::ShaderRead)
}
pub fn index_buffer(self, buffer: BufferId) -> Self {
self.use_buffer(buffer, ResourceState::IndexBuffer)
}
pub fn use_buffer(mut self, buffer: BufferId, state: ResourceState) -> Self {
self.buffers.push(BufferAccess { buffer, state });
self
}
pub fn execute(self, body: impl FnOnce(&mut PassContext<'_>) + 'a) {
self.graph.passes.push(Pass {
label: self.label,
kind: self.kind,
queue: self.queue,
images: self.images,
buffers: self.buffers,
body: Box::new(body),
});
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GraphImageBarrier {
pub image: ImageId,
pub from: ResourceState,
pub to: ResourceState,
pub queue_transfer: Option<QueueTransfer>,
pub range: Option<ImageSubresourceRange>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GraphBufferBarrier {
pub buffer: BufferId,
pub from: ResourceState,
pub to: ResourceState,
pub queue_transfer: Option<QueueTransfer>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct GraphBarriers {
pub images: Vec<GraphImageBarrier>,
pub buffers: Vec<GraphBufferBarrier>,
}
impl GraphBarriers {
#[must_use]
pub fn is_empty(&self) -> bool {
self.images.is_empty() && self.buffers.is_empty()
}
#[must_use]
pub fn len(&self) -> usize {
self.images.len() + self.buffers.len()
}
}
pub struct CompiledPass<'a> {
label: String,
kind: PassKind,
queue: QueueHandle,
barriers: GraphBarriers,
release_barriers: GraphBarriers,
images: Vec<ImageAccess>,
buffers: Vec<BufferAccess>,
render_area: Rect2d,
body: PassBody<'a>,
}
impl fmt::Debug for CompiledPass<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CompiledPass")
.field("label", &self.label)
.field("kind", &self.kind)
.field("barriers", &self.barriers)
.finish_non_exhaustive()
}
}
impl CompiledPass<'_> {
#[must_use]
pub fn label(&self) -> &str {
&self.label
}
#[must_use]
pub const fn kind(&self) -> PassKind {
self.kind
}
#[must_use]
pub const fn barriers(&self) -> &GraphBarriers {
&self.barriers
}
#[must_use]
pub const fn release_barriers(&self) -> &GraphBarriers {
&self.release_barriers
}
#[must_use]
pub const fn queue(&self) -> QueueHandle {
self.queue
}
#[must_use]
pub const fn render_area(&self) -> Rect2d {
self.render_area
}
#[must_use]
pub fn reads_buffer(&self, buffer: BufferId) -> bool {
self.buffers
.iter()
.any(|access| access.buffer == buffer && access.state == ResourceState::ShaderRead)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Slot {
Imported,
Transient(usize),
}
pub struct CompiledGraph<'a> {
images: Vec<ImageNode>,
buffers: Vec<BufferNode>,
passes: Vec<CompiledPass<'a>>,
final_barriers: GraphBarriers,
image_slots: Vec<Slot>,
buffer_slots: Vec<Slot>,
transient_images: Vec<TransientImageDesc>,
transient_buffers: Vec<TransientBufferDesc>,
transient_image_end: Vec<TransientUse>,
transient_buffer_end: Vec<TransientUse>,
imported_image_end: Vec<(ImageHandle, ResourceState)>,
imported_buffer_end: Vec<(BufferHandle, ResourceState)>,
}
impl fmt::Debug for CompiledGraph<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CompiledGraph")
.field("passes", &self.passes)
.field("final_barriers", &self.final_barriers)
.field("transient_images", &self.transient_images)
.field("transient_buffers", &self.transient_buffers)
.finish_non_exhaustive()
}
}
impl<'a> CompiledGraph<'a> {
#[must_use]
pub fn passes(&self) -> &[CompiledPass<'a>] {
&self.passes
}
#[must_use]
pub const fn final_barriers(&self) -> &GraphBarriers {
&self.final_barriers
}
#[must_use]
pub fn physical_image_count(&self) -> usize {
self.transient_images.len()
}
#[must_use]
pub fn physical_buffer_count(&self) -> usize {
self.transient_buffers.len()
}
#[must_use]
pub fn images_alias(&self, first: ImageId, second: ImageId) -> bool {
matches!(
(
self.image_slots.get(first.index()),
self.image_slots.get(second.index())
),
(Some(Slot::Transient(a)), Some(Slot::Transient(b))) if a == b
)
}
#[must_use]
pub fn barrier_batches(&self) -> Vec<&GraphBarriers> {
self.passes
.iter()
.flat_map(|pass| [&pass.barriers, &pass.release_barriers])
.chain(core::iter::once(&self.final_barriers))
.filter(|batch| !batch.is_empty())
.collect()
}
#[must_use]
pub fn dump(&self) -> String {
let mut out = String::new();
self.write_dump(&mut out).expect("writing to a String");
out
}
fn write_dump(&self, out: &mut impl fmt::Write) -> fmt::Result {
let aliased = self
.image_slots
.iter()
.filter(|slot| matches!(slot, Slot::Transient(_)))
.count()
.saturating_sub(self.transient_images.len());
writeln!(
out,
"render graph: {} pass(es), {} transient image(s) on {} physical, \
{} transient buffer(s) on {} physical, {} barrier(s)",
self.passes.len(),
self.transient_image_users(),
self.transient_images.len(),
self.transient_buffer_users(),
self.transient_buffers.len(),
self.passes
.iter()
.map(|pass| pass.barriers.len() + pass.release_barriers.len())
.sum::<usize>()
+ self.final_barriers.len(),
)?;
if aliased > 0 {
writeln!(out, " aliasing saved {aliased} physical image(s)")?;
}
for (index, pass) in self.passes.iter().enumerate() {
self.write_barriers(out, &pass.barriers, &format!("[{index}] "))?;
writeln!(
out,
"[{index}] {} pass {:?} {}x{}",
pass.kind.name(),
pass.label,
pass.render_area.width,
pass.render_area.height
)?;
for access in &pass.images {
let node = &self.images[access.image.index()];
let role = match access.attachment {
Some(Attachment::Color {
index, load, store, ..
}) => {
format!("color[{index}] load={load:?} store={store:?}")
}
Some(Attachment::Depth {
load, store, write, ..
}) => format!(
"depth load={load:?} store={store:?} write={}",
if write { "yes" } else { "no" }
),
None => "sampled/storage".to_string(),
};
writeln!(
out,
" image {:<20} {:<20} {role} [{}]",
node.label,
format!("{:?}", access.state),
self.slot_note(self.image_slots[access.image.index()]),
)?;
}
for access in &pass.buffers {
let node = &self.buffers[access.buffer.index()];
writeln!(
out,
" buffer {:<20} {:<20} [{}]",
node.label,
format!("{:?}", access.state),
self.slot_note(self.buffer_slots[access.buffer.index()]),
)?;
}
self.write_barriers(out, &pass.release_barriers, &format!("[{index}] release "))?;
}
self.write_barriers(out, &self.final_barriers, "[final] ")?;
Ok(())
}
fn transient_image_users(&self) -> usize {
self.image_slots
.iter()
.filter(|slot| matches!(slot, Slot::Transient(_)))
.count()
}
fn transient_buffer_users(&self) -> usize {
self.buffer_slots
.iter()
.filter(|slot| matches!(slot, Slot::Transient(_)))
.count()
}
fn slot_note(&self, slot: Slot) -> String {
match slot {
Slot::Imported => "imported".to_string(),
Slot::Transient(index) => format!("transient #{index}"),
}
}
fn write_barriers(
&self,
out: &mut impl fmt::Write,
barriers: &GraphBarriers,
prefix: &str,
) -> fmt::Result {
if barriers.is_empty() {
return Ok(());
}
writeln!(out, "{prefix}barriers ({})", barriers.len())?;
for barrier in &barriers.images {
writeln!(
out,
" image {:<20} {:>18} -> {:<18}{}",
self.images[barrier.image.index()].label,
format!("{:?}", barrier.from),
format!("{:?}", barrier.to),
queue_note(barrier.queue_transfer),
)?;
}
for barrier in &barriers.buffers {
writeln!(
out,
" buffer {:<20} {:>18} -> {:<18}{}",
self.buffers[barrier.buffer.index()].label,
format!("{:?}", barrier.from),
format!("{:?}", barrier.to),
queue_note(barrier.queue_transfer),
)?;
}
Ok(())
}
pub fn execute(
self,
device: &dyn Device,
pool: &mut TransientPool,
encoder: &mut dyn CommandEncoder,
mut timers: Option<&mut PassTimers>,
) -> Result<(), GraphError> {
let realised = self.realise(device, pool)?;
let Self {
images,
passes,
final_barriers,
transient_images,
transient_buffers,
transient_image_end,
transient_buffer_end,
imported_image_end,
imported_buffer_end,
..
} = self;
if let Some(timers) = timers.as_deref_mut() {
timers.begin_frame(device, encoder, &passes);
}
for (index, pass) in passes.into_iter().enumerate() {
emit(encoder, &images, &realised, &pass.barriers);
let timestamp_writes = timers
.as_deref()
.and_then(|timers| timers.pass_writes(index));
match pass.kind {
PassKind::Render => {
let (colors, depth_stencil) = attachments(&realised, &pass.images);
encoder.begin_render_pass(&RenderPassDesc {
label: Some(&pass.label),
color_attachments: &colors,
depth_stencil_attachment: depth_stencil,
render_area: pass.render_area,
timestamp_writes,
});
encoder.set_viewport(&Viewport::from_size(
pass.render_area.width,
pass.render_area.height,
));
encoder.set_scissor(&pass.render_area);
}
PassKind::Compute => {
encoder.begin_compute_pass(&ComputePassDesc {
label: Some(&pass.label),
timestamp_writes,
});
}
PassKind::Copy => {}
}
{
let mut context = PassContext {
device,
encoder,
realised: &realised,
render_area: pass.render_area,
};
(pass.body)(&mut context);
}
match pass.kind {
PassKind::Render => encoder.end_render_pass(),
PassKind::Compute => encoder.end_compute_pass(),
PassKind::Copy => {}
}
emit(encoder, &images, &realised, &pass.release_barriers);
}
emit(encoder, &images, &realised, &final_barriers);
for (slot, desc) in transient_images.iter().enumerate() {
pool.set_image_use(
*desc,
ordinal(&transient_images, slot),
transient_image_end[slot],
);
}
for (slot, desc) in transient_buffers.iter().enumerate() {
pool.set_buffer_use(
*desc,
ordinal(&transient_buffers, slot),
transient_buffer_end[slot],
);
}
for (image, state) in imported_image_end {
pool.set_imported_image_use(image, state);
}
for (buffer, state) in imported_buffer_end {
pool.set_imported_buffer_use(buffer, state);
}
Ok(())
}
fn realise(
&self,
device: &dyn Device,
pool: &mut TransientPool,
) -> Result<Realised, GraphError> {
pool.begin_frame();
let mut physical_images = Vec::with_capacity(self.transient_images.len());
for desc in &self.transient_images {
physical_images.push(pool.image(device, *desc)?);
}
let mut physical_buffers = Vec::with_capacity(self.transient_buffers.len());
for desc in &self.transient_buffers {
physical_buffers.push(pool.buffer(device, *desc)?);
}
let images = self
.images
.iter()
.zip(&self.image_slots)
.map(|(node, slot)| match (slot, node.source) {
(Slot::Imported, ImageSource::Imported(imported)) => {
(imported.image, imported.view)
}
(Slot::Transient(index), _) => physical_images[*index],
(Slot::Imported, ImageSource::Transient(_)) => {
unreachable!("a transient image was assigned the imported slot")
}
})
.collect();
let buffers = self
.buffers
.iter()
.zip(&self.buffer_slots)
.map(|(node, slot)| match (slot, node.source) {
(Slot::Imported, BufferSource::Imported(imported)) => imported.buffer,
(Slot::Transient(index), _) => physical_buffers[*index],
(Slot::Imported, BufferSource::Transient(_)) => {
unreachable!("a transient buffer was assigned the imported slot")
}
})
.collect();
Ok(Realised { images, buffers })
}
}
fn queue_note(transfer: Option<QueueTransfer>) -> String {
transfer.map_or_else(String::new, |transfer| {
format!(" queue {:?} -> {:?}", transfer.from, transfer.to)
})
}
#[derive(Debug)]
struct Realised {
images: Vec<(ImageHandle, ImageViewHandle)>,
buffers: Vec<BufferHandle>,
}
#[derive(Debug)]
pub struct PassContext<'a> {
device: &'a dyn Device,
encoder: &'a mut dyn CommandEncoder,
realised: &'a Realised,
render_area: Rect2d,
}
impl PassContext<'_> {
pub fn encoder(&mut self) -> &mut dyn CommandEncoder {
self.encoder
}
#[must_use]
pub fn device(&self) -> &dyn Device {
self.device
}
#[must_use]
pub fn image(&self, id: ImageId) -> ImageHandle {
self.realised.images[id.index()].0
}
#[must_use]
pub fn image_view(&self, id: ImageId) -> ImageViewHandle {
self.realised.images[id.index()].1
}
#[must_use]
pub fn buffer(&self, id: BufferId) -> BufferHandle {
self.realised.buffers[id.index()]
}
#[must_use]
pub const fn render_area(&self) -> Rect2d {
self.render_area
}
}
fn emit(
encoder: &mut dyn CommandEncoder,
images: &[ImageNode],
realised: &Realised,
barriers: &GraphBarriers,
) {
if barriers.is_empty() {
return;
}
let image_barriers: Vec<ImageBarrier> = barriers
.images
.iter()
.map(|barrier| ImageBarrier {
image: realised.images[barrier.image.index()].0,
range: barrier.range.unwrap_or_else(|| {
ImageSubresourceRange::all(images[barrier.image.index()].format())
}),
from: barrier.from,
to: barrier.to,
queue_transfer: barrier.queue_transfer,
})
.collect();
let buffer_barriers: Vec<BufferBarrier> = barriers
.buffers
.iter()
.map(|barrier| BufferBarrier {
buffer: realised.buffers[barrier.buffer.index()],
from: barrier.from,
to: barrier.to,
queue_transfer: barrier.queue_transfer,
})
.collect();
encoder.pipeline_barrier(&Barriers {
buffers: &buffer_barriers,
images: &image_barriers,
global: false,
});
}
fn attachments(
realised: &Realised,
accesses: &[ImageAccess],
) -> (Vec<ColorAttachment>, Option<DepthStencilAttachment>) {
let mut colors: Vec<(u32, ColorAttachment)> = Vec::new();
let mut depth_stencil = None;
for access in accesses {
let view = realised.images[access.image.index()].1;
match access.attachment {
Some(Attachment::Color {
index,
load,
store,
clear,
}) => colors.push((
index,
ColorAttachment {
view,
resolve: None,
load,
store,
clear,
},
)),
Some(Attachment::Depth {
load,
store,
clear,
write,
}) => {
depth_stencil = Some(DepthStencilAttachment {
view,
read_only: !write,
depth_load: load,
depth_store: store,
stencil_load: LoadOp::DontCare,
stencil_store: StoreOp::Discard,
clear,
});
}
None => {}
}
}
colors.sort_by_key(|(index, _)| *index);
(
colors
.into_iter()
.map(|(_, attachment)| attachment)
.collect(),
depth_stencil,
)
}
#[derive(Debug, thiserror::Error)]
pub enum GraphError {
#[error(
"pass `{pass}` accesses `{resource}` as both {first:?} and {second:?}; a resource is in \
one state per pass, so this needs two passes or one state"
)]
ConflictingAccess {
pass: String,
resource: String,
first: ResourceState,
second: ResourceState,
},
#[error(
"render pass `{pass}` has no attachments; a pass that renders nowhere is a declaration \
mistake, not an optimisation"
)]
NoAttachments {
pass: String,
},
#[error(
"render pass `{pass}` attaches `{first}` at {first_extent:?} and `{second}` at \
{second_extent:?}; every attachment must be the same size"
)]
AttachmentExtentMismatch {
pass: String,
first: String,
first_extent: (u32, u32),
second: String,
second_extent: (u32, u32),
},
#[error("render pass `{pass}` attaches more than one depth image")]
DuplicateDepthAttachment {
pass: String,
},
#[error(
"pass `{pass}` declares `{resource}` twice over the same subrange; a resource is declared \
once per pass, and two attachments over one view is not a second attachment"
)]
DuplicateDeclaration {
pass: String,
resource: String,
},
#[error(
"pass `{pass}` uses `{resource}` at mip {base_mip}+{mip_count} / layer \
{base_layer}+{layer_count}, but the image has {mip_levels} mip level(s) and \
{layers} layer(s); a barrier on a subresource that does not exist covers nothing"
)]
SubresourceOutOfRange {
pass: String,
resource: String,
base_mip: u32,
mip_count: u32,
base_layer: u32,
layer_count: u32,
mip_levels: u32,
layers: u32,
},
#[error("{kind} pass `{pass}` attaches `{resource}`; only a render pass has attachments")]
AttachmentOutsideRenderPass {
kind: &'static str,
pass: String,
resource: String,
},
#[error(
"`{resource}` is a transient no pass reads or writes; either a pass forgot to declare it \
or the resource should not have been created"
)]
UnusedTransient {
resource: String,
},
#[error(
"`{resource}` is imported as {declared:?}, but the last graph left it in {left:?}; a \
barrier out of a state the image is not in carries the wrong source scope — declare \
what was left, or say `InitialClaim::Acquired` if a semaphore already orders this frame"
)]
ImportStateMismatch {
resource: String,
declared: ResourceState,
left: ResourceState,
},
#[error(
"`{resource}` is imported as {declared:?}, but the last graph left it in {left:?}; a \
barrier out of a state the buffer is not in carries the wrong source scope, and \
`Undefined` carries none at all — declare what was left"
)]
BufferImportStateMismatch {
resource: String,
declared: ResourceState,
left: ResourceState,
},
#[error(
"`{resource}` is imported more than once with different declarations: `{field}` is \
{first} in one and {second} in the other; one handle is one node with one state \
tracker, so the graph cannot honour both — import it once and share the id"
)]
ImportDeclarationConflict {
resource: String,
field: ImportField,
first: String,
second: String,
},
#[error(
"`{resource}` is imported more than once with different declarations: `{field}` is \
{first} in one and {second} in the other; one handle is one node with one state \
tracker, so the graph cannot honour both — import it once and share the id"
)]
BufferImportDeclarationConflict {
resource: String,
field: ImportField,
first: String,
second: String,
},
#[error(transparent)]
Hal(#[from] HalError),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ImportField {
View,
Format,
Extent,
Initial,
Claim,
FinalState,
}
impl fmt::Display for ImportField {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::View => "view",
Self::Format => "format",
Self::Extent => "extent",
Self::Initial => "initial",
Self::Claim => "claim",
Self::FinalState => "final_state",
})
}
}
fn image_import_conflict(
first: &ImportedImage,
second: &ImportedImage,
) -> Option<(ImportField, String, String)> {
let ImportedImage {
image: _,
view: _,
format: _,
extent: _,
initial: _,
claim: _,
final_state: _,
} = first;
if first.view != second.view {
return Some((
ImportField::View,
format!("{:?}", first.view),
format!("{:?}", second.view),
));
}
if first.format != second.format {
return Some((
ImportField::Format,
format!("{:?}", first.format),
format!("{:?}", second.format),
));
}
if first.extent != second.extent {
return Some((
ImportField::Extent,
format!("{:?}", first.extent),
format!("{:?}", second.extent),
));
}
if first.initial != second.initial {
return Some((
ImportField::Initial,
format!("{:?}", first.initial),
format!("{:?}", second.initial),
));
}
if first.claim != second.claim {
return Some((
ImportField::Claim,
format!("{:?}", first.claim),
format!("{:?}", second.claim),
));
}
if first.final_state != second.final_state {
return Some((
ImportField::FinalState,
format!("{:?}", first.final_state),
format!("{:?}", second.final_state),
));
}
None
}
fn buffer_import_conflict(
first: &ImportedBuffer,
second: &ImportedBuffer,
) -> Option<(ImportField, String, String)> {
let ImportedBuffer {
buffer: _,
initial: _,
final_state: _,
} = first;
if first.initial != second.initial {
return Some((
ImportField::Initial,
format!("{:?}", first.initial),
format!("{:?}", second.initial),
));
}
if first.final_state != second.final_state {
return Some((
ImportField::FinalState,
format!("{:?}", first.final_state),
format!("{:?}", second.final_state),
));
}
None
}
const TRANSIENT_LAYERS: u32 = 1;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Tracked {
state: ResourceState,
queue: Option<QueueHandle>,
last_pass: Option<usize>,
}
impl Tracked {
const fn carried(last: TransientUse) -> Self {
Self {
state: last.state,
queue: last.queue,
last_pass: None,
}
}
const fn declared(state: ResourceState) -> Self {
Self {
state,
queue: None,
last_pass: None,
}
}
const fn end(self) -> TransientUse {
TransientUse {
state: self.state,
queue: self.queue,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Subrect {
mips: (u32, u32),
layers: (u32, u32),
}
impl Subrect {
const UNBOUNDED: Self = Self {
mips: (0, u32::MAX),
layers: (0, u32::MAX),
};
const fn bounded(mip_levels: u32, layers: u32) -> Self {
Self {
mips: (0, mip_levels),
layers: (0, layers),
}
}
const fn is_empty(self) -> bool {
self.mips.0 >= self.mips.1 || self.layers.0 >= self.layers.1
}
fn intersect(self, other: Self) -> Self {
Self {
mips: (self.mips.0.max(other.mips.0), self.mips.1.min(other.mips.1)),
layers: (
self.layers.0.max(other.layers.0),
self.layers.1.min(other.layers.1),
),
}
}
fn subtract(self, cut: Self) -> Vec<Self> {
let mut out = Vec::new();
if cut.mips.0 > self.mips.0 {
out.push(Self {
mips: (self.mips.0, cut.mips.0),
layers: self.layers,
});
}
if self.mips.1 > cut.mips.1 {
out.push(Self {
mips: (cut.mips.1, self.mips.1),
layers: self.layers,
});
}
if cut.layers.0 > self.layers.0 {
out.push(Self {
mips: cut.mips,
layers: (self.layers.0, cut.layers.0),
});
}
if self.layers.1 > cut.layers.1 {
out.push(Self {
mips: cut.mips,
layers: (cut.layers.1, self.layers.1),
});
}
out
}
fn to_range(self, aspect: crcbl_hal::ImageAspect) -> ImageSubresourceRange {
ImageSubresourceRange {
aspect,
base_mip: self.mips.0,
mip_count: if self.mips.1 == u32::MAX {
ImageSubresourceRange::ALL
} else {
self.mips.1 - self.mips.0
},
base_layer: self.layers.0,
layer_count: if self.layers.1 == u32::MAX {
ImageSubresourceRange::ALL
} else {
self.layers.1 - self.layers.0
},
}
}
}
fn subrect_of(range: ImageSubresourceRange, bounds: Subrect) -> Subrect {
let mip_end = if range.mip_count == ImageSubresourceRange::ALL {
bounds.mips.1
} else {
range.base_mip.saturating_add(range.mip_count)
};
let layer_end = if range.layer_count == ImageSubresourceRange::ALL {
bounds.layers.1
} else {
range.base_layer.saturating_add(range.layer_count)
};
Subrect {
mips: (range.base_mip, mip_end),
layers: (range.base_layer, layer_end),
}
}
#[derive(Clone, Copy, Debug)]
struct SubBarrier {
from: ResourceState,
queue_transfer: Option<QueueTransfer>,
rect: Option<Subrect>,
last_pass: Option<usize>,
}
#[derive(Clone, Debug)]
struct ImageTracker {
bounds: Subrect,
segments: Vec<(Subrect, Tracked)>,
}
impl ImageTracker {
fn new(bounds: Subrect, tracked: Tracked) -> Self {
Self {
bounds,
segments: vec![(bounds, tracked)],
}
}
fn transition(
&mut self,
rect: Subrect,
want: ResourceState,
queue: QueueHandle,
pass: usize,
) -> Vec<SubBarrier> {
let mut outside: Vec<(Subrect, Tracked)> = Vec::new();
let mut inside: Vec<(Subrect, Tracked)> = Vec::new();
for (segment, tracked) in self.segments.drain(..) {
let overlap = segment.intersect(rect);
if overlap.is_empty() {
outside.push((segment, tracked));
continue;
}
outside.extend(
segment
.subtract(overlap)
.into_iter()
.map(|piece| (piece, tracked)),
);
inside.push((overlap, tracked));
}
let mut barriers = Vec::new();
for (piece, tracked) in &inside {
let queue_transfer = match tracked.queue {
Some(previous) if previous != queue => Some(QueueTransfer {
from: previous,
to: queue,
}),
_ => None,
};
if ResourceState::needs_barrier(tracked.state, want) || queue_transfer.is_some() {
barriers.push(SubBarrier {
from: tracked.state,
queue_transfer,
rect: Some(*piece),
last_pass: tracked.last_pass,
});
}
}
if barriers.len() == inside.len()
&& barriers.windows(2).all(|pair| {
pair[0].from == pair[1].from && pair[0].queue_transfer == pair[1].queue_transfer
})
{
barriers.truncate(1.min(barriers.len()));
if let Some(first) = barriers.first_mut() {
first.rect = None;
}
}
let entered = Tracked {
state: want,
queue: Some(queue),
last_pass: Some(pass),
};
self.segments = outside;
for (piece, tracked) in inside {
let state = if ResourceState::needs_barrier(tracked.state, want) {
want
} else {
tracked.state
};
self.segments.push((piece, Tracked { state, ..entered }));
}
self.coalesce();
barriers
}
fn coalesce(&mut self) {
let Some((_, first)) = self.segments.first().copied() else {
return;
};
if self.segments.iter().all(|(_, tracked)| *tracked == first) {
self.segments = vec![(self.bounds, first)];
}
}
fn end(&self) -> TransientUse {
self.segments
.iter()
.find(|(rect, _)| {
rect.mips.0 == self.bounds.mips.0 && rect.layers.0 == self.bounds.layers.0
})
.or_else(|| self.segments.first())
.map_or_else(TransientUse::default, |(_, tracked)| tracked.end())
}
}
fn ordinal<D: PartialEq>(descs: &[D], at: usize) -> usize {
descs[..at]
.iter()
.filter(|other| **other == descs[at])
.count()
}
fn compile<'a>(
graph: RenderGraph<'a>,
pool: &TransientPool,
) -> Result<CompiledGraph<'a>, GraphError> {
let RenderGraph {
images,
buffers,
passes,
default_queue: _,
import_conflict,
} = graph;
if let Some(conflict) = import_conflict {
return Err(conflict);
}
validate(&images, &buffers, &passes)?;
validate_imports(&images, &buffers, pool)?;
let image_lifetimes = lifetimes(passes.len(), passes.iter().map(|pass| &pass.images), |a| {
a.image.0
});
let buffer_lifetimes = lifetimes(passes.len(), passes.iter().map(|pass| &pass.buffers), |a| {
a.buffer.0
});
let mut transient_images = Vec::new();
let image_slots = assign(
&images,
&image_lifetimes,
|node| match node.source {
ImageSource::Transient(desc) => Some(desc),
ImageSource::Imported(_) => None,
},
|node| node.label.clone(),
&mut transient_images,
)?;
let mut transient_buffers = Vec::new();
let buffer_slots = assign(
&buffers,
&buffer_lifetimes,
|node| match node.source {
BufferSource::Transient(desc) => Some(desc),
BufferSource::Imported(_) => None,
},
|node| node.label.clone(),
&mut transient_buffers,
)?;
let mut image_state: Vec<ImageTracker> = images
.iter()
.zip(&image_slots)
.map(|(node, slot)| match (slot, node.source) {
(Slot::Imported, ImageSource::Imported(imported)) => {
ImageTracker::new(Subrect::UNBOUNDED, Tracked::declared(imported.initial))
}
_ => ImageTracker::new(
Subrect::UNBOUNDED,
Tracked::declared(ResourceState::Undefined),
),
})
.collect();
let mut transient_image_state: Vec<ImageTracker> = (0..transient_images.len())
.map(|slot| {
let desc = transient_images[slot];
ImageTracker::new(
Subrect::bounded(desc.mip_levels.max(1), 1),
Tracked::carried(pool.image_use(desc, ordinal(&transient_images, slot))),
)
})
.collect();
let mut buffer_state: Vec<Tracked> = buffers
.iter()
.zip(&buffer_slots)
.map(|(node, slot)| Tracked {
state: match (slot, node.source) {
(Slot::Imported, BufferSource::Imported(imported)) => imported.initial,
_ => ResourceState::Undefined,
},
queue: None,
last_pass: None,
})
.collect();
let mut transient_buffer_state: Vec<Tracked> = (0..transient_buffers.len())
.map(|slot| {
Tracked::carried(
pool.buffer_use(transient_buffers[slot], ordinal(&transient_buffers, slot)),
)
})
.collect();
let mut compiled: Vec<CompiledPass<'a>> = Vec::with_capacity(passes.len());
for (index, pass) in passes.into_iter().enumerate() {
let mut barriers = GraphBarriers::default();
for access in &pass.images {
let node = &images[access.image.index()];
let aspect = access
.range
.map_or_else(|| ImageAspect::of(node.format()), |range| range.aspect);
let tracked = tracker(
image_slots[access.image.index()],
access.image.0,
&mut image_state,
&mut transient_image_state,
);
let rect = access
.range
.map_or(tracked.bounds, |range| subrect_of(range, tracked.bounds));
for sub in tracked.transition(rect, access.state, pass.queue, index) {
let range = match sub.rect {
None => access.range,
Some(piece) => Some(piece.to_range(aspect)),
};
let barrier = GraphImageBarrier {
image: access.image,
from: sub.from,
to: access.state,
queue_transfer: sub.queue_transfer,
range,
};
if sub.queue_transfer.is_some()
&& let Some(source) = sub.last_pass
{
compiled[source].release_barriers.images.push(barrier);
}
barriers.images.push(barrier);
}
}
for access in &pass.buffers {
let tracked = tracker(
buffer_slots[access.buffer.index()],
access.buffer.0,
&mut buffer_state,
&mut transient_buffer_state,
);
if let Some(barrier) = transition(tracked, access.state, pass.queue, index) {
let compiled_barrier = GraphBufferBarrier {
buffer: access.buffer,
from: barrier.0,
to: access.state,
queue_transfer: barrier.1,
};
if barrier.1.is_some()
&& let Some(source) = barrier.2
{
compiled[source]
.release_barriers
.buffers
.push(compiled_barrier);
}
barriers.buffers.push(compiled_barrier);
}
}
let render_area = render_area(&images, &pass)?;
compiled.push(CompiledPass {
label: pass.label,
kind: pass.kind,
queue: pass.queue,
barriers,
release_barriers: GraphBarriers::default(),
images: pass.images,
buffers: pass.buffers,
render_area,
body: pass.body,
});
}
let mut final_barriers = GraphBarriers::default();
for (index, node) in images.iter().enumerate() {
let ImageSource::Imported(imported) = node.source else {
continue;
};
let tracker = &image_state[index];
let aspect = ImageAspect::of(imported.format);
let whole = tracker.segments.len() == 1;
for (rect, tracked) in &tracker.segments {
if tracked.state != imported.final_state {
final_barriers.images.push(GraphImageBarrier {
image: ImageId(u32::try_from(index).expect("a frame has few resources")),
from: tracked.state,
to: imported.final_state,
queue_transfer: None,
range: if whole {
None
} else {
Some(rect.to_range(aspect))
},
});
}
}
}
for (index, node) in buffers.iter().enumerate() {
let BufferSource::Imported(imported) = node.source else {
continue;
};
let tracked = buffer_state[index];
if tracked.state != imported.final_state {
final_barriers.buffers.push(GraphBufferBarrier {
buffer: BufferId(u32::try_from(index).expect("a frame has few resources")),
from: tracked.state,
to: imported.final_state,
queue_transfer: None,
});
}
}
let transient_image_end = transient_image_state
.iter()
.map(ImageTracker::end)
.collect();
let transient_buffer_end = transient_buffer_state.iter().map(|t| t.end()).collect();
let imported_image_end = images
.iter()
.filter_map(|node| match node.source {
ImageSource::Imported(imported) if imported.claim == InitialClaim::Tracked => {
Some((imported.image, imported.final_state))
}
_ => None,
})
.collect();
let imported_buffer_end = buffers
.iter()
.filter_map(|node| match node.source {
BufferSource::Imported(imported) => Some((imported.buffer, imported.final_state)),
BufferSource::Transient(_) => None,
})
.collect();
Ok(CompiledGraph {
images,
buffers,
passes: compiled,
final_barriers,
image_slots,
buffer_slots,
transient_images,
transient_buffers,
transient_image_end,
transient_buffer_end,
imported_image_end,
imported_buffer_end,
})
}
fn tracker<'s, T>(
slot: Slot,
id: u32,
per_resource: &'s mut [T],
per_slot: &'s mut [T],
) -> &'s mut T {
match slot {
Slot::Imported => &mut per_resource[id as usize],
Slot::Transient(index) => &mut per_slot[index],
}
}
fn transition(
tracked: &mut Tracked,
want: ResourceState,
queue: QueueHandle,
pass: usize,
) -> Option<(ResourceState, Option<QueueTransfer>, Option<usize>)> {
let queue_transfer = match tracked.queue {
Some(previous) if previous != queue => Some(QueueTransfer {
from: previous,
to: queue,
}),
_ => None,
};
let from = tracked.state;
let source_pass = tracked.last_pass;
tracked.queue = Some(queue);
tracked.last_pass = Some(pass);
if !ResourceState::needs_barrier(from, want) && queue_transfer.is_none() {
return None;
}
tracked.state = want;
Some((from, queue_transfer, source_pass))
}
fn lifetimes<'p, A: 'p, I>(
pass_count: usize,
accesses: impl Iterator<Item = I>,
id_of: impl Fn(&A) -> u32,
) -> Vec<Option<(usize, usize)>>
where
I: IntoIterator<Item = &'p A>,
{
let mut spans: Vec<Option<(usize, usize)>> = Vec::new();
for (pass, list) in accesses.enumerate() {
debug_assert!(pass < pass_count);
for access in list {
let id = id_of(access) as usize;
if spans.len() <= id {
spans.resize(id + 1, None);
}
spans[id] = Some(match spans[id] {
Some((first, last)) => (first.min(pass), last.max(pass)),
None => (pass, pass),
});
}
}
spans
}
fn assign<N, D: Copy + PartialEq>(
nodes: &[N],
spans: &[Option<(usize, usize)>],
desc_of: impl Fn(&N) -> Option<D>,
label_of: impl Fn(&N) -> String,
physical: &mut Vec<D>,
) -> Result<Vec<Slot>, GraphError> {
let mut free_from: Vec<usize> = Vec::new();
let mut slots = Vec::with_capacity(nodes.len());
let mut order: Vec<usize> = (0..nodes.len()).collect();
order.sort_by_key(|index| {
spans
.get(*index)
.copied()
.flatten()
.map_or(usize::MAX, |s| s.0)
});
slots.resize(nodes.len(), Slot::Imported);
for index in order {
let Some(desc) = desc_of(&nodes[index]) else {
continue;
};
let Some((first, last)) = spans.get(index).copied().flatten() else {
return Err(GraphError::UnusedTransient {
resource: label_of(&nodes[index]),
});
};
let reused =
(0..physical.len()).find(|slot| physical[*slot] == desc && free_from[*slot] <= first);
let slot = match reused {
Some(slot) => slot,
None => {
physical.push(desc);
free_from.push(0);
physical.len() - 1
}
};
free_from[slot] = last + 1;
slots[index] = Slot::Transient(slot);
}
Ok(slots)
}
fn validate_imports(
images: &[ImageNode],
buffers: &[BufferNode],
pool: &TransientPool,
) -> Result<(), GraphError> {
for node in images {
let ImageSource::Imported(imported) = node.source else {
continue;
};
if imported.claim != InitialClaim::Tracked {
continue;
}
let Some(left) = pool.imported_image_use(imported.image) else {
continue;
};
if left != imported.initial {
return Err(GraphError::ImportStateMismatch {
resource: node.label.clone(),
declared: imported.initial,
left,
});
}
}
for node in buffers {
let BufferSource::Imported(imported) = node.source else {
continue;
};
let Some(left) = pool.imported_buffer_use(imported.buffer) else {
continue;
};
if left != imported.initial {
return Err(GraphError::BufferImportStateMismatch {
resource: node.label.clone(),
declared: imported.initial,
left,
});
}
}
Ok(())
}
fn validate(
images: &[ImageNode],
buffers: &[BufferNode],
passes: &[Pass<'_>],
) -> Result<(), GraphError> {
for pass in passes {
let mut seen_depth = false;
for (position, access) in pass.images.iter().enumerate() {
if pass.kind != PassKind::Render && access.attachment.is_some() {
return Err(GraphError::AttachmentOutsideRenderPass {
kind: pass.kind.name(),
pass: pass.label.clone(),
resource: images[access.image.index()].label.clone(),
});
}
if matches!(access.attachment, Some(Attachment::Depth { .. })) {
if seen_depth {
return Err(GraphError::DuplicateDepthAttachment {
pass: pass.label.clone(),
});
}
seen_depth = true;
}
if let (Some(range), ImageSource::Transient(desc)) =
(access.range, images[access.image.index()].source)
{
let mip_levels = desc.mip_levels.max(1);
let mips_ok = range.mip_count == ImageSubresourceRange::ALL
|| range.base_mip.saturating_add(range.mip_count) <= mip_levels;
let layers_ok = range.layer_count == ImageSubresourceRange::ALL
|| range.base_layer.saturating_add(range.layer_count) <= TRANSIENT_LAYERS;
if !mips_ok || !layers_ok || range.base_mip >= mip_levels {
return Err(GraphError::SubresourceOutOfRange {
pass: pass.label.clone(),
resource: images[access.image.index()].label.clone(),
base_mip: range.base_mip,
mip_count: range.mip_count,
base_layer: range.base_layer,
layer_count: range.layer_count,
mip_levels,
layers: TRANSIENT_LAYERS,
});
}
}
for other in &pass.images[position + 1..] {
if other.image != access.image {
continue;
}
if other.state != access.state {
return Err(GraphError::ConflictingAccess {
pass: pass.label.clone(),
resource: images[access.image.index()].label.clone(),
first: access.state,
second: other.state,
});
}
if other.range == access.range {
return Err(GraphError::DuplicateDeclaration {
pass: pass.label.clone(),
resource: images[access.image.index()].label.clone(),
});
}
}
}
for (position, access) in pass.buffers.iter().enumerate() {
for other in &pass.buffers[position + 1..] {
if other.buffer != access.buffer {
continue;
}
if other.state != access.state {
return Err(GraphError::ConflictingAccess {
pass: pass.label.clone(),
resource: buffers[access.buffer.index()].label.clone(),
first: access.state,
second: other.state,
});
}
return Err(GraphError::DuplicateDeclaration {
pass: pass.label.clone(),
resource: buffers[access.buffer.index()].label.clone(),
});
}
}
}
Ok(())
}
fn render_area(images: &[ImageNode], pass: &Pass<'_>) -> Result<Rect2d, GraphError> {
if pass.kind != PassKind::Render {
return Ok(Rect2d::from_size(0, 0));
}
let mut area: Option<(&str, (u32, u32))> = None;
for access in &pass.images {
if access.attachment.is_none() {
continue;
}
let node = &images[access.image.index()];
let extent = node.extent();
match area {
None => area = Some((&node.label, extent)),
Some((first, first_extent)) if first_extent != extent => {
return Err(GraphError::AttachmentExtentMismatch {
pass: pass.label.clone(),
first: first.to_string(),
first_extent,
second: node.label.clone(),
second_extent: extent,
});
}
Some(_) => {}
}
}
match area {
Some((_, (width, height))) => Ok(Rect2d::from_size(width, height)),
None => Err(GraphError::NoAttachments {
pass: pass.label.clone(),
}),
}
}
impl TransientBufferDesc {
#[must_use]
pub const fn storage(size: u64) -> Self {
Self {
size,
usage: BufferUsage::STORAGE.union(BufferUsage::TRANSFER_DST),
}
}
}