use alloc::{boxed::Box, sync::Arc, vec::Vec};
use thiserror::Error;
use crate::{
binding_model::{BindGroup, BindGroupLayout, LateMinBufferBindingSizeMismatch, PipelineLayout},
pipeline::LateSizedBufferGroup,
resource::{Labeled, ParentDevice, ResourceErrorIdent},
};
mod compat {
use alloc::{
string::{String, ToString as _},
sync::{Arc, Weak},
vec::Vec,
};
use core::num::NonZeroU32;
use thiserror::Error;
use wgt::{BindingType, ShaderStages};
use crate::{binding_model::BindGroupLayout, error::MultiError, resource::ParentDevice};
pub(super) fn check(
expected_bgl: &Arc<BindGroupLayout>,
assigned_bgl: &Arc<BindGroupLayout>,
) -> Result<(), MultiError> {
if expected_bgl.is_equal(assigned_bgl) {
return Ok(());
}
#[derive(Clone, Debug, Error)]
#[error("Exclusive pipelines don't match: expected {expected}, got {assigned}")]
struct IncompatibleExclusivePipelines {
expected: String,
assigned: String,
}
use crate::binding_model::ExclusivePipeline;
match (
expected_bgl.exclusive_pipeline.get().unwrap(),
assigned_bgl.exclusive_pipeline.get().unwrap(),
) {
(ExclusivePipeline::None, ExclusivePipeline::None) => {}
(ExclusivePipeline::Render(e_pipeline), ExclusivePipeline::Render(a_pipeline))
if Weak::ptr_eq(e_pipeline, a_pipeline) => {}
(ExclusivePipeline::Compute(e_pipeline), ExclusivePipeline::Compute(a_pipeline))
if Weak::ptr_eq(e_pipeline, a_pipeline) => {}
(expected, assigned) => {
return Err(
MultiError::new(core::iter::once(IncompatibleExclusivePipelines {
expected: expected.to_string(),
assigned: assigned.to_string(),
}))
.unwrap(),
);
}
}
#[derive(Clone, Debug, Error)]
enum EntryError {
#[error("Entries with binding {binding} differ in visibility: expected {expected:?}, got {assigned:?}")]
Visibility {
binding: u32,
expected: ShaderStages,
assigned: ShaderStages,
},
#[error("Entries with binding {binding} differ in type: expected {expected:?}, got {assigned:?}")]
Type {
binding: u32,
expected: BindingType,
assigned: BindingType,
},
#[error("Entries with binding {binding} differ in count: expected {expected:?}, got {assigned:?}")]
Count {
binding: u32,
expected: Option<NonZeroU32>,
assigned: Option<NonZeroU32>,
},
#[error(
"Expected entry with binding {binding} not found in assigned bind group layout"
)]
ExtraExpected { binding: u32 },
#[error(
"Assigned entry with binding {binding} not found in expected bind group layout"
)]
ExtraAssigned { binding: u32 },
}
let mut errors = Vec::new();
for (&binding, expected_entry) in expected_bgl.entries.iter() {
if let Some(assigned_entry) = assigned_bgl.entries.get(binding) {
if assigned_entry.visibility != expected_entry.visibility {
errors.push(EntryError::Visibility {
binding,
expected: expected_entry.visibility,
assigned: assigned_entry.visibility,
});
}
if assigned_entry.ty != expected_entry.ty {
errors.push(EntryError::Type {
binding,
expected: expected_entry.ty,
assigned: assigned_entry.ty,
});
}
if assigned_entry.count != expected_entry.count {
errors.push(EntryError::Count {
binding,
expected: expected_entry.count,
assigned: assigned_entry.count,
});
}
} else {
errors.push(EntryError::ExtraExpected { binding });
}
}
for (&binding, _) in assigned_bgl.entries.iter() {
if !expected_bgl.entries.contains_key(binding) {
errors.push(EntryError::ExtraAssigned { binding });
}
}
Err(MultiError::new(errors.drain(..)).unwrap())
}
}
#[derive(Clone, Debug, Error)]
pub enum BinderError {
#[error("The current set {pipeline} expects a BindGroup to be set at index {index}")]
MissingBindGroup {
index: usize,
pipeline: ResourceErrorIdent,
},
#[error("The {assigned_bgl} of current set {assigned_bg} at index {index} is not compatible with the corresponding {expected_bgl} of {pipeline}")]
IncompatibleBindGroup {
expected_bgl: ResourceErrorIdent,
assigned_bgl: ResourceErrorIdent,
assigned_bg: ResourceErrorIdent,
index: usize,
pipeline: ResourceErrorIdent,
#[source]
inner: crate::error::MultiError,
},
#[error(transparent)]
BindingSizeTooSmall(#[from] LateMinBufferBindingSizeMismatch),
}
#[derive(Debug, Default)]
struct EntryPayload {
group: Option<Arc<BindGroup>>,
dynamic_offsets: Vec<wgt::DynamicOffset>,
}
impl EntryPayload {
fn reset(&mut self) {
self.group = None;
self.dynamic_offsets.clear();
}
}
#[derive(Debug)]
pub(super) struct Binder {
pub(super) pipeline_layout: Option<Arc<PipelineLayout>>,
payloads: [EntryPayload; hal::MAX_BIND_GROUPS],
rebind_start: usize,
}
impl Binder {
pub(super) fn new() -> Self {
Self {
pipeline_layout: None,
payloads: Default::default(),
rebind_start: 0,
}
}
pub(super) fn reset(&mut self) {
self.pipeline_layout = None;
for payload in self.payloads.iter_mut() {
payload.reset();
}
self.rebind_start = 0;
}
fn expected_layout(&self, index: usize) -> Option<&Arc<BindGroupLayout>> {
self.pipeline_layout
.as_ref()?
.bind_group_layouts
.get(index)?
.as_ref()
}
fn active_slots(
&self,
) -> impl Iterator<Item = (usize, &EntryPayload, &Arc<BindGroup>, &Arc<BindGroupLayout>)> + '_
{
self.payloads
.iter()
.enumerate()
.filter_map(|(index, payload)| {
let group = payload.group.as_ref()?;
let expected = self.expected_layout(index)?;
Some((index, payload, group, expected))
})
}
fn update_rebind_start_index(&mut self, start_index: usize) {
self.rebind_start = self.rebind_start.min(start_index);
}
pub(super) fn change_pipeline_layout<'a>(&'a mut self, new: &Arc<PipelineLayout>) -> bool {
if let Some(old) = self.pipeline_layout.as_ref() {
if old.is_equal(new) {
return false;
}
}
let old = self.pipeline_layout.replace(new.clone());
let old_layouts = old
.as_ref()
.map_or(&[][..], |old| &old.bind_group_layouts[..]);
let first_changed = (0..hal::MAX_BIND_GROUPS).position(|i| {
let old_bgl = old_layouts.get(i).and_then(Option::as_ref);
let new_bgl = new.bind_group_layouts.get(i).and_then(Option::as_ref);
match (old_bgl, new_bgl) {
(None, None) => false,
(Some(old_bgl), Some(new_bgl)) => !old_bgl.is_equal(new_bgl),
_ => true,
}
});
if let Some(first_changed) = first_changed {
self.update_rebind_start_index(first_changed);
}
if let Some(old) = old {
if old.immediate_size != new.immediate_size {
self.update_rebind_start_index(0);
}
}
true
}
pub(super) fn assign_group<'a>(
&'a mut self,
index: usize,
bind_group: &Arc<BindGroup>,
offsets: &[wgt::DynamicOffset],
) {
let payload = &mut self.payloads[index];
payload.group = Some(bind_group.clone());
payload.dynamic_offsets.clear();
payload.dynamic_offsets.extend_from_slice(offsets);
self.update_rebind_start_index(index);
}
pub(super) fn clear_group(&mut self, index: usize) {
self.payloads[index].reset();
}
pub(super) fn take_rebind_start_index(&mut self) -> usize {
core::mem::replace(&mut self.rebind_start, hal::MAX_BIND_GROUPS)
}
pub(super) fn list_valid_with_start(
&self,
start: usize,
) -> impl Iterator<Item = (usize, &Arc<BindGroup>, &[wgt::DynamicOffset])> + '_ {
self.active_slots()
.filter(move |&(index, _, group, expected)| {
index >= start && expected.is_equal(&group.layout)
})
.map(|(index, payload, group, _)| (index, group, payload.dynamic_offsets.as_slice()))
}
pub(super) fn last_assigned_index(&self) -> Option<usize> {
self.payloads
.iter()
.rposition(|payload| payload.group.is_some())
}
pub(super) fn list_active(&self) -> impl Iterator<Item = &Arc<BindGroup>> + '_ {
self.active_slots().map(|(_, _, group, _)| group)
}
pub(super) fn list_valid(
&self,
) -> impl Iterator<Item = (usize, &Arc<BindGroup>, &[wgt::DynamicOffset])> + '_ {
self.list_valid_with_start(0)
}
pub(super) fn check_compatibility<T: Labeled>(
&self,
pipeline: &T,
late_sized_buffer_groups: &[LateSizedBufferGroup],
) -> Result<(), Box<BinderError>> {
for (index, payload) in self.payloads.iter().enumerate() {
let Some(expected_bgl) = self.expected_layout(index) else {
continue;
};
let Some(group) = payload.group.as_ref() else {
return Err(Box::new(BinderError::MissingBindGroup {
index,
pipeline: pipeline.error_ident(),
}));
};
compat::check(expected_bgl, &group.layout).map_err(|inner| {
Box::new(BinderError::IncompatibleBindGroup {
expected_bgl: expected_bgl.error_ident(),
assigned_bgl: group.layout.error_ident(),
assigned_bg: group.error_ident(),
index,
pipeline: pipeline.error_ident(),
inner,
})
})?;
let shader_sizes = &late_sized_buffer_groups[index].shader_sizes;
assert_eq!(
group.layout.late_sized_bindings.len(),
group.late_buffer_binding_sizes.len()
);
assert_eq!(group.late_buffer_binding_sizes.len(), shader_sizes.len());
for ((&binding_index, bound_size), &shader_size) in group
.layout
.late_sized_bindings
.iter()
.zip(&group.late_buffer_binding_sizes)
.zip(shader_sizes)
{
if bound_size.get() < shader_size {
return Err(Box::new(
LateMinBufferBindingSizeMismatch {
group_index: index as u32,
binding_index,
shader_size,
bound_size: bound_size.get(),
}
.into(),
));
}
}
}
Ok(())
}
}