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.
impl WebGpuRenderer
Implements async initialization and GPU resource creation for WebGpuRenderer.
Sourcepub fn is_available() -> bool
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-truewhennavigator.gpuis a non-null, non-undefined object;falseotherwise (including the “nowindow” runtime case, whichweb_sys::window()returnsNonefor).
Sourcepub async fn probe() -> bool
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-trueonly when bothnavigator.gpuis present andrequestAdapter()resolves to a non-null adapter within the timeout window.falsecovers every other case (nowindow, missingnavigator.gpu, reflect exception, adapter promise rejected or timed out, adapter resolved tonull/undefined).
Sourcepub async fn init(
config: &RenderConfig,
) -> Result<WebGpuRenderer, WebGpuInitError>
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.
Sourcepub fn resize(&mut self, physical_width: u32, physical_height: u32) -> bool
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-trueon success,falseif the swap chain or canvas handles were missing orconfigurefailed.
Sourcepub fn sync_to_current_canvas(&mut self) -> bool
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-trueif the resize succeeded,falseif the canvas was zero-sized (nothing to render to), detached (CSS layout box collapses to 0), or the underlying resize rejected.
Sourcepub fn create_render_pipeline<S>(&self, shader_code: S) -> JsValue
pub fn create_render_pipeline<S>(&self, shader_code: S) -> JsValue
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.
Sourcepub fn render_frame(
&mut self,
pipeline: &JsValue,
clear_color: (f64, f64, f64, f64),
vertex_count: u32,
)
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.
Sourcepub fn dispose(&self)
pub fn dispose(&self)
Releases all GPU resources held by this renderer.
The teardown order matters per the WebGPU spec:
GpuCanvasContext.unconfigure()- releases the swap chain so the DOM canvas can be GCed.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
impl WebGpuRenderer
pub fn get_device(&self) -> &JsValue
pub fn get_mut_device(&mut self) -> &mut JsValue
pub fn set_device(&mut self, val: JsValue) -> &mut Self
pub fn get_queue(&self) -> &JsValue
pub fn get_mut_queue(&mut self) -> &mut JsValue
pub fn set_queue(&mut self, val: JsValue) -> &mut Self
pub fn get_context(&self) -> &JsValue
pub fn get_mut_context(&mut self) -> &mut JsValue
pub fn set_context(&mut self, val: JsValue) -> &mut Self
pub fn get_canvas(&self) -> &HtmlCanvasElement
pub fn get_mut_canvas(&mut self) -> &mut HtmlCanvasElement
pub fn set_canvas(&mut self, val: HtmlCanvasElement) -> &mut Self
pub fn get_format(&self) -> String
pub fn get_mut_format(&mut self) -> &mut String
pub fn set_format(&mut self, val: String) -> &mut Self
pub fn get_width(&self) -> u32
pub fn get_mut_width(&mut self) -> &mut u32
pub fn set_width(&mut self, val: u32) -> &mut Self
pub fn get_height(&self) -> u32
pub fn get_mut_height(&mut self) -> &mut u32
pub fn set_height(&mut self, val: u32) -> &mut Self
pub fn get_antialias(&self) -> bool
pub fn get_mut_antialias(&mut self) -> &mut bool
pub fn set_antialias(&mut self, val: bool) -> &mut Self
pub fn get_multisample_texture(&self) -> Option<JsValue>
pub fn try_get_multisample_texture(&self) -> Option<JsValue>
pub fn get_mut_multisample_texture(&mut self) -> &mut Option<JsValue>
pub fn set_multisample_texture(&mut self, val: Option<JsValue>) -> &mut Self
pub fn get_multisample_view(&self) -> Option<JsValue>
pub fn try_get_multisample_view(&self) -> Option<JsValue>
pub fn get_mut_multisample_view(&mut self) -> &mut Option<JsValue>
pub fn set_multisample_view(&mut self, val: Option<JsValue>) -> &mut Self
Trait Implementations§
Source§impl Clone for WebGpuRenderer
impl Clone for WebGpuRenderer
Source§fn clone(&self) -> WebGpuRenderer
fn clone(&self) -> WebGpuRenderer
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more