mirror of
https://github.com/storytold/wgpu.git
synced 2026-11-21 06:50:59 +01:00
fix(core): Use more checked arithmetic, part 2b (#9425)
This commit is contained in:
1 parent
006e346a94
commit
61e76ee746
9 files changed
+110
-55
No files matched your search
@@ -108,6 +108,10 @@ By @teoxoy in [#9351](https://github.com/gfx-rs/wgpu/pull/9351).
|
||||
- Passthrough shaders now require a list of entry points when being created. by @inner-daemons in [#9064](https://github.com/gfx-rs/wgpu/pull/9064).
|
||||
- BREAKING: The `dispatch` and `dispatch_indirect` methods on pass and bundle encoders have been renamed to `dispatch_workgroups` and `dispatch_workgroups_indirect`, respectively, to match the WebGPU spec. By @ErichDonGubler in [#9362](https://github.com/gfx-rs/wgpu/pull/9362).
|
||||
- `LoadOp::DontCare` can no longer be deserialized, and the `LoadOpDontCare` token no longer implements `Default`. This ensures that `DontCare` can only be used with `unsafe`, as intended. By @kpreid in [#9428](https://github.com/gfx-rs/wgpu/pull/9428).
|
||||
- Minor changes to various error enums to support improved validation. By @andyleiserson in [#9357](https://github.com/gfx-rs/wgpu/pull/9357), [#9363](https://github.com/gfx-rs/wgpu/pull/9363), and [#9425](https://github.com/gfx-rs/wgpu/pull/9425):
|
||||
- Added new `InvalidWorkgroupSizeError`, which is now used by `DrawError::InvalidGroupSize` and `StageError::InvalidWorkgroupSize`.
|
||||
- Added `BuildAccelerationStructureError` variant `OffsetLimitedTo4GB` and changed `IndirectBufferOverrun` to contain offset and size rather than start and end offsets.
|
||||
- `IndexFormat::byte_size` now returns `u32` instead of `usize`.
|
||||
|
||||
#### Validation
|
||||
|
||||
|
||||
@@ -697,10 +697,10 @@ fn set_index_buffer(
|
||||
buffer.same_device(&state.device)?;
|
||||
buffer.check_usage(wgt::BufferUsages::INDEX)?;
|
||||
|
||||
if !offset.is_multiple_of(u64::try_from(index_format.byte_size()).unwrap()) {
|
||||
if !offset.is_multiple_of(u64::from(index_format.byte_size())) {
|
||||
return Err(RenderCommandError::UnalignedIndexBuffer {
|
||||
offset,
|
||||
alignment: index_format.byte_size(),
|
||||
alignment: index_format.byte_size() as usize,
|
||||
}
|
||||
.into());
|
||||
}
|
||||
|
||||
@@ -213,7 +213,7 @@ pub(crate) fn build_acceleration_structures(
|
||||
state,
|
||||
)?;
|
||||
|
||||
let mut scratch_buffer_tlas_size = 0;
|
||||
let mut scratch_buffer_tlas_size: u64 = 0;
|
||||
let mut tlas_storage = Vec::<TlasStore>::with_capacity(tlas.len());
|
||||
let mut instance_buffer_staging_source = Vec::<u8>::new();
|
||||
|
||||
@@ -222,15 +222,10 @@ pub(crate) fn build_acceleration_structures(
|
||||
state.tracker.tlas_s.insert_single(tlas.clone());
|
||||
|
||||
let scratch_buffer_offset = scratch_buffer_tlas_size;
|
||||
assert!(
|
||||
tlas.size_info.build_scratch_size
|
||||
<= u64::MAX
|
||||
- u64::from(state.device.alignments.ray_tracing_scratch_buffer_alignment)
|
||||
);
|
||||
scratch_buffer_tlas_size += align_to(
|
||||
scratch_buffer_tlas_size = scratch_buffer_tlas_size.saturating_add(align_to(
|
||||
tlas.size_info.build_scratch_size,
|
||||
u64::from(state.device.alignments.ray_tracing_scratch_buffer_alignment),
|
||||
);
|
||||
));
|
||||
|
||||
let first_byte_index = instance_buffer_staging_source.len();
|
||||
|
||||
@@ -311,7 +306,9 @@ pub(crate) fn build_acceleration_structures(
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
assert!(scratch_size.get() != u64::MAX);
|
||||
if scratch_size.get() == u64::MAX {
|
||||
return Err(crate::device::DeviceError::OutOfMemory.into());
|
||||
}
|
||||
|
||||
let scratch_buffer = ScratchBuffer::new(state.device, scratch_size)?;
|
||||
|
||||
@@ -775,11 +772,30 @@ fn iter_blas<'snatch_guard: 'buffers, 'buffers>(
|
||||
}) {
|
||||
input_barriers.push(barrier);
|
||||
}
|
||||
let index_stride = mesh.size.index_format.unwrap().byte_size() as u32;
|
||||
let index_stride = mesh.size.index_format.unwrap().byte_size();
|
||||
// `hal::AccelerationStructureTriangleIndices` accepts only `u32` offset
|
||||
let vertex_offset = mesh.first_index.unwrap().saturating_mul(index_stride);
|
||||
let indexes_size =
|
||||
mesh.size.index_count.unwrap().saturating_mul(index_stride);
|
||||
let Some(vertex_offset) =
|
||||
mesh.first_index.unwrap().checked_mul(index_stride)
|
||||
else {
|
||||
return Err(BuildAccelerationStructureError::OffsetLimitedTo4GB {
|
||||
buffer_ident: index_buffer.error_ident(),
|
||||
offset: u64::from(mesh.first_index.unwrap())
|
||||
.saturating_mul(u64::from(index_stride)),
|
||||
count: u64::from(mesh.first_index.unwrap()),
|
||||
stride: u64::from(index_stride),
|
||||
});
|
||||
};
|
||||
let Some(indexes_size) =
|
||||
mesh.size.index_count.unwrap().checked_mul(index_stride)
|
||||
else {
|
||||
return Err(BuildAccelerationStructureError::OffsetLimitedTo4GB {
|
||||
buffer_ident: index_buffer.error_ident(),
|
||||
offset: u64::from(mesh.size.index_count.unwrap())
|
||||
.saturating_mul(u64::from(index_stride)),
|
||||
count: u64::from(mesh.size.index_count.unwrap()),
|
||||
stride: u64::from(index_stride),
|
||||
});
|
||||
};
|
||||
|
||||
if mesh.size.index_count.unwrap() % 3 != 0 {
|
||||
return Err(BuildAccelerationStructureError::InvalidIndexCount(
|
||||
@@ -787,9 +803,7 @@ fn iter_blas<'snatch_guard: 'buffers, 'buffers>(
|
||||
mesh.size.index_count.unwrap(),
|
||||
));
|
||||
}
|
||||
if indexes_size == u32::MAX
|
||||
|| vertex_offset == u32::MAX
|
||||
|| index_buffer.size < u64::from(vertex_offset)
|
||||
if index_buffer.size < u64::from(vertex_offset)
|
||||
|| index_buffer.size - u64::from(vertex_offset)
|
||||
< u64::from(indexes_size)
|
||||
{
|
||||
@@ -847,8 +861,15 @@ fn iter_blas<'snatch_guard: 'buffers, 'buffers>(
|
||||
}
|
||||
|
||||
// `hal::AccelerationStructureTriangleTransform` accepts only `u32` offset
|
||||
let offset = u32::try_from(mesh.transform_buffer_offset.unwrap())
|
||||
.unwrap_or(u32::MAX);
|
||||
let Ok(offset) = u32::try_from(mesh.transform_buffer_offset.unwrap())
|
||||
else {
|
||||
return Err(BuildAccelerationStructureError::OffsetLimitedTo4GB {
|
||||
buffer_ident: transform_buffer.error_ident(),
|
||||
offset: mesh.transform_buffer_offset.unwrap(),
|
||||
count: mesh.transform_buffer_offset.unwrap(),
|
||||
stride: 1,
|
||||
});
|
||||
};
|
||||
|
||||
if offset % wgt::TRANSFORM_BUFFER_ALIGNMENT as u32 != 0 {
|
||||
return Err(
|
||||
@@ -857,8 +878,7 @@ fn iter_blas<'snatch_guard: 'buffers, 'buffers>(
|
||||
),
|
||||
);
|
||||
}
|
||||
if offset == u32::MAX
|
||||
|| transform_buffer.size < 48
|
||||
if transform_buffer.size < 48
|
||||
|| transform_buffer.size - 48 < u64::from(offset)
|
||||
{
|
||||
return Err(BuildAccelerationStructureError::InsufficientBufferSize {
|
||||
@@ -915,13 +935,6 @@ fn iter_blas<'snatch_guard: 'buffers, 'buffers>(
|
||||
|
||||
{
|
||||
let scratch_buffer_offset = *scratch_buffer_blas_size;
|
||||
assert!(
|
||||
blas.size_info.build_scratch_size
|
||||
<= u64::MAX
|
||||
- u64::from(
|
||||
state.device.alignments.ray_tracing_scratch_buffer_alignment
|
||||
)
|
||||
);
|
||||
*scratch_buffer_blas_size = scratch_buffer_blas_size.saturating_add(align_to(
|
||||
blas.size_info.build_scratch_size,
|
||||
u64::from(state.device.alignments.ray_tracing_scratch_buffer_alignment),
|
||||
@@ -1004,12 +1017,20 @@ fn iter_blas<'snatch_guard: 'buffers, 'buffers>(
|
||||
}
|
||||
|
||||
// `hal::AccelerationStructureAABBs` accepts only `u32` offset
|
||||
let aabb_size = aabb
|
||||
.size
|
||||
.primitive_count
|
||||
.saturating_mul(u32::try_from(aabb.stride).unwrap());
|
||||
if aabb_size == u32::MAX
|
||||
|| aabb_buffer.size < u64::from(aabb.primitive_offset)
|
||||
let Some(aabb_size) = u32::try_from(aabb.stride)
|
||||
.ok()
|
||||
.and_then(|stride| aabb.size.primitive_count.checked_mul(stride))
|
||||
else {
|
||||
return Err(BuildAccelerationStructureError::OffsetLimitedTo4GB {
|
||||
buffer_ident: aabb_buffer.error_ident(),
|
||||
offset: u64::from(aabb.size.primitive_count)
|
||||
.saturating_mul(aabb.stride),
|
||||
count: u64::from(aabb.size.primitive_count),
|
||||
stride: aabb.stride,
|
||||
});
|
||||
};
|
||||
|
||||
if aabb_buffer.size < u64::from(aabb.primitive_offset)
|
||||
|| aabb_buffer.size - u64::from(aabb.primitive_offset)
|
||||
< u64::from(aabb_size)
|
||||
{
|
||||
|
||||
@@ -2562,10 +2562,10 @@ fn set_index_buffer(
|
||||
|
||||
buffer.check_usage(BufferUsages::INDEX)?;
|
||||
|
||||
if !offset.is_multiple_of(u64::try_from(index_format.byte_size()).unwrap()) {
|
||||
if !offset.is_multiple_of(u64::from(index_format.byte_size())) {
|
||||
return Err(RenderCommandError::UnalignedIndexBuffer {
|
||||
offset,
|
||||
alignment: index_format.byte_size(),
|
||||
alignment: index_format.byte_size() as usize,
|
||||
}
|
||||
.into());
|
||||
}
|
||||
|
||||
@@ -268,7 +268,8 @@ impl Device {
|
||||
let instance_buffer_size = self
|
||||
.alignments
|
||||
.raw_tlas_instance_size
|
||||
.saturating_mul(desc.max_instances.max(1));
|
||||
.checked_mul(desc.max_instances.max(1))
|
||||
.expect("max_tlas_instance_count should not allow excessive buffer size");
|
||||
let instance_buffer = unsafe {
|
||||
self.raw().create_buffer(&hal::BufferDescriptor {
|
||||
label: hal_label(Some("(wgpu-core) instances_buffer"), self.instance_flags),
|
||||
|
||||
@@ -119,6 +119,16 @@ pub enum BuildAccelerationStructureError {
|
||||
buffer_size: BufferAddress,
|
||||
},
|
||||
|
||||
#[error(
|
||||
"Offset {offset}, computed as {count} times {stride} B, exceeds the maximum addressable offset 2^32 - 1 within buffer {buffer_ident:?}"
|
||||
)]
|
||||
OffsetLimitedTo4GB {
|
||||
buffer_ident: ResourceErrorIdent,
|
||||
offset: BufferAddress,
|
||||
count: BufferAddress,
|
||||
stride: BufferAddress,
|
||||
},
|
||||
|
||||
#[error("Buffer {0:?} associated offset doesn't align with the index type")]
|
||||
UnalignedIndexBufferOffset(ResourceErrorIdent),
|
||||
|
||||
@@ -215,6 +225,7 @@ impl WebGpuError for BuildAccelerationStructureError {
|
||||
Self::MissingBufferUsage(e) => e.webgpu_error_type(),
|
||||
Self::MissingFeatures(e) => e.webgpu_error_type(),
|
||||
Self::InsufficientBufferSize { .. }
|
||||
| Self::OffsetLimitedTo4GB { .. }
|
||||
| Self::UnalignedIndexBufferOffset(..)
|
||||
| Self::UnalignedTransformBufferOffset(..)
|
||||
| Self::InvalidIndexCount(..)
|
||||
|
||||
@@ -1397,7 +1397,10 @@ impl crate::Device for super::Device {
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
unsafe {
|
||||
buffer_desc.setStride(wgt::math::align_to(stride as _, 4))
|
||||
buffer_desc.setStride(wgt::math::align_to(
|
||||
NSUInteger::try_from(stride).unwrap(),
|
||||
4,
|
||||
))
|
||||
};
|
||||
buffer_desc.setStepFunction(MTLVertexStepFunction::Constant);
|
||||
unsafe { buffer_desc.setStepRate(0) };
|
||||
|
||||
+30
-15
@@ -1,31 +1,46 @@
|
||||
//! Utility math functions.
|
||||
|
||||
use core::ops::{Add, Rem, Sub};
|
||||
/// Trait for adjusting integers to the next multiple of an alignment.
|
||||
pub trait AlignTo: Copy {
|
||||
/// Aligns `self` to `alignment`.
|
||||
///
|
||||
/// Panics if doing so would overflow.
|
||||
fn align_to(self, alignment: Self) -> Self;
|
||||
}
|
||||
|
||||
macro_rules! impl_align_to {
|
||||
($ty:ty) => {
|
||||
impl AlignTo for $ty {
|
||||
fn align_to(self, alignment: Self) -> Self {
|
||||
self.checked_next_multiple_of(alignment).unwrap()
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl_align_to!(u32);
|
||||
impl_align_to!(u64);
|
||||
impl_align_to!(usize);
|
||||
|
||||
///
|
||||
/// Aligns a `value` to an `alignment`.
|
||||
///
|
||||
/// Returns the first number greater than or equal to `value` that is also a
|
||||
/// multiple of `alignment`. If `value` is already a multiple of `alignment`,
|
||||
/// `value` will be returned.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// If aligning `value` to `alignment` would overflow.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// # use wgpu_types::math::align_to;
|
||||
/// assert_eq!(align_to(253, 16), 256);
|
||||
/// assert_eq!(align_to(256, 16), 256);
|
||||
/// assert_eq!(align_to(0, 16), 0);
|
||||
/// assert_eq!(align_to(253_u32, 16), 256);
|
||||
/// assert_eq!(align_to(256_u32, 16), 256);
|
||||
/// assert_eq!(align_to(0_u32, 16), 0);
|
||||
/// ```
|
||||
///
|
||||
pub fn align_to<T>(value: T, alignment: T) -> T
|
||||
where
|
||||
T: Add<Output = T> + Copy + Default + PartialEq<T> + Rem<Output = T> + Sub<Output = T>,
|
||||
{
|
||||
let remainder = value % alignment;
|
||||
if remainder == T::default() {
|
||||
value
|
||||
} else {
|
||||
value + alignment - remainder
|
||||
}
|
||||
pub fn align_to<T: AlignTo>(value: T, alignment: T) -> T {
|
||||
value.align_to(alignment)
|
||||
}
|
||||
@@ -470,7 +470,7 @@ pub enum IndexFormat {
|
||||
|
||||
impl IndexFormat {
|
||||
/// Returns the size in bytes of the index format
|
||||
pub fn byte_size(&self) -> usize {
|
||||
pub fn byte_size(&self) -> u32 {
|
||||
match self {
|
||||
IndexFormat::Uint16 => 2,
|
||||
IndexFormat::Uint32 => 4,
|
||||
|
||||
Reference in new issue
Block a user