Skip to main content

GraphicsDevice

Struct GraphicsDevice 

Source
pub struct GraphicsDevice { /* private fields */ }
Expand description

A graphics service bound to one renderer’s device and upload queue.

Implementations§

Source§

impl GraphicsDevice

Source

pub fn frame_buffer(&self, usage: BufferUsages, bytes: &[u8]) -> FrameBuffer

Stages uniform or storage bytes in a reusable frame buffer. Each call owns a separate aligned range; pages are uploaded once before submission.

Source

pub fn cached_bind_group( &self, descriptor: &BindGroupDescriptor<'_>, ) -> BindGroup

Reuses bindings for buffer ranges, textures and samplers across frames. Array bindings are created directly rather than cached.

Source§

impl GraphicsDevice

Source

pub fn scratch_texture( &self, descriptor: ScratchTextureDescriptor, ) -> ScratchTexture

Leases a pooled texture for work recorded in the current frame.

Source§

impl GraphicsDevice

Source

pub fn encode_before_frame(&self, record: impl FnOnce(&mut CommandEncoder))

Records GPU work that runs before the current frame’s passes, in the same submission.

Use it to prepare textures, such as atlas entries, that the frame samples. Queue writes made during the frame complete before this work.

Source

pub fn device(&self) -> &Device

Returns the device used by this renderer.

Source

pub fn queue(&self) -> &Queue

Returns the upload queue used by this renderer.

Source

pub fn upload_budget(&self) -> u64

Texture bytes that can still be uploaded in the current frame.

Spread larger uploads over several frames, and call Self::defer_upload while some remain.

Source

pub fn defer_upload(&self)

Requests another frame to continue uploads deferred by the budget.

Source

pub fn diagnostics(&self) -> GraphicsWorkDiagnostics

Captures actual operations performed through this graphics service.

Source

pub fn create_buffer( &self, group: &'static str, descriptor: &BufferDescriptor<'_>, ) -> TrackedBuffer

Creates an owned buffer in a pipeline resource group.

Source

pub fn create_buffer_init( &self, group: &'static str, descriptor: &BufferInitDescriptor<'_>, ) -> TrackedBuffer

Creates a buffer containing its initial data.

Source

pub fn write_buffer(&self, buffer: &TrackedBuffer, offset: u64, data: &[u8])

Uploads bytes to a buffer owned by this renderer.

Source

pub fn create_texture( &self, group: &'static str, descriptor: &TextureDescriptor<'_>, ) -> Texture

Creates a texture in a pipeline resource group.

Source

pub fn write_texture( &self, group: &'static str, destination: TexelCopyTextureInfo<'_>, data: &[u8], layout: TexelCopyBufferLayout, size: Extent3d, )

Uploads texture bytes through this renderer’s queue.

Methods from Deref<Target = Device>§

pub fn poll( &self, poll_type: PollType<SubmissionIndex>, ) -> Result<PollStatus, PollError>

Check for resource cleanups and mapping callbacks. Will block if [PollType::Wait] is passed.

Return true if the queue is empty, or false if there are more queue submissions still in flight. (Note that, unless access to the [Queue] is coordinated somehow, this information could be out of date by the time the caller receives it. Queues can be shared between threads, so other threads could submit new work at any time.)

When running on WebGPU, this is a no-op. Devices are automatically polled.

pub fn features(&self) -> Features

The [features][Features] which can be used on this device.

This will be equal to the [required_features][DeviceDescriptor::required_features] specified when creating the device. No additional features can be used, even if the underlying adapter can support them.

pub fn limits(&self) -> Limits

The limits which can be used on this device.

This will be equal to the [required_limits][DeviceDescriptor::required_limits] specified when creating the device. No better limits can be used, even if the underlying adapter can support them.

pub fn adapter_info(&self) -> AdapterInfo

Get info about the adapter that this device was created from.

pub fn create_shader_module( &self, desc: ShaderModuleDescriptor<'_>, ) -> ShaderModule

Creates a shader module.

This function may consume a lot of stack space. Compiler-enforced limits for parsing recursion exist; if shader compilation runs into them, it will return an error gracefully. However, on some build profiles and platforms, the default stack size for a thread may be exceeded before this limit is reached during parsing. Callers should ensure that there is enough stack space for this, particularly if calls to this method are exposed to user input.

pub unsafe fn create_shader_module_unchecked( &self, desc: ShaderModuleDescriptor<'_>, ) -> ShaderModule

👎Deprecated since 24.0.0:

Use Device::create_shader_module_trusted(desc, wgpu::ShaderRuntimeChecks::unchecked()) instead.

Deprecated: Use create_shader_module_trusted instead.

§Safety

See create_shader_module_trusted.

pub unsafe fn create_shader_module_trusted( &self, desc: ShaderModuleDescriptor<'_>, runtime_checks: ShaderRuntimeChecks, ) -> ShaderModule

Creates a shader module with flags to dictate runtime checks.

When running on WebGPU, this will merely call create_shader_module.

§Safety

In contrast with create_shader_module this function creates a shader module with user-customizable runtime checks which allows shaders to perform operations which can lead to undefined behavior like indexing out of bounds, thus it’s the caller responsibility to pass a shader which doesn’t perform any of this operations.

See the documentation for [ShaderRuntimeChecks] for more information about specific checks.

pub unsafe fn create_shader_module_passthrough( &self, desc: CreateShaderModuleDescriptorPassthrough<'_, Option<&str>>, ) -> ShaderModule

Creates a shader module which will bypass wgpu’s shader tooling and validation and be used directly by the backend.

§Safety

This function passes data to the backend as-is and can potentially result in a driver crash or bogus behaviour. No attempt is made to ensure that data is valid.

pub fn create_command_encoder( &self, desc: &CommandEncoderDescriptor<Option<&str>>, ) -> CommandEncoder

Creates an empty [CommandEncoder].

pub fn create_render_bundle_encoder<'a>( &self, desc: &RenderBundleEncoderDescriptor<'_>, ) -> RenderBundleEncoder<'a>

Creates an empty [RenderBundleEncoder].

pub fn create_bind_group(&self, desc: &BindGroupDescriptor<'_>) -> BindGroup

Creates a new [BindGroup].

pub fn create_bind_group_layout( &self, desc: &BindGroupLayoutDescriptor<'_>, ) -> BindGroupLayout

Creates a [BindGroupLayout].

pub fn create_pipeline_layout( &self, desc: &PipelineLayoutDescriptor<'_>, ) -> PipelineLayout

Creates a [PipelineLayout].

pub fn create_render_pipeline( &self, desc: &RenderPipelineDescriptor<'_>, ) -> RenderPipeline

Creates a [RenderPipeline].

pub fn create_mesh_pipeline( &self, desc: &MeshPipelineDescriptor<'_>, ) -> RenderPipeline

Creates a mesh shader based [RenderPipeline].

pub fn create_compute_pipeline( &self, desc: &ComputePipelineDescriptor<'_>, ) -> ComputePipeline

Creates a [ComputePipeline].

pub fn create_buffer(&self, desc: &BufferDescriptor<Option<&str>>) -> Buffer

Creates a [Buffer].

pub fn create_texture( &self, desc: &TextureDescriptor<Option<&str>, &[TextureFormat]>, ) -> Texture

Creates a new [Texture].

desc specifies the general format of the texture.

pub unsafe fn create_texture_from_hal<A>( &self, hal_texture: <A as Api>::Texture, desc: &TextureDescriptor<Option<&str>, &[TextureFormat]>, initial_state: TextureUses, ) -> Texture
where A: Api,

Creates a [Texture] from a wgpu-hal Texture.

§Types

The type of A::Texture depends on the backend:

  • [hal::api::Vulkan] uses [hal::vulkan::Texture]
  • hal::api::Metal uses hal::metal::Texture
  • hal::api::Dx12 uses hal::dx12::Texture
  • [hal::api::Gles] uses [hal::gles::Texture]

On [Backend::BrowserWebGpu], use Device::create_texture_from_webgpu_handle() instead.

§initial_state

If the resource has already been initialized, initial_state should be set to the [wgt::TextureUses] state of the wrapped resource. It will be used as the source state (oldLayout / StateBefore) of the first barrier emitted on the texture.

If the resource has not been initialized (or if the existing contents may be discarded), initial_state may be set to TextureUses::UNINITIALIZED.

§Safety
  • hal_texture must be created from this device internal handle
  • hal_texture must be created respecting desc
  • hal_texture must be initialized
  • initial_state, if it is not TextureUses::UNINITIALIZED, must match the actual driver-side layout/state of the wrapped resource at the moment of wrap.

pub fn create_external_texture( &self, desc: &ExternalTextureDescriptor<Option<&str>>, planes: &[&TextureView], ) -> ExternalTexture

Creates a new [ExternalTexture].

pub unsafe fn create_buffer_from_hal<A>( &self, hal_buffer: <A as Api>::Buffer, desc: &BufferDescriptor<Option<&str>>, ) -> Buffer
where A: Api,

Creates a [Buffer] from a wgpu-hal Buffer.

§Types

The type of A::Buffer depends on the backend:

  • [hal::api::Vulkan] uses [hal::vulkan::Buffer]
  • hal::api::Metal uses hal::metal::Buffer
  • hal::api::Dx12 uses hal::dx12::Buffer
  • [hal::api::Gles] uses [hal::gles::Buffer]
§Safety
  • hal_buffer must be created from this device internal handle
  • hal_buffer must be created respecting desc
  • hal_buffer must be initialized
  • hal_buffer must not have zero size

pub fn create_sampler(&self, desc: &SamplerDescriptor<Option<&str>>) -> Sampler

Creates a new [Sampler].

desc specifies the behavior of the sampler.

pub fn create_query_set( &self, desc: &QuerySetDescriptor<Option<&str>>, ) -> QuerySet

Creates a new [QuerySet].

pub fn on_uncaptured_error( &self, handler: Arc<dyn UncapturedErrorHandler<Output = ()>>, )

Set a callback which will be called for all errors that are not handled in error scopes.

pub fn push_error_scope(&self, filter: ErrorFilter) -> ErrorScopeGuard

Push an error scope on this device’s thread-local error scope stack. All operations on this device, or on resources created from this device, will have their errors captured by this scope until the scope is popped.

Scopes must be popped in reverse order to their creation. If a guard is dropped without being pop()ped, the scope will be popped, and the captured errors will be dropped.

Multiple error scopes may be active at one time, forming a stack. Each error will be reported to the inner-most scope that matches its filter.

With the std feature enabled, this stack is thread-local. Without, this is global to all threads.

let error_scope = device.push_error_scope(wgpu::ErrorFilter::Validation);

// ...
// do work that may produce validation errors
// ...

// pop the error scope and get a future for the result
let error_future = error_scope.pop();

// await the future to get the error, if any
let error = error_future.await;

pub unsafe fn start_graphics_debugger_capture(&self)

Starts a capture in the attached graphics debugger.

This behaves differently depending on which graphics debugger is attached:

§Safety
  • There should not be any other captures currently active.
  • All other safety rules are defined by the graphics debugger, see the documentation for the specific debugger.
  • In general, graphics debuggers can easily cause crashes, so this isn’t ever guaranteed to be sound.
§Tips
  • Debuggers need to capture both the recording of the commands and the submission of the commands to the GPU. Try to wrap all of your gpu work in a capture.
  • If you encounter issues, try waiting for the GPU to finish all work before stopping the capture.

pub unsafe fn stop_graphics_debugger_capture(&self)

Stops the current capture in the attached graphics debugger.

This behaves differently depending on which graphics debugger is attached:

§Safety
  • There should be a capture currently active.
  • All other safety rules are defined by the graphics debugger, see the documentation for the specific debugger.
  • In general, graphics debuggers can easily cause crashes, so this isn’t ever guaranteed to be sound.
§Tips
  • If you encounter issues, try to submit all work to the GPU, and waiting for that work to finish before stopping the capture.

pub fn get_internal_counters(&self) -> InternalCounters

Query internal counters from the native backend for debugging purposes.

Some backends may not set all counters, or may not set any counter at all. The counters cargo feature must be enabled for any counter to be set.

If a counter is not set, its contains its default value (zero).

pub fn generate_allocator_report(&self) -> Option<AllocatorReport>

Generate an GPU memory allocation report if the underlying backend supports it.

Backends that do not support producing these reports return None. A backend may Support it and still return None if it is not using performing sub-allocation, for example as a workaround for driver issues.

pub unsafe fn as_hal<A>( &self, ) -> Option<impl Deref<Target = <A as Api>::Device> + WasmNotSendSync>
where A: Api,

Get the [wgpu_hal] device from this Device.

Find the Api struct corresponding to the active backend in [wgpu_hal::api], and pass that struct to the to the A type parameter.

Returns a guard that dereferences to the type of the hal backend which implements A::Device.

§Types

The returned type depends on the backend:

  • [hal::api::Vulkan] uses [hal::vulkan::Device]
  • hal::api::Metal uses hal::metal::Device
  • hal::api::Dx12 uses hal::dx12::Device
  • [hal::api::Gles] uses [hal::gles::Device]
§Errors

This method will return None if:

  • The device is not from the backend specified by A.
  • The device is from the webgpu or custom backend.

On the webgpu backend, use as_webgpu instead.

§Safety
  • The returned resource must not be destroyed unless the guard is the last reference to it and it is not in use by the GPU. The guard and handle may be dropped at any time however.
  • All the safety requirements of wgpu-hal must be upheld.

pub fn destroy(&self)

Destroy this device.

pub fn set_device_lost_callback( &self, callback: impl Fn(DeviceLostReason, String) + Send + 'static, )

Set a DeviceLostCallback on this device.

pub unsafe fn create_pipeline_cache( &self, desc: &PipelineCacheDescriptor<'_>, ) -> PipelineCache

Create a [PipelineCache] with initial data

This can be passed to [Device::create_compute_pipeline] and [Device::create_render_pipeline] to either accelerate these or add the cache results from those.

§Safety

If the data field of desc is set, it must have previously been returned from a call to [PipelineCache::get_data]1. This data will only be used if it came from an adapter with the same [util::pipeline_cache_key]. This is compatible across wgpu versions, as any data format change will be accounted for.

It is not supported to bring caches from previous direct uses of backend APIs into this method.

§Errors

Returns an error value if:

  • the PIPELINE_CACHE feature is not enabled
  • this device is invalid; or
  • the device is out of memory

This method also returns an error value if:

  • The fallback field on desc is false; and
  • the data provided would not be used2

If an error value is used in subsequent calls, default caching will be used.


  1. We do recognise that saving this data to disk means this condition is impossible to fully prove. Consider the risks for your own application in this case. ↩

  2. This data may be not used if: the data was produced by a prior version of wgpu; or was created for an incompatible adapter, or there was a GPU driver update. In some cases, the data might not be used and a real value is returned, this is left to the discretion of GPU drivers. ↩

pub fn create_blas( &self, desc: &CreateBlasDescriptor<Option<&str>>, sizes: BlasGeometrySizeDescriptors, ) -> Blas

Create a bottom level acceleration structure, used inside a top level acceleration structure for ray tracing.

  • desc: The descriptor of the acceleration structure.
  • sizes: Size descriptor limiting what can be built into the acceleration structure.
§Validation

If any of the following is not satisfied a validation error is generated

The device must have Features::EXPERIMENTAL_RAY_QUERY enabled. if sizes is [BlasGeometrySizeDescriptors::Triangles] then the following must be satisfied

  • For every geometry descriptor (for the purposes this is called geo_desc) of sizes.descriptors the following must be satisfied:
    • geo_desc.vertex_format must be within allowed formats (allowed formats for a given feature set may be queried with Features::allowed_vertex_formats_for_blas).
    • Both or neither of geo_desc.index_format and geo_desc.index_count must be provided.

pub fn create_tlas(&self, desc: &CreateTlasDescriptor<Option<&str>>) -> Tlas

Create a top level acceleration structure, used for ray tracing.

  • desc: The descriptor of the acceleration structure.
§Validation

If any of the following is not satisfied a validation error is generated

The device must have Features::EXPERIMENTAL_RAY_QUERY enabled.

Trait Implementations§

Source§

impl Clone for GraphicsDevice

Source§

fn clone(&self) -> GraphicsDevice

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for GraphicsDevice

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for GraphicsDevice

Source§

type Target = Device

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
§

impl<T> Downcast for T
where T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
§

impl<T> Downcast for T
where T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
§

impl<T> Downcast<T> for T

§

fn downcast(&self) -> &T

§

impl<T> DowncastSend for T
where T: Any + Send,

§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync> ⓘ

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

§

fn into_any_sync(self: Box<T>) -> Box<dyn Any + Send + Sync>

Converts Box<Trait> (where Trait: DowncastSync) to Box<dyn Any + Send + Sync>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync> ⓘ

Converts Arc<Trait> (where Trait: DowncastSync) to Arc<Any>, which can then be downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> SendSync for T
where T: Send + Sync + 'static,

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> Upcast<T> for T

§

fn upcast(&self) -> Option<&T>

§

impl<T> WasmNotSend for T
where T: Send,

§

impl<T> WasmNotSendSync for T
where T: WasmNotSend + WasmNotSync,

§

impl<T> WasmNotSync for T
where T: Sync,

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more