Skip to main content

WebGpuRenderer

Struct WebGpuRenderer 

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

A WebGPU rendering backend wrapping the GPU device, queue, and canvas context for GPU-accelerated rendering on the web.

Created asynchronously via WebGpuRenderer::init because adapter and device acquisition returns JavaScript Promises that must be awaited. Once initialized, the renderer provides methods to create GPU resources (buffers, shader modules, command encoders) and execute render passes.

WebGPU types are stored as JsValue to avoid feature-gated import issues with web_sys. Method calls are performed via Reflect and JsCast.

Implementations§

Source§

impl WebGpuRenderer

Implements async initialization and GPU resource creation for WebGpuRenderer.

Source

pub fn is_available() -> bool

Returns true if navigator.gpu is exposed on the current origin.

This is the synchronous half of the canonical WebGPU capability probe used by Three.js (examples/jsm/capabilities/WebGPU.js): it only checks that the browser surfaces the GPU interface at all. It does not request an adapter — a present navigator.gpu does not guarantee that a usable GPU adapter is reachable (Linux software-rendered sessions, headless browsers, GPU-blacklisted devices and sandboxed iframes all expose navigator.gpu while requestAdapter() resolves to null or hangs forever).

Use this as the cheapest pre-flight check before showing a “needs HTTPS or localhost” prompt. For a definitive answer use Self::probe which also awaits requestAdapter().

§Returns
  • bool - true when navigator.gpu is a non-null, non-undefined object; false otherwise (including the “no window” runtime case, which web_sys::window() returns None for).
Source

pub async fn probe() -> bool

Probes whether a WebGPU adapter can actually be acquired.

Mirrors Three.js’ canonical capability probe exactly:

isAvailable = (navigator.gpu !== undefined)
if (isAvailable) {
    isAvailable = Boolean(await navigator.gpu.requestAdapter())
}

Wraps the adapter request in the same Promise.race timeout used by Self::init so that browsers which leave the adapter promise permanently pending (headless, sandboxed, device-lost) do not stall the UI forever. The timeout itself uses [INIT_PROMISE_TIMEOUT_MILLIS]; on timeout, probe returns false rather than an error so callers can treat it the same as “no adapter”.

§Returns
  • bool - true only when both navigator.gpu is present and requestAdapter() resolves to a non-null adapter within the timeout window. false covers every other case (no window, missing navigator.gpu, reflect exception, adapter promise rejected or timed out, adapter resolved to null/undefined).
Source

pub async fn init( config: &RenderConfig, ) -> Result<WebGpuRenderer, WebGpuInitError>

Asynchronously initializes a WebGPU renderer from the given render configuration.

Requests a GPU adapter and device, obtains the WebGPU canvas context, and configures it with the preferred texture format. Returns Err if WebGPU is not supported, the adapter/device request fails, the canvas element is not found, or the adapter/device request hangs beyond INIT_PROMISE_TIMEOUT_MILLIS (a defensive timeout for browser GPU states that leave the WebGPU promises permanently pending).

The engine no longer logs diagnostic output internally; instead each failure mode is returned as a distinct WebGpuInitError variant so the caller can decide how to surface it (typically via Console::error or by falling back to the Canvas 2D backend).

§Arguments
  • &RenderConfig - The rendering configuration.
§Returns
  • Result<WebGpuRenderer, WebGpuInitError> - The initialized renderer, or a typed error describing the specific failure.
Source

pub fn resize(&mut self, physical_width: u32, physical_height: u32) -> bool

Resizes the canvas backing store and reconfigures the swap chain.

WebGPU’s GpuCanvasContext.configure is sticky: it sets the texture format and device once, but the swap chain tracks the canvas’s width/height attributes. When the CSS layout size changes (a window resize, a panel toggle, a DPR change) the canvas keeps its old physical dimensions unless we explicitly update width/height and call configure again. Without this, subsequent getCurrentTexture() calls return a texture that no longer matches the visible region and the frame either stretches or freezes.

Re-configureing with the same device + format is the spec-defined way to swap in a fresh swap chain bound to the new backing-store size.

§Arguments
  • u32 - The new physical pixel width (already multiplied by DPR).
  • u32 - The new physical pixel height.
§Returns
  • bool - true on success, false if the swap chain or canvas handles were missing or configure failed.
Source

pub fn sync_to_current_canvas(&mut self) -> bool

Resizes the canvas backing store to match the canvas element’s current CSS-rendered size in physical pixels (DPR applied).

This is the right entry point when the render loop does not know the desired logical size ahead of time and wants to follow the element’s actual layout box. It is also useful as a defensive recovery when the canvas was created while hidden (zero-sized parent) and is later shown at its real size.

Reads client_width / client_height from the canvas element, multiplies by detect_dpr(), and forwards to Self::resize.

§Returns
  • bool - true if the resize succeeded, false if the canvas was zero-sized (nothing to render to), detached (CSS layout box collapses to 0), or the underlying resize rejected.
Source

pub fn create_render_pipeline<S>(&self, shader_code: S) -> JsValue
where S: AsRef<str>,

Creates a simple render pipeline from a single WGSL shader source.

The shader must contain @vertex fn vs_main(...) and @fragment fn fs_main(...) entry points. No vertex buffers are used; vertex positions should be derived from @builtin(vertex_index) in the shader. The pipeline uses auto-layout (layout: null), which works when the shader has no bind groups.

§Arguments
  • S: AsRef<str> - The WGSL shader source code.
§Returns
  • JsValue - The created render pipeline as a JavaScript value.
Source

pub fn render_frame( &mut self, pipeline: &JsValue, clear_color: (f64, f64, f64, f64), vertex_count: u32, )

Renders a complete frame with a pipeline and animated clear color.

This is a convenience method that creates a command encoder, begins a render pass with the given clear color, sets the pipeline, draws the specified number of vertices, ends the pass, finishes the encoder, and submits the command buffer.

§Arguments
  • &JsValue - The render pipeline to use.
  • (f64, f64, f64, f64) - The clear color as (r, g, b, a) in 0.0–1.0 range.
  • u32 - The number of vertices to draw.
Source

pub fn dispose(&self)

Releases all GPU resources held by this renderer.

The teardown order matters per the WebGPU spec:

  1. GpuCanvasContext.unconfigure() - releases the swap chain so the DOM canvas can be GCed.
  2. GpuDevice.destroy() - releases all child resources (buffers, textures, pipelines) and the device itself.

Callers should run this from a use_cleanup callback whenever the host component is being torn down (e.g. on a match arm switch). Without it the previous GPU device lingers until GC, and a fresh init() may either reuse the dead device (silent black canvas) or fail to acquire a new one until the old device is collected.

Reflect::get failures and JS exceptions are swallowed - this is a best-effort cleanup path, and the engine must not panic during teardown.

Source§

impl WebGpuRenderer

Source

pub fn get_device(&self) -> &JsValue

Source

pub fn get_mut_device(&mut self) -> &mut JsValue

Source

pub fn set_device(&mut self, val: JsValue) -> &mut Self

Source

pub fn get_queue(&self) -> &JsValue

Source

pub fn get_mut_queue(&mut self) -> &mut JsValue

Source

pub fn set_queue(&mut self, val: JsValue) -> &mut Self

Source

pub fn get_context(&self) -> &JsValue

Source

pub fn get_mut_context(&mut self) -> &mut JsValue

Source

pub fn set_context(&mut self, val: JsValue) -> &mut Self

Source

pub fn get_canvas(&self) -> &HtmlCanvasElement

Source

pub fn get_mut_canvas(&mut self) -> &mut HtmlCanvasElement

Source

pub fn set_canvas(&mut self, val: HtmlCanvasElement) -> &mut Self

Source

pub fn get_format(&self) -> String

Source

pub fn get_mut_format(&mut self) -> &mut String

Source

pub fn set_format(&mut self, val: String) -> &mut Self

Source

pub fn get_width(&self) -> u32

Source

pub fn get_mut_width(&mut self) -> &mut u32

Source

pub fn set_width(&mut self, val: u32) -> &mut Self

Source

pub fn get_height(&self) -> u32

Source

pub fn get_mut_height(&mut self) -> &mut u32

Source

pub fn set_height(&mut self, val: u32) -> &mut Self

Source

pub fn get_antialias(&self) -> bool

Source

pub fn get_mut_antialias(&mut self) -> &mut bool

Source

pub fn set_antialias(&mut self, val: bool) -> &mut Self

Source

pub fn get_multisample_texture(&self) -> Option<JsValue>

Source

pub fn try_get_multisample_texture(&self) -> Option<JsValue>

Source

pub fn get_mut_multisample_texture(&mut self) -> &mut Option<JsValue>

Source

pub fn set_multisample_texture(&mut self, val: Option<JsValue>) -> &mut Self

Source

pub fn get_multisample_view(&self) -> Option<JsValue>

Source

pub fn try_get_multisample_view(&self) -> Option<JsValue>

Source

pub fn get_mut_multisample_view(&mut self) -> &mut Option<JsValue>

Source

pub fn set_multisample_view(&mut self, val: Option<JsValue>) -> &mut Self

Trait Implementations§

Source§

impl Clone for WebGpuRenderer

Source§

fn clone(&self) -> WebGpuRenderer

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

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
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
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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.

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.
Source§

impl<S, T> Upcast<T> for S
where T: UpcastFrom<S> + ?Sized, S: ?Sized,

Source§

fn upcast(&self) -> &T
where Self: ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider ref type within the Wasm bindgen generics type system. Read more
Source§

fn upcast_into(self) -> T
where Self: Sized + ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider type within the Wasm bindgen generics type system. Read more