### starts_with example Source: https://docs.rs/wgpu/latest/wgpu/struct.BufferView.html Illustrates checking if a slice starts with a given prefix. ```rust let v = [10, 40, 30]; assert!(v.starts_with(&[10])); assert!(v.starts_with(&[10, 40])); assert!(v.starts_with(&v)); assert!(!v.starts_with(&[50])); assert!(!v.starts_with(&[10, 50])); ``` -------------------------------- ### first example Source: https://docs.rs/wgpu/latest/wgpu/struct.BufferView.html Example of using the first method. ```rust let v = [10, 40, 30]; assert_eq!(Some(&10), v.first()); let w: &[i32] = &[]; assert_eq!(None, w.first()); ``` -------------------------------- ### unwrap example Source: https://docs.rs/wgpu/latest/wgpu/type.Label.html A simple example of using `unwrap` to get the value from a Some variant. ```rust let x = Some("air"); assert_eq!(x.unwrap(), "air"); ``` -------------------------------- ### windows() example with overlapping windows Source: https://docs.rs/wgpu/latest/wgpu/struct.BufferView.html Demonstrates how to use the windows() method to get overlapping windows of a specified size from a slice. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.windows(3); assert_eq!(iter.next().unwrap(), &['l', 'o', 'r']); assert_eq!(iter.next().unwrap(), &['o', 'r', 'e']); assert_eq!(iter.next().unwrap(), &['r', 'e', 'm']); assert!(iter.next().is_none()); ``` -------------------------------- ### split_first example Source: https://docs.rs/wgpu/latest/wgpu/struct.BufferView.html Example of using the split_first method. ```rust let x = &[0, 1, 2]; if let Some((first, elements)) = x.split_first() { assert_eq!(first, &0); assert_eq!(elements, &[1, 2]); } ``` -------------------------------- ### trim_ascii_start example Source: https://docs.rs/wgpu/latest/wgpu/struct.BufferView.html Example of using the trim_ascii_start method. ```rust assert_eq!(b" \t hello world\n".trim_ascii_start(), b"hello world\n"); assert_eq!(b" ".trim_ascii_start(), b""); assert_eq!(b"".trim_ascii_start(), b""); ``` -------------------------------- ### get Source: https://docs.rs/wgpu/latest/wgpu/struct.BufferView.html Examples of using the `get` method on slices for element and subslice retrieval. ```rust let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` -------------------------------- ### Instance::new Source: https://docs.rs/wgpu/latest/src/wgpu/api/instance.rs.html?search=std%3A%3Avec Creates a new wgpu Instance with specified options and enabled backends. It panics if no backend feature for the active target platform is enabled. ```APIDOC ## Instance::new ### Description Creates a new wgpu Instance using the given options and enabled backends. This is the primary way to initialize wgpu. ### Method `Instance::new(desc: InstanceDescriptor)` ### Parameters * `desc` (InstanceDescriptor) - The descriptor containing instance creation options. ### Panics * If no backend feature for the active target platform is enabled. See `Instance::enabled_backend_features()`. ### Response * Returns a new `Instance` object. ``` -------------------------------- ### binary_search example Source: https://docs.rs/wgpu/latest/wgpu/struct.BufferView.html Examples demonstrating the usage of the `binary_search` method for finding an element in a sorted slice. ```rust let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; assert_eq!(s.binary_search(&13), Ok(9)); assert_eq!(s.binary_search(&4), Err(7)); assert_eq!(s.binary_search(&100), Err(13)); let r = s.binary_search(&1); assert!(match r { Ok(1..=4) => true, _ => false, }); ``` ```rust let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; let low = s.partition_point(|x| x < &1); assert_eq!(low, 1); let high = s.partition_point(|x| x <= &1); assert_eq!(high, 5); let r = s.binary_search(&1); assert!((low..high).contains(&r.unwrap())); assert!(s[..low].iter().all(|&x| x < 1)); assert!(s[low..high].iter().all(|&x| x == 1)); assert!(s[high..].iter().all(|&x| x > 1)); // For something not found, the "range" of equal items is empty assert_eq!(s.partition_point(|x| x < &11), 9); assert_eq!(s.partition_point(|x| x <= &11), 9); assert_eq!(s.binary_search(&11), Err(9)); ``` ```rust let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; let num = 42; let idx = s.partition_point(|&x| x <= num); // If `num` is unique, `s.partition_point(|&x| x < num)` (with `<`) is equivalent to // `s.binary_search(&num).unwrap_or_else(|x| x)`, but using `<=` will allow `insert` // to shift less elements. s.insert(idx, num); assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]); ``` -------------------------------- ### Instance::default Source: https://docs.rs/wgpu/latest/wgpu/struct.Instance.html?search=std%3A%3Avec Creates a new instance of wgpu with default options. ```APIDOC ## Instance::default ### Description Creates a new instance of wgpu with default options. Backends are set to `Backends::all()`, and FXC is chosen as the `dx12_shader_compiler`. ### Panics If no backend feature for the active target platform is enabled, this method will panic, see `Instance::enabled_backend_features()`. ### Signature `fn default() -> Self` ``` -------------------------------- ### write_buffer example Source: https://docs.rs/wgpu/latest/wgpu/struct.Queue.html Example of writing data to a buffer using write_buffer and submitting an empty command buffer to start execution immediately. ```rust queue.write_buffer(&buffer, 0, &data); queue.submit([]); ``` -------------------------------- ### Example of `Box::new` Source: https://docs.rs/wgpu/latest/wgpu/custom/type.BoxSubmittedWorkDoneCallback.html A simple example demonstrating the creation of a `Box` containing an integer. ```rust let five = Box::new(5); ``` -------------------------------- ### Manually create a Box from scratch Source: https://docs.rs/wgpu/latest/wgpu/custom/type.BufferMapCallback.html This example shows how to manually create a `Box` from scratch using the system allocator, by allocating memory, writing a value, and then constructing the `Box`. ```rust #![feature(allocator_api)] use std::alloc::{Allocator, Layout, System}; unsafe { let non_null = System.allocate(Layout::new::())?.cast::(); // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `non_null`. non_null.write(5); let x = Box::from_non_null_in(non_null, System); } ``` -------------------------------- ### Instance::new Source: https://docs.rs/wgpu/latest/src/wgpu/api/instance.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new wgpu instance with the specified descriptor, which includes options for backends and other configurations. It panics if no backend features are enabled for the target platform. ```APIDOC ## Instance::new ### Description Creates a new wgpu instance using the given options and enabled backends. This is the primary way to initialize wgpu. ### Method `Instance::new(desc: InstanceDescriptor)` ### Parameters * `desc` (InstanceDescriptor) - The descriptor containing instance creation options. ### Panics * If no backend feature for the active target platform is enabled, this method will panic. See `Instance::enabled_backend_features()` for more information. ### Related Functions * [`Instance::enabled_backend_features()`] * [`Instance::default()`] ``` -------------------------------- ### Example of WriteOnly::len Source: https://docs.rs/wgpu/latest/wgpu/struct.WriteOnly.html Demonstrates how to get the length of a WriteOnly slice. ```rust let example_slice: &mut [u8] = &mut [0; 10]; assert_eq!(wgpu::WriteOnly::from_mut(example_slice).len(), example_slice.len()); ``` -------------------------------- ### Instance::new Source: https://docs.rs/wgpu/latest/wgpu/struct.Instance.html?search=u32+-%3E+bool Creates a new wgpu instance with the specified descriptor. This is the first step in using wgpu. ```APIDOC ## Instance::new ### Description Create a new instance of wgpu using the given options and enabled backends. ### Method `pub fn new(desc: InstanceDescriptor) -> Self` ### Panics If no backend feature for the active target platform is enabled, this method will panic; see `Instance::enabled_backend_features()`. ``` -------------------------------- ### Get Offset of Buffer Slice Source: https://docs.rs/wgpu/latest/src/wgpu/api/buffer.rs.html?search=std%3A%3Avec Returns the starting offset of this `BufferSlice` within its underlying `Buffer`. ```rust pub fn offset(&self) -> BufferAddress { self.offset } ``` -------------------------------- ### rsplitn Source: https://docs.rs/wgpu/latest/wgpu/struct.BufferView.html Example of using `rsplitn` to limit the number of subslices returned, starting from the end. ```rust let v = [10, 40, 30, 20, 60, 50]; for group in v.rsplitn(2, |num| *num % 3 == 0) { println!("{group:?}"); } ``` -------------------------------- ### Create New Instance Source: https://docs.rs/wgpu/latest/wgpu/struct.Instance.html?search=std%3A%3Avec Creates a new wgpu instance with specified options and enabled backends. Panics if no backend feature for the active target platform is enabled. ```rust pub fn new(desc: InstanceDescriptor) -> Self ``` -------------------------------- ### Default trait implementation example Source: https://docs.rs/wgpu/latest/wgpu/type.Label.html Shows how to get the default value for an Option, which is None. ```rust let opt: Option = Option::default(); assert!(opt.is_none()); ``` -------------------------------- ### windows() example with Cell and swap Source: https://docs.rs/wgpu/latest/wgpu/struct.BufferView.html Demonstrates a workaround for the lack of a windows_mut analog using Cell::as_slice_of_cells and Cell::swap. ```rust use std::cell::Cell; let mut array = ['R', 'u', 's', 't', ' ', '2', '0', '1', '5']; let slice = &mut array[..]; let slice_of_cells: &[Cell] = Cell::from_mut(slice).as_slice_of_cells(); for w in slice_of_cells.windows(3) { Cell::swap(&w[0], &w[2]); } assert_eq!(array, ['s', 't', ' ', '2', '0', '1', '5', 'u', 'R']); ``` -------------------------------- ### Option::xor Example Source: https://docs.rs/wgpu/latest/wgpu/type.Label.html?search=std%3A%3Avec Use `xor` to get a value if exactly one of the Options is Some. Otherwise, returns None. ```rust let x = Some(2); let y: Option = None; assert_eq!(x.xor(y), Some(2)); let x: Option = None; let y = Some(2); assert_eq!(x.xor(y), Some(2)); let x = Some(2); let y = Some(2); assert_eq!(x.xor(y), None); let x: Option = None; let y: Option = None; assert_eq!(x.xor(y), None); ``` -------------------------------- ### Box::from_raw Example with Global Allocator Source: https://docs.rs/wgpu/latest/wgpu/custom/type.BoxDeviceLostCallback.html?search= Shows how to manually create a Box from scratch using the global allocator and Box::from_raw. ```rust use std::alloc::{alloc, Layout}; unsafe { let ptr = alloc(Layout::new::()) as *mut i32; // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `ptr`, though for this // simple example `*ptr = 5` would have worked as well. ptr.write(5); let x = Box::from_raw(ptr); } ``` -------------------------------- ### Box::from_raw Example 2 Source: https://docs.rs/wgpu/latest/wgpu/custom/type.BoxDeviceLostCallback.html Manually creating a Box from scratch using the global allocator. ```rust use std::alloc::{alloc, Layout}; unsafe { let ptr = alloc(Layout::new::()) as *mut i32; // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `ptr`, though for this // simple example `*ptr = 5` would have worked as well. ptr.write(5); let x = Box::from_raw(ptr); } ``` -------------------------------- ### Option::iter Example Source: https://docs.rs/wgpu/latest/wgpu/type.Label.html Shows how to use iter to get an iterator over the possibly contained value. ```rust let x = Some(4); assert_eq!(x.iter().next(), Some(&4)); let x: Option = None; assert_eq!(x.iter().next(), None); ``` -------------------------------- ### Instance::default Source: https://docs.rs/wgpu/latest/src/wgpu/api/instance.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new wgpu instance with default options. Backends are set to `Backends::all()`, and FXC is chosen as the `dx12_shader_compiler`. This method panics if no backend features are enabled for the target platform. ```APIDOC ## Instance::default ### Description Creates a new instance of wgpu with default options. Backends are set to `Backends::all()`, and FXC is chosen as the `dx12_shader_compiler`. ### Method `Instance::default()` ### Panics * If no backend feature for the active target platform is enabled, this method will panic. See `Instance::enabled_backend_features()` for more information. ### Related Functions * [`Instance::new()`] * [`Instance::enabled_backend_features()`] ``` -------------------------------- ### as_slice example Source: https://docs.rs/wgpu/latest/wgpu/type.Label.html Demonstrates the usage of `as_slice` to get a slice from an Option, handling both Some and None cases. ```rust assert_eq!( [Some(1234).as_slice(), None.as_slice()], [&[1234][..], &[][..]], ); ``` -------------------------------- ### as_ptr Source: https://docs.rs/wgpu/latest/wgpu/struct.BufferView.html Example of using `as_ptr` to get a raw pointer to the slice's buffer and iterating through it. ```rust let x = &[1, 2, 4]; let x_ptr = x.as_ptr(); unsafe { for i in 0..x.len() { assert_eq!(x.get_unchecked(i), &*x_ptr.add(i)); } } ``` -------------------------------- ### Instance::default Source: https://docs.rs/wgpu/latest/src/wgpu/api/instance.rs.html?search=std%3A%3Avec Creates a new wgpu Instance with default options. Backends are set to `Backends::all()`, and FXC is chosen as the `dx12_shader_compiler`. ```APIDOC ## Instance::default ### Description Creates a new wgpu Instance with default options. This is a convenient way to get started without explicit configuration. ### Method `Default::default()` for `Instance` ### Panics * If no backend feature for the active target platform is enabled. See `Instance::enabled_backend_features()`. ### Response * Returns a new `Instance` object with default settings. ``` -------------------------------- ### Example of `Box::new_uninit` Source: https://docs.rs/wgpu/latest/wgpu/custom/type.BoxSubmittedWorkDoneCallback.html Demonstrates creating a `Box` with uninitialized contents and then initializing it. ```rust let mut five = Box::::new_uninit(); // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5) ``` -------------------------------- ### TextureBlitter::new Source: https://docs.rs/wgpu/latest/src/wgpu/util/texture_blitter.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Constructs a new TextureBlitter with default settings. This is a convenient way to get started with texture blitting. ```APIDOC ## TextureBlitter::new ### Description Returns a [`TextureBlitter`] with default settings. ### Arguments - `device`: A [`Device`] - `format`: The [`TextureFormat`] of the texture that will be copied to. This has to have the `RENDER_TARGET` usage. ### Returns A new instance of `TextureBlitter`. ### Example ```rust let blitter = TextureBlitter::new(&device, TextureFormat::Rgba8UnormSrgb); ``` ``` -------------------------------- ### Option::as_deref_mut Example Source: https://docs.rs/wgpu/latest/wgpu/type.Label.html Demonstrates the usage of as_deref_mut to get a mutable reference to the inner value and modify it. ```rust let mut x: Option = Some("hey".to_owned()); assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), Some("HEY".to_owned().as_mut_str())); ``` -------------------------------- ### initialize_adapter_from_env_or_default Source: https://docs.rs/wgpu/latest/src/wgpu/util/init.rs.html?search=std%3A%3Avec Initializes an adapter by first attempting to use the `WGPU_ADAPTER_NAME` environment variable via `initialize_adapter_from_env`. If that fails (e.g., the environment variable is not set or no matching adapter is found), it falls back to requesting a default adapter using `Instance::request_adapter` with options derived from the environment. ```APIDOC ## initialize_adapter_from_env_or_default ### Description Initializes an adapter by first attempting to use the `WGPU_ADAPTER_NAME` environment variable via `initialize_adapter_from_env`. If that fails (e.g., the environment variable is not set or no matching adapter is found), it falls back to requesting a default adapter using `Instance::request_adapter` with options derived from the environment. ### Function Signature ```rust pub async fn initialize_adapter_from_env_or_default<'a>( instance: &'a Instance, compatible_surface: Option<&'a Surface<'a>>, ) -> Result ``` ### Parameters * `instance`: A reference to the `Instance` to use for requesting adapters. * `compatible_surface`: An optional reference to a `Surface` to check for compatibility with the adapter. ### Returns A `Result` containing the chosen `Adapter`, either from the environment variable or the default fallback, or a `wgt::RequestAdapterError` if the default request also fails. ``` -------------------------------- ### rchunks example Source: https://docs.rs/wgpu/latest/wgpu/struct.BufferView.html Shows how to use `rchunks` to get an iterator over chunks of a specified size from the end of the slice. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert_eq!(iter.next().unwrap(), &['l']); assert!(iter.next().is_none()); ``` -------------------------------- ### expect recommended message style example Source: https://docs.rs/wgpu/latest/wgpu/type.Label.html Shows the recommended style for `expect` messages, focusing on the reason why the Option should be Some. ```rust let item = slice.get(0) .expect("slice should not be empty"); ``` -------------------------------- ### chunks() example Source: https://docs.rs/wgpu/latest/wgpu/struct.BufferView.html Demonstrates how to use the chunks() method to get non-overlapping chunks of a specified size from a slice. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.chunks(2); assert_eq!(iter.next().unwrap(), &['l', 'o']); assert_eq!(iter.next().unwrap(), &['r', 'e']); assert_eq!(iter.next().unwrap(), &['m']); assert!(iter.next().is_none()); ``` -------------------------------- ### Option::iter_mut Example Source: https://docs.rs/wgpu/latest/wgpu/type.Label.html Demonstrates using iter_mut to get a mutable iterator over the possibly contained value and modify it. ```rust let mut x = Some(4); match x.iter_mut().next() { Some(v) => *v = 42, None => {}, } assert_eq!(x, Some(42)); let mut x: Option = None; assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### chunks_exact() example Source: https://docs.rs/wgpu/latest/wgpu/struct.BufferView.html Demonstrates how to use the chunks_exact() method to get exactly sized chunks from a slice, and how to access the remainder. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.chunks_exact(2); assert_eq!(iter.next().unwrap(), &['l', 'o']); assert_eq!(iter.next().unwrap(), &['r', 'e']); assert!(iter.next().is_none()); assert_eq!(iter.remainder(), &['m']); ``` -------------------------------- ### Manually create a Box from scratch by using the system allocator Source: https://docs.rs/wgpu/latest/wgpu/custom/type.BoxSubmittedWorkDoneCallback.html This example shows how to manually create a Box from scratch using the system allocator, involving allocating memory, writing a value, and then constructing the Box. ```rust #![feature(allocator_api)] use std::alloc::{Allocator, Layout, System}; unsafe { let non_null = System.allocate(Layout::new::())?.cast::(); // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `non_null`. non_null.write(5); let x = Box::from_non_null_in(non_null, System); } ``` -------------------------------- ### as_ptr_range Source: https://docs.rs/wgpu/latest/wgpu/struct.BufferView.html Example demonstrating the use of `as_ptr_range` to get raw pointers spanning the slice and checking pointer containment. ```rust let a = [1, 2, 3]; let x = &a[1] as *const _; let y = &5 as *const _; assert!(a.as_ptr_range().contains(&x)); assert!(!a.as_ptr_range().contains(&y)); ``` -------------------------------- ### initialize_adapter_from_env_or_default Source: https://docs.rs/wgpu/latest/src/wgpu/util/init.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes a wgpu adapter using the `WGPU_ADAPTER_NAME` environment variable. If an adapter is found based on the environment variable, it is returned. Otherwise, it falls back to requesting a default adapter using `Instance::request_adapter`. ```APIDOC ## initialize_adapter_from_env_or_default ### Description Initializes a wgpu adapter using the `WGPU_ADAPTER_NAME` environment variable. If an adapter is found based on the environment variable, it is returned. Otherwise, it falls back to requesting a default adapter using `Instance::request_adapter`. ### Function Signature ```rust pub async fn initialize_adapter_from_env_or_default( instance: &Instance, compatible_surface: Option<&Surface<'_>>, ) -> Result ``` ### Parameters * `instance`: A reference to the `Instance` to use for enumerating adapters. * `compatible_surface`: An optional reference to a `Surface` to check for adapter compatibility. ### Returns A `Result` containing the `Adapter` if found, or a `wgt::RequestAdapterError` if an error occurs during the fallback adapter request. ``` -------------------------------- ### Instance::new Source: https://docs.rs/wgpu/latest/wgpu/struct.Instance.html Creates a new instance of wgpu with specified options and enabled backends. ```rust pub fn new(desc: InstanceDescriptor) -> Self ``` -------------------------------- ### DownloadBuffer Example Source: https://docs.rs/wgpu/latest/src/wgpu/util/mod.rs.html Demonstrates how to asynchronously read the contents of a buffer from the GPU back to the CPU using `DownloadBuffer`. ```rust /// CPU accessible buffer used to download data back from the GPU. pub struct DownloadBuffer { _gpu_buffer: super::Buffer, mapped_range: dispatch::DispatchBufferMappedRange, } impl DownloadBuffer { /// Asynchronously read the contents of a buffer. pub fn read_buffer( device: &super::Device, queue: &super::Queue, buffer: &super::BufferSlice<'_>, callback: impl FnOnce(Result) + Send + 'static, ) { let size = buffer.size.into(); let download = device.create_buffer(&super::BufferDescriptor { size, usage: super::BufferUsages::COPY_DST | super::BufferUsages::MAP_READ, mapped_at_creation: false, label: None, }); let mut encoder = device.create_command_encoder(&super::CommandEncoderDescriptor { label: None }); encoder.copy_buffer_to_buffer(buffer.buffer, buffer.offset, &download, 0, size); let command_buffer: super::CommandBuffer = encoder.finish(); queue.submit(Some(command_buffer)); download .clone() .slice(..) .map_async(super::MapMode::Read, move |result| { if let Err(e) = result { callback(Err(e)); return; } let mapped_range = download.inner.get_mapped_range(0..size); callback(Ok(Self { _gpu_buffer: download, mapped_range, })); }); } } impl core::ops::Deref for DownloadBuffer { type Target = [u8]; fn deref(&self) -> &[u8] { // SAFETY: `self.mapped_range` is always a read mapping unsafe { self.mapped_range.read_slice() } } } ``` -------------------------------- ### Getting a mutable view of a mapped buffer Source: https://docs.rs/wgpu/latest/wgpu/struct.Buffer.html This example demonstrates how to gain write access to the bytes of a mapped `Buffer` using `get_mapped_range_mut()`. ```rust pub fn get_mapped_range_mut>( &self, bounds: S, ) -> BufferViewMut ``` -------------------------------- ### initialize_adapter_from_env_or_default Source: https://docs.rs/wgpu/latest/src/wgpu/util/init.rs.html?search= Initializes a wgpu adapter by first attempting to use the `WGPU_ADAPTER_NAME` environment variable via `initialize_adapter_from_env`. If that fails (e.g., the environment variable is not set or no adapter matches), it falls back to requesting a default adapter using `Instance::request_adapter` with default options. ```APIDOC ## initialize_adapter_from_env_or_default ### Description Initializes a wgpu adapter by first attempting to use the `WGPU_ADAPTER_NAME` environment variable via `initialize_adapter_from_env`. If that fails (e.g., the environment variable is not set or no adapter matches), it falls back to requesting a default adapter using `Instance::request_adapter` with default options. ### Function Signature ```rust pub async fn initialize_adapter_from_env_or_default( instance: &Instance, compatible_surface: Option<&Surface<'_>>, ) -> Result ``` ### Parameters * `instance` (*Instance*) - A reference to the wgpu Instance. * `compatible_surface` (*Option<&Surface<'_>>*) - An optional reference to a Surface to check for compatibility. ### Returns * `Result` - Returns the chosen `Adapter` if successful, otherwise returns a `wgt::RequestAdapterError` from the fallback mechanism. ``` -------------------------------- ### Getting a read-only view of a mapped buffer Source: https://docs.rs/wgpu/latest/wgpu/struct.Buffer.html This example shows how to gain read-only access to the bytes of a mapped `Buffer` using `get_mapped_range()`. ```rust pub fn get_mapped_range>( &self, bounds: S, ) -> BufferView ``` -------------------------------- ### Option unwrap_or_default Example Source: https://docs.rs/wgpu/latest/wgpu/type.Label.html?search=std%3A%3Avec Use unwrap_or_default to get the contained value or the default value of the type if the Option is None. This is useful for providing sensible defaults. ```rust assert_eq!(x.unwrap_or_default(), 0); assert_eq!(y.unwrap_or_default(), 12); ``` -------------------------------- ### expect example Source: https://docs.rs/wgpu/latest/wgpu/type.Label.html A basic example of using `expect` to retrieve a value from an Option, providing a custom panic message if it's None. ```rust let x = Some("value"); assert_eq!(x.expect("fruits are healthy"), "value"); ``` -------------------------------- ### Getting a custom buffer implementation Source: https://docs.rs/wgpu/latest/wgpu/struct.Buffer.html This example shows how to retrieve a custom implementation of `Buffer` if a custom backend is used and the internal type matches `T`. ```rust pub fn as_custom(&self) -> Option<&T> ``` -------------------------------- ### Create wgpu Instance with Custom Descriptors Source: https://docs.rs/wgpu/latest/src/wgpu/util/init.rs.html?search= Creates a wgpu instance using a custom InstanceDescriptor. This example demonstrates how to conditionally remove the BROWSER_WEBGPU backend if it's not supported in the browser environment. ```rust let mut instance_desc = wgt::InstanceDescriptor::default(); // Remove BROWSER_WEBGPU backend if it's not supported in the browser. if instance_desc .backends .contains(wgt::Backends::BROWSER_WEBGPU) && !is_browser_webgpu_supported().await { instance_desc.backends.remove(wgt::Backends::BROWSER_WEBGPU); } crate::Instance::new(instance_desc) ``` -------------------------------- ### Get Shader Model from DXC Version Source: https://docs.rs/wgpu/latest/wgpu/enum.DxcShaderModel.html?search= Retrieves the corresponding DxcShaderModel enum variant based on the major and minor version numbers of a DXC installation. ```rust pub fn from_dxc_version(major: u32, minor: u32) -> DxcShaderModel ``` -------------------------------- ### Get Element Offset in a Slice Source: https://docs.rs/wgpu/latest/wgpu/struct.BufferView.html?search= Use `element_offset` to find the index of an element reference within a slice. Returns `None` if the reference is not aligned to the start of an element. ```rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` ```rust let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### new_instance_with_webgpu_detection Source: https://docs.rs/wgpu/latest/src/wgpu/util/init.rs.html?search=std%3A%3Avec Creates a new `wgpu` instance, automatically handling WebGPU detection for browser targets. If the `InstanceDescriptor` specifies `Backends::BROWSER_WEBGPU`, this function first checks for WebGPU support using `is_browser_webgpu_supported`. If support is detected, it proceeds with the descriptor as is; otherwise, it creates the instance without the `Backends::BROWSER_WEBGPU` backend. This is recommended over `Instance::new` for WebGPU targets to allow fallback to WebGL. ```APIDOC ## new_instance_with_webgpu_detection ### Description Creates a new `wgpu` instance, automatically handling WebGPU detection for browser targets. If the `InstanceDescriptor` specifies `Backends::BROWSER_WEBGPU`, this function first checks for WebGPU support using `is_browser_webgpu_supported`. If support is detected, it proceeds with the descriptor as is; otherwise, it creates the instance without the `Backends::BROWSER_WEBGPU` backend. This is recommended over `Instance::new` for WebGPU targets to allow fallback to WebGL. ### Function Signature ```rust pub async fn new_instance_with_webgpu_detection(instance_desc: wgt::InstanceDescriptor) -> crate::Instance ``` ### Parameters * `instance_desc`: The `InstanceDescriptor` to configure the new instance. The `backends` field will be adjusted if WebGPU is not supported. ### Returns A new `Instance` of wgpu. ### Panics If no backend feature for the active target platform is enabled, this method will panic, see [`Instance::enabled_backend_features()`]. ``` -------------------------------- ### Get Presentation Timestamp Example Source: https://docs.rs/wgpu/latest/src/wgpu/api/adapter.rs.html Demonstrates how to use `get_presentation_timestamp` to synchronize with the presentation engine's clock and measure time intervals. ```rust use std::time::{Duration, Instant}; # let adapter: wgpu::Adapter = panic!(); # let some_code = || wgpu::PresentationTimestamp::INVALID_TIMESTAMP; let presentation = adapter.get_presentation_timestamp(); let instant = Instant::now(); // We can now turn a new presentation timestamp into an Instant. let some_pres_timestamp = some_code(); let duration = Duration::from_nanos((some_pres_timestamp.0 - presentation.0) as u64); let new_instant: Instant = instant + duration; ``` -------------------------------- ### Batching Barriers with transition_resources Source: https://docs.rs/wgpu/latest/wgpu/struct.CommandEncoder.html?search= This example demonstrates how to use transition_resources to manually transition resources before and after command buffer usage, reducing the number of automatically inserted barriers. ```rust let mut encoder = device.create_command_encoder(&Default::default()); // CommandBuffer A: // Use `CommandEncoder::transition_resources` to transition resources X and Y from TextureUses::RESOURCE (from last frame) to TextureUses::COLOR_TARGET encoder.transition_resources(buffer_transitions_a, texture_transitions_a); // Use resource X as a render pass attachment // ... render pass setup ... // CommandBuffer B: // Use resource Y as a render pass attachment // ... render pass setup ... // CommandBuffer C: // Use `CommandEncoder::transition_resources` to transition resources X and Y from TextureUses::COLOR_TARGET to TextureUses::RESOURCE encoder.transition_resources(buffer_transitions_c, texture_transitions_c); // Use resources X and Y in a bind group // ... bind group setup ... let command_buffer = encoder.finish(); queue.submit(std::iter::once(command_buffer)); ``` -------------------------------- ### InstanceDescriptor Source: https://docs.rs/wgpu/latest/wgpu/struct.InstanceDescriptor.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Describes the configuration options for creating a wgpu instance. This includes specifying which backends to enable, tuning instance behavior with flags, setting memory budget thresholds, configuring backend-specific options, and providing a system display handle for presentation. ```APIDOC ## Struct InstanceDescriptor ### Description Options for creating an instance. If you want to allow control of instance settings via environment variables, call any of the `*from_env()` functions or `InstanceDescriptor::with_env()`. ### Fields * **`backends: Backends`**: Specifies which `Backends` to enable. `Backends::BROWSER_WEBGPU` has an additional effect on browsers, potentially limiting the instance to only create WebGPU adapters. If WebGPU is not detected, it may fall back to WebGL if the `webgl` feature is enabled. * **`flags: InstanceFlags`**: Flags to tune the behavior of the instance. * **`memory_budget_thresholds: MemoryBudgetThresholds`**: Memory budget thresholds used by some backends. * **`backend_options: BackendOptions`**: Options that control the behavior of specific backends. * **`display: Option>`**: System platform or compositor connection to connect this `Instance` to. If not `None`, it is invalid to pass a different `raw_window_handle::HasDisplayHandle` to `create_surface()`. This is required on GLES for presentation, especially on Wayland, and is unused on Vulkan, Metal, and Dx12. When used with `winit`, callers should pass its `OwnedDisplayHandle`. ``` -------------------------------- ### Rust Option unwrap_unchecked Example Source: https://docs.rs/wgpu/latest/wgpu/type.Label.html?search=std%3A%3Avec Use unwrap_unchecked to get the contained value without checking if it's None. This is unsafe and calling it on None results in undefined behavior. ```rust let x = Some("air"); assert_eq!(unsafe { x.unwrap_unchecked() }, "air"); ``` ```rust let x: Option<&str> = None; assert_eq!(unsafe { x.unwrap_unchecked() }, "air"); // Undefined behavior! ``` -------------------------------- ### initialize_adapter_from_env Source: https://docs.rs/wgpu/latest/src/wgpu/util/init.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes a wgpu adapter by filtering available adapters based on the name specified in the `WGPU_ADAPTER_NAME` environment variable. If the environment variable is not set or no matching adapter is found, it returns an error. ```APIDOC ## initialize_adapter_from_env ### Description Initializes a wgpu adapter by filtering available adapters based on the name specified in the `WGPU_ADAPTER_NAME` environment variable. If the environment variable is not set or no matching adapter is found, it returns an error. ### Function Signature ```rust pub async fn initialize_adapter_from_env( instance: &Instance, compatible_surface: Option<&Surface<'_>>, ) -> Result ``` ### Parameters * `instance`: A reference to the `Instance` to use for enumerating adapters. * `compatible_surface`: An optional reference to a `Surface` to check for adapter compatibility. ### Returns A `Result` containing the `Adapter` if found, or a `wgt::RequestAdapterError` if the environment variable is not set or no matching adapter is found. ``` -------------------------------- ### Create an empty DownlevelFlags value Source: https://docs.rs/wgpu/latest/wgpu/struct.DownlevelFlags.html?search=std%3A%3Avec Use `DownlevelFlags::empty()` to get a flags value with no bits set. This is useful for starting with a clean slate when building up a set of flags. ```rust pub const fn empty() -> DownlevelFlags ``` -------------------------------- ### Example of `Box::try_new_uninit` Source: https://docs.rs/wgpu/latest/wgpu/custom/type.BoxSubmittedWorkDoneCallback.html Shows how to use `Box::try_new_uninit` to create a `Box` with uninitialized contents, handling potential allocation errors. ```rust #![feature(allocator_api)] let mut five = Box::::try_new_uninit()?; // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5); ``` -------------------------------- ### Get wgpu-hal TextureView (Vulkan Example) Source: https://docs.rs/wgpu/latest/wgpu/struct.TextureView.html?search= Safely retrieves the underlying wgpu-hal texture view for the Vulkan backend. This guard holds a read-lock that can cause deadlocks if device destruction is called while the guard is held. ```rust pub unsafe fn as_hal( &self, ) -> Option> ``` -------------------------------- ### Get element index using pointer arithmetic Source: https://docs.rs/wgpu/latest/wgpu/struct.BufferView.html?search=std%3A%3Avec Use `element_offset` to find the index of an element reference within a slice using pointer arithmetic. Returns `None` if the reference is not aligned to an element's start. ```Rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` ```Rust let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); assert_eq!(arr.element_offset(weird_elm), None); ``` -------------------------------- ### MIN Example Source: https://docs.rs/wgpu/latest/wgpu/type.BufferSize.html Shows the minimum value for NonZero. ```rust assert_eq!(NonZero::::MIN.get(), 1u64); ``` -------------------------------- ### Queue::write_buffer Source: https://docs.rs/wgpu/latest/src/wgpu/api/queue.rs.html?search= Copies the bytes of `data` into `buffer` starting at `offset`. The data must be written fully in-bounds, that is, `offset + data.len() <= buffer.len()`. Calls to `write_buffer()` do not submit the transfer to the GPU immediately. They begin GPU execution only on the next call to `Queue::submit()`, just before the explicitly submitted commands. To get a set of scheduled transfers started immediately, it's fine to call `submit` with no command buffers at all. ```APIDOC ## Queue::write_buffer ### Description Copies the bytes of `data` into `buffer` starting at `offset`. The data must be written fully in-bounds, that is, `offset + data.len() <= buffer.len()`. Calls to `write_buffer()` do not submit the transfer to the GPU immediately. They begin GPU execution only on the next call to `Queue::submit()`, just before the explicitly submitted commands. To get a set of scheduled transfers started immediately, it's fine to call `submit` with no command buffers at all. ### Method `write_buffer` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust # let queue: wgpu::Queue = todo!(); # let buffer: wgpu::Buffer = todo!(); # let data = [0u8]; queue.write_buffer(&buffer, 0, &data); ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Queue::write_buffer Source: https://docs.rs/wgpu/latest/src/wgpu/api/queue.rs.html?search=std%3A%3Avec Copies the bytes of `data` into `buffer` starting at `offset`. The data must be written fully in-bounds, that is, `offset + data.len() <= buffer.len()`. Calls to `write_buffer()` do not submit the transfer to the GPU immediately. They begin GPU execution only on the next call to `Queue::submit()`, just before the explicitly submitted commands. To get a set of scheduled transfers started immediately, it's fine to call `submit` with no command buffers at all. ```APIDOC ## Queue::write_buffer ### Description Copies the bytes of `data` into `buffer` starting at `offset`. The data must be written fully in-bounds, that is, `offset + data.len() <= buffer.len()`. Calls to `write_buffer()` do not submit the transfer to the GPU immediately. They begin GPU execution only on the next call to `Queue::submit()`, just before the explicitly submitted commands. To get a set of scheduled transfers started immediately, it's fine to call `submit` with no command buffers at all. ### Method ``` fn write_buffer( &self, buffer: &Buffer, offset: BufferAddress, data: &[u8], ) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust # let queue: wgpu::Queue = todo!(); # let buffer: wgpu::Buffer = todo!(); # let data = [0u8]; queue.write_buffer(&buffer, 0, &data); ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### reduce method example Source: https://docs.rs/wgpu/latest/wgpu/type.Label.html Demonstrates the usage of the `reduce` method on Option, which combines two options using a provided function if both are Some. ```rust #![feature(option_reduce)] let s12 = Some(12); let s17 = Some(17); let n = None; let f = |a, b| a + b; assert_eq!(s12.reduce(s17, f), Some(29)); assert_eq!(s12.reduce(n, f), Some(12)); assert_eq!(n.reduce(s17, f), Some(17)); assert_eq!(n.reduce(n, f), None); ``` -------------------------------- ### Get wgpu-hal Surface (Vulkan Example) Source: https://docs.rs/wgpu/latest/wgpu/struct.Surface.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Safely retrieves the underlying wgpu-hal surface for a given backend, such as Vulkan. This is an unsafe operation and requires adherence to wgpu-hal's safety requirements. The returned guard dereferences to the specific hal backend surface type. ```rust pub unsafe fn as_hal( &self, ) -> Option + WasmNotSendSync> ``` -------------------------------- ### initialize_adapter_from_env Source: https://docs.rs/wgpu/latest/wgpu/util/fn.initialize_adapter_from_env.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes the adapter obeying the `WGPU_ADAPTER_NAME` environment variable. ```APIDOC ## Function initialize_adapter_from_env ### Description Initializes the adapter obeying the `WGPU_ADAPTER_NAME` environment variable. ### Signature ```rust pub async fn initialize_adapter_from_env( instance: &Instance, compatible_surface: Option<&Surface<'_>>, ) -> Result ``` ### Parameters * `instance`: A reference to the wgpu `Instance`. * `compatible_surface`: An optional reference to a `Surface` for compatibility checks. ### Returns A `Result` containing either the initialized `Adapter` or a `RequestAdapterError`. ``` -------------------------------- ### Examples Source: https://docs.rs/wgpu/latest/wgpu/util/fn.pipeline_cache_key.html Example of how to use pipeline_cache_key to manage pipeline caches. ```rust use wgpu::PipelineCacheDescriptor; let cache_dir: PathBuf = unimplemented!("Some reasonable platform-specific cache directory for your app."); let filename = wgpu::util::pipeline_cache_key(&adapter_info); let (pipeline_cache, cache_file) = if let Some(filename) = filename { let cache_path = cache_dir.join(&filename); // If we failed to read the cache, for whatever reason, treat the data as lost. // In a real app, we'd probably avoid caching entirely unless the error was "file not found". let cache_data = std::fs::read(&cache_path).ok(); let pipeline_cache = unsafe { device.create_pipeline_cache(&PipelineCacheDescriptor { data: cache_data.as_deref(), label: None, fallback: true }) }; (Some(pipeline_cache), Some(cache_path)) } else { (None, None) }; // Run pipeline initialisation, making sure to set the `cache` // fields of your `*PipelineDescriptor` to `pipeline_cache` // And then save the resulting cache (probably off the main thread). if let (Some(pipeline_cache), Some(cache_file)) = (pipeline_cache, cache_file) { let data = pipeline_cache.get_data(); if let Some(data) = data { let temp_file = cache_file.with_extension("temp"); std::fs::write(&temp_file, &data)?; std::fs::rename(&temp_file, &cache_file)?; } } ``` -------------------------------- ### Option::and Example Source: https://docs.rs/wgpu/latest/wgpu/type.Label.html Illustrates the behavior of the and method, which returns the second option if the first is Some, otherwise None. ```rust let x = Some(2); let y: Option<&str> = None; assert_eq!(x.and(y), None); let x: Option = None; let y = Some("foo"); assert_eq!(x.and(y), None); let x = Some(2); let y = Some("foo"); assert_eq!(x.and(y), Some("foo")); let x: Option = None; let y: Option<&str> = None; assert_eq!(x.and(y), None); ``` -------------------------------- ### draw example Source: https://docs.rs/wgpu/latest/wgpu/struct.RenderBundleEncoder.html Example of how draw is used internally. ```rust for instance_id in instance_range { for vertex_id in vertex_range { let vertex = vertex[vertex_id]; vertex_shader(vertex, vertex_id, instance_id); } } ``` -------------------------------- ### Buffer Usage Example Source: https://docs.rs/wgpu/latest/src/wgpu/api/buffer.rs.html Illustrates how to create a buffer with mapped_at_creation flag set to true and write data to it. ```rust let buffer = device.create_buffer(&BufferDescriptor { label: Some("my buffer"), usage: BufferUsages::MAP_READ | BufferUsages::COPY_DST, size: 1024, mapped_at_creation: true, }); let mut mapped_range = buffer.get_mapped_range_mut(); mapped_range.copy_from_slice(&[0u8; 1024]); // You must call `unmap` when you are done writing. // The buffer is not usable by the GPU until it is unmapped. // If you need to write more data later, you must call `map_async` again. buffer.unmap(); ``` -------------------------------- ### split_last example Source: https://docs.rs/wgpu/latest/wgpu/struct.BufferView.html Example of using the split_last method. ```rust let x = &[0, 1, 2]; if let Some((last, elements)) = x.split_last() { assert_eq!(last, &2); assert_eq!(elements, &[0, 1]); } ```