From c4b25b8794d28f73abcb84ed159deb25cae2cf11 Mon Sep 17 00:00:00 2001 From: Kevin Reid Date: Thu, 13 Feb 2025 05:40:09 -0800 Subject: [PATCH] Duplicate `BufferSlice` methods onto `Buffer` and vice versa. (#7123) This allows users to skip creation of `BufferSlice` if they have no use for it, and brings `wgpu` closer to the WebGPU API without removing any Rust convenience. New functions: * `BufferSlice::slice()` * `Buffer::map_async()` * `Buffer::get_mapped_range()` * `Buffer::get_mapped_range_mut()` * `Buffer::get_mapped_range()` --- CHANGELOG.md | 2 + tests/validation_tests/api/buffer.rs | 32 +++++++ tests/validation_tests/api/mod.rs | 1 + tests/validation_tests/noop.rs | 17 +--- tests/validation_tests/root.rs | 22 +++++ wgpu/src/api/buffer.rs | 125 ++++++++++++++++++++++++--- 6 files changed, 170 insertions(+), 29 deletions(-) create mode 100644 tests/validation_tests/api/buffer.rs create mode 100644 tests/validation_tests/api/mod.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 93961b42a..76b78382d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,6 +50,8 @@ Bottom level categories: By @kpreid in [#7063](https://github.com/gfx-rs/wgpu/pull/7063). +- Added `Buffer` methods corresponding to `BufferSlice` methods, so you can skip creating a `BufferSlice` when it offers no benefit, and `BufferSlice::slice()` for sub-slicing a slice. By @kpreid in [#7123](https://github.com/gfx-rs/wgpu/pull/7123). + #### Naga - Support @must_use attribute on function declarations. By @turbocrime in [#6801](https://github.com/gfx-rs/wgpu/pull/6801). diff --git a/tests/validation_tests/api/buffer.rs b/tests/validation_tests/api/buffer.rs new file mode 100644 index 000000000..f0469c608 --- /dev/null +++ b/tests/validation_tests/api/buffer.rs @@ -0,0 +1,32 @@ +//! Tests of [`wgpu::Buffer`] and related. + +mod buffer_slice { + #[test] + fn reslice_success() { + let (device, _queue) = crate::request_noop_device(); + + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 100, + usage: wgpu::BufferUsages::VERTEX, + mapped_at_creation: false, + }); + + assert_eq!(buffer.slice(10..90).slice(10..70), buffer.slice(20..80)); + } + + #[test] + #[should_panic = "slice offset 10 size 80 is out of range for buffer of size 80"] + fn reslice_out_of_bounds() { + let (device, _queue) = crate::request_noop_device(); + + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: 100, + usage: wgpu::BufferUsages::VERTEX, + mapped_at_creation: false, + }); + + buffer.slice(10..90).slice(10..90); + } +} diff --git a/tests/validation_tests/api/mod.rs b/tests/validation_tests/api/mod.rs new file mode 100644 index 000000000..3e5a66613 --- /dev/null +++ b/tests/validation_tests/api/mod.rs @@ -0,0 +1 @@ +mod buffer; diff --git a/tests/validation_tests/noop.rs b/tests/validation_tests/noop.rs index 65c1681da..3fac4b4b0 100644 --- a/tests/validation_tests/noop.rs +++ b/tests/validation_tests/noop.rs @@ -19,22 +19,7 @@ fn device_is_not_available_by_default() { #[test] fn device_and_buffers() { - let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor { - backends: wgpu::Backends::NOOP, - backend_options: wgpu::BackendOptions { - noop: wgpu::NoopBackendOptions { enable: true }, - ..Default::default() - }, - ..Default::default() - }); - let adapter = - pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) - .expect("adapter"); - let (device, queue) = - pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default(), None)) - .expect("device"); - - assert_eq!(adapter.get_info().backend, wgpu::Backend::Noop); + let (device, queue) = crate::request_noop_device(); // Demonstrate that creating and *writing* to a buffer succeeds. // This also involves creation of a staging buffer. diff --git a/tests/validation_tests/root.rs b/tests/validation_tests/root.rs index e2e090c5b..1f899a5b1 100644 --- a/tests/validation_tests/root.rs +++ b/tests/validation_tests/root.rs @@ -1,3 +1,25 @@ //! Tests of the [`wgpu`] library API that are not run against a particular GPU. +mod api; mod noop; + +/// Obtain a device using [`wgpu::Backend::Noop`]. +/// This should never fail. +fn request_noop_device() -> (wgpu::Device, wgpu::Queue) { + let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor { + backends: wgpu::Backends::NOOP, + backend_options: wgpu::BackendOptions { + noop: wgpu::NoopBackendOptions { enable: true }, + ..Default::default() + }, + ..Default::default() + }); + + let adapter = + pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) + .expect("adapter"); + assert_eq!(adapter.get_info().backend, wgpu::Backend::Noop); + + pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default(), None)) + .expect("device") +} diff --git a/wgpu/src/api/buffer.rs b/wgpu/src/api/buffer.rs index e4e3f1ab7..26a4c2a91 100644 --- a/wgpu/src/api/buffer.rs +++ b/wgpu/src/api/buffer.rs @@ -218,8 +218,6 @@ impl Buffer { } } - /// Return a slice of a [`Buffer`]'s bytes. - /// /// Return a [`BufferSlice`] referring to the portion of `self`'s contents /// indicated by `bounds`. Regardless of what sort of data `self` stores, /// `bounds` start and end are given in bytes. @@ -266,6 +264,81 @@ impl Buffer { pub fn usage(&self) -> BufferUsages { self.usage } + + /// Map the buffer. Buffer is ready to map once the callback is called. + /// + /// For the callback to complete, either `queue.submit(..)`, `instance.poll_all(..)`, or `device.poll(..)` + /// must be called elsewhere in the runtime, possibly integrated into an event loop or run on a separate thread. + /// + /// The callback will be called on the thread that first calls the above functions after the gpu work + /// has completed. There are no restrictions on the code you can run in the callback, however on native the + /// call to the function will not complete until the callback returns, so prefer keeping callbacks short + /// and used to set flags, send messages, etc. + /// + /// This can also be performed using [`BufferSlice::map_async()`]. + pub fn map_async>( + &self, + mode: MapMode, + bounds: S, + callback: impl FnOnce(Result<(), BufferAsyncError>) + WasmNotSend + 'static, + ) { + self.slice(bounds).map_async(mode, callback) + } + + /// Gain read-only access to the bytes of a [mapped] [`Buffer`]. + /// + /// Return a [`BufferView`] referring to the buffer range represented by + /// `self`. See the documentation for [`BufferView`] for details. + /// + /// This can also be performed using [`BufferSlice::get_mapped_range()`]. + /// + /// # Panics + /// + /// - If the buffer to which `self` refers is not currently [mapped]. + /// - If you try to create overlapping views of a buffer, mutable or otherwise. + /// + /// [mapped]: Buffer#mapping-buffers + pub fn get_mapped_range>(&self, bounds: S) -> BufferView<'_> { + self.slice(bounds).get_mapped_range() + } + + /// Synchronously and immediately map a buffer for reading. If the buffer is not immediately mappable + /// through [`BufferDescriptor::mapped_at_creation`] or [`BufferSlice::map_async`], will fail. + /// + /// This is useful when targeting WebGPU and you want to pass mapped data directly to js. + /// Unlike `get_mapped_range` which unconditionally copies mapped data into the wasm heap, + /// this function directly hands you the ArrayBuffer that we mapped the data into in js. + /// + /// This is only available on WebGPU, on any other backends this will return `None`. + /// + /// This can also be performed using [`BufferSlice::get_mapped_range_as_array_buffer()`]. + #[cfg(webgpu)] + pub fn get_mapped_range_as_array_buffer>( + &self, + bounds: S, + ) -> Option { + self.slice(bounds).get_mapped_range_as_array_buffer() + } + + /// Gain write access to the bytes of a [mapped] [`Buffer`]. + /// + /// Return a [`BufferViewMut`] referring to the buffer range represented by + /// `self`. See the documentation for [`BufferViewMut`] for more details. + /// + /// This can also be performed using [`BufferSlice::get_mapped_range_mut()`]. + /// + /// # Panics + /// + /// - If the buffer to which `self` refers is not currently [mapped]. + /// - If you try to create overlapping views of a buffer, mutable or otherwise. + /// + /// [mapped]: Buffer#mapping-buffers + pub fn get_mapped_range_mut>( + &self, + bounds: S, + ) -> BufferViewMut<'_> { + self.slice(bounds).get_mapped_range_mut() + } } /// A slice of a [`Buffer`], to be mapped, used for vertex or index data, or the like. @@ -307,7 +380,7 @@ impl Buffer { /// working with the [`Buffer`], instead. /// /// [map]: Buffer#mapping-buffers -#[derive(Copy, Clone, Debug)] +#[derive(Copy, Clone, Debug, PartialEq)] pub struct BufferSlice<'a> { pub(crate) buffer: &'a Buffer, pub(crate) offset: BufferAddress, @@ -317,6 +390,30 @@ pub struct BufferSlice<'a> { static_assertions::assert_impl_all!(BufferSlice<'_>: Send, Sync); impl<'a> BufferSlice<'a> { + /// Return another [`BufferSlice`] referring to the portion of `self`'s contents + /// indicated by `bounds`. + /// + /// The `range` argument can be half or fully unbounded: for example, + /// `buffer.slice(..)` refers to the entire buffer, and `buffer.slice(n..)` + /// refers to the portion starting at the `n`th byte and extending to the + /// end of the buffer. + pub fn slice>(&self, bounds: S) -> BufferSlice<'a> { + let (offset, size) = range_to_offset_size(bounds); + check_buffer_bounds( + match self.size { + Some(size) => size.get(), + None => self.buffer.size(), + }, + offset, + size, + ); + BufferSlice { + buffer: self.buffer, + offset: self.offset + offset, // check_buffer_bounds ensures this does not overflow + size: size.or(self.size), // check_buffer_bounds ensures this is essentially min() + } + } + /// Map the buffer. Buffer is ready to map once the callback is called. /// /// For the callback to complete, either `queue.submit(..)`, `instance.poll_all(..)`, or `device.poll(..)` @@ -326,6 +423,8 @@ impl<'a> BufferSlice<'a> { /// has completed. There are no restrictions on the code you can run in the callback, however on native the /// call to the function will not complete until the callback returns, so prefer keeping callbacks short /// and used to set flags, send messages, etc. + /// + /// This can also be performed using [`Buffer::map_async()`]. pub fn map_async( &self, mode: MapMode, @@ -349,13 +448,12 @@ impl<'a> BufferSlice<'a> { /// Return a [`BufferView`] referring to the buffer range represented by /// `self`. See the documentation for [`BufferView`] for details. /// + /// This can also be performed using [`Buffer::get_mapped_range()`]. + /// /// # Panics /// - /// - This panics if the buffer to which `self` refers is not currently - /// [mapped]. - /// - /// - If you try to create overlapping views of a buffer, mutable or - /// otherwise, `get_mapped_range` will panic. + /// - If the buffer to which `self` refers is not currently [mapped]. + /// - If you try to create overlapping views of a buffer, mutable or otherwise. /// /// [mapped]: Buffer#mapping-buffers pub fn get_mapped_range(&self) -> BufferView<'a> { @@ -375,6 +473,8 @@ impl<'a> BufferSlice<'a> { /// this function directly hands you the ArrayBuffer that we mapped the data into in js. /// /// This is only available on WebGPU, on any other backends this will return `None`. + /// + /// This can also be performed using [`Buffer::get_mapped_range_as_array_buffer()`]. #[cfg(webgpu)] pub fn get_mapped_range_as_array_buffer(&self) -> Option { let end = self.buffer.map_context.lock().add(self.offset, self.size); @@ -389,13 +489,12 @@ impl<'a> BufferSlice<'a> { /// Return a [`BufferViewMut`] referring to the buffer range represented by /// `self`. See the documentation for [`BufferViewMut`] for more details. /// + /// This can also be performed using [`Buffer::get_mapped_range_mut()`]. + /// /// # Panics /// - /// - This panics if the buffer to which `self` refers is not currently - /// [mapped]. - /// - /// - If you try to create overlapping views of a buffer, mutable or - /// otherwise, `get_mapped_range_mut` will panic. + /// - If the buffer to which `self` refers is not currently [mapped]. + /// - If you try to create overlapping views of a buffer, mutable or otherwise. /// /// [mapped]: Buffer#mapping-buffers pub fn get_mapped_range_mut(&self) -> BufferViewMut<'a> {