Skip to main content

WgpuRenderer

Struct WgpuRenderer 

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

WGPU-based renderer for GPU-accelerated 2D rendering.

This renderer supports:

  • GPU-accelerated shape rendering (rectangles, rounded rectangles)
  • Gradients (solid, linear, radial)
  • GPU text rendering via retained raster image batches
  • Cross-platform support (Desktop, Web, Android)

Implementations§

Source§

impl WgpuRenderer

Source

pub fn render_with_scene_depth( &mut self, texture: &Texture, view: &TextureView, depth: &TextureView, (width, height): (u32, u32), ) -> Result<(), WgpuRendererError>

Renders like render, with the 3D scenes of the frame drawn against depth and leaving their depth there, for a host that hands the depth on, such as an XR compositor.

depth is a view of a texture of SCENE_DEPTH_FORMAT with width by height pixels and the render attachment usage. The scenes clear it and write the distance of what they draw as 1 - near / z, where z is the depth along the camera’s axis and near is Camera::near: 0 at the near plane, 1 at infinity, and 1 where no scene drew. Each scene pass clears it again, so a frame that draws several scenes leaves the depth of the last one. A scene drawn into an intermediate layer, such as one under a blur, uses depth of the renderer’s own.

A scene with Multisample::Off stores its depth in its own pass. A scene with four samples cannot, because a render pass holds one sample count and wgpu has no depth resolve. Such a scene that covers a page holding only its transparent clear averages its colour straight into the page, then a second pass with one sample draws its opaque surfaces and volumes again with the depth pipelines. Each pixel holds the depth of its centre, so a pixel that an edge covers in part carries the depth of the surface at its centre, or the far plane where none covers the centre. Any other scene of four samples leaves the far plane.

Source§

impl WgpuRenderer

Source

pub fn new(fonts: &[&'static [u8]]) -> Self

Create a new WGPU renderer.

  • fonts – font bytes to load, ordered by priority (first = highest priority). Pass &[] to load no fonts; text will not render until fonts are provided.

Call init_gpu before rendering.

Source

pub fn with_text_fonts(fonts: TextFonts) -> Self

Create a renderer over fonts an app already built.

Source

pub fn with_text_system(text_system: WgpuTextSystem) -> Self

Create a renderer that hands the app the fonts of text_system.

Source

pub fn set_device_lost_handler(&mut self, handler: DeviceLostHandler)

Runs handler when the device of a later init_gpu call is lost, so the host can open another device and hand it over.

Source

pub fn release_gpu(&mut self)

Drops what the renderer holds on its device, for a host whose device is gone: the frees then reach the lost device, as a WebGL context that is lost ignores them, rather than the device that replaces it. Self::init_gpu gives the renderer a device again.

Source

pub fn init_gpu(&mut self, target: GpuTarget)

Initialize GPU resources with a WGPU device and queue.

Replacing a live renderer (Android surface recreation, device loss) bumps the renderer epoch, so a packet built against the previous renderer is cancelled instead of drawn.

Source

pub fn init_gpu_threaded( &mut self, target: GpuTarget, waker: Arc<dyn Fn() + Send + Sync>, clock: Option<Arc<dyn Fn() -> i64 + Send + Sync>>, observer: Option<Box<dyn PresentObserver>>, ) -> Result<(), WgpuRendererError>

init_gpu for the threaded present runtime (Android): the same epoch bump and planner replacement hygiene, but instead of constructing a GpuRenderer here, everything it needs — all owned, all Send — crosses to a spawned present thread that constructs its own (its Rc caches are thread-confined). Frames then flow through publish_frame / drain_present_returns under the depth-one credit protocol instead of render.

  • waker — wakes the producer’s event loop after every returns send (the Android frame waker).
  • clock — producer’s monotonic nanosecond clock, so present-side PresentTimings share the producer telemetry’s clock domain; None leaves timings at zero.
  • observer — runs on the present thread around every present to the surface.
Source

pub fn note_surface_reconfigured(&mut self)

Record that the surface was reconfigured (resize, format change, swapchain recreation): bumps the surface epoch stamped into every subsequent packet, so a packet built against the previous configuration is cancelled by the present stage instead of drawn.

Source

pub fn set_transparent_background(&mut self, transparent: bool)

Clears each frame to nothing instead of the framework’s background, for a window whose surface composites with the desktop behind it. A renderer starts opaque; false puts the background back. Takes effect from the next frame, on either present backend.

Source

pub fn root_scale(&self) -> f32

The scale from logical to device pixels the renderer draws the root with, as last set by Renderer::set_root_scale. It starts at 1.0.

Source

pub fn render( &mut self, texture: &Texture, view: &TextureView, width: u32, height: u32, ) -> Result<(), WgpuRendererError>

Render the scene to a texture view.

Producer first, present second: the frontend collects the frame into a frame_packet::FramePacket (root and dev overlay alike), the GPU renderer consumes it, and the present stage’s returns fold back into the frontend afterwards.

Source

pub fn render_surface_texture( &mut self, frame: &SurfaceTexture, view: &TextureView, width: u32, height: u32, ) -> Result<(), WgpuRendererError>

Renders the frame into a surface’s presentable image frame, through view. When the image carries the composition format and the capture usages, the scene renders into it directly and no output conversion pass runs. When the surface hands the image back with the frame it last presented (wgpu::Surface::keep_presented_images), the frame draws only what changed since that frame. When the surface hands its images out cleared, as a WebGPU canvas does, and the frames change a small part of a window drawn over more than twice, the renderer keeps the frame in a texture of its own, draws only what changed there and copies it into the image; see release_kept_copy.

Source

pub fn present(&self, frame: SurfaceTexture)

Presents a surface image this renderer drew with render_surface_texture, on the queue that recorded it.

Before init_gpu there is no queue, and the image is released without being shown.

Source

pub fn release_kept_copy(&mut self)

Lets go of the texture that keeps the last frame for a surface whose images come cleared (see render_surface_texture), a window of memory. A runtime calls it once its app holds still; the next frame draws whole.

Source

pub fn shows_scene(&mut self, width: u32, height: u32) -> bool

Whether the surface already shows the current scene at width by height device pixels: the frame drawn last into a surface that keeps its presented images, with nothing changed since. A platform asks before it takes the surface’s next image, and when the surface shows the scene it takes no image, draws nothing and presents nothing. Otherwise the frame drawn next starts from the scene this collected.

Source

pub fn capture_frame( &mut self, width: u32, height: u32, ) -> Result<CapturedFrame, WgpuRendererError>

Render the current scene into an RGBA pixel buffer for robot tests.

Uses the renderer’s configured root scale.

Source

pub fn prepare_recorded_pipelines( &mut self, timeout: Duration, stop: &dyn Fn() -> bool, ) -> bool

Builds every pipeline the pipeline cache file records on the background compiler, and returns whether they were all built before timeout, or before stop said to stop. An app runs it after an update, before its next launch, so that launch finds them compiled; the renderer writes the file when it is dropped, and drops the builds not started. It draws nothing, and needs a renderer initialized for synchronous rendering.

Source

pub fn capture_frame_with_scale( &mut self, width: u32, height: u32, root_scale: f32, ) -> Result<CapturedFrame, WgpuRendererError>

Render the current scene into an RGBA pixel buffer with an explicit scale.

width and height are in device pixels and root_scale is the scale from logical to device pixels. Needs a renderer initialized for synchronous rendering.

Source

pub fn has_frame_credit(&self) -> bool

Threaded mode: whether the present thread takes a packet now. Two packets go in flight at most. The Android loop checks this BEFORE shell.update() so backpressure lands before the expensive update/lowering work. Always true on the sync path, which has no slot to fill.

Source

pub fn frame_credit_returned(&self) -> bool

Threaded mode: whether the present thread has handed back a frame that drain_present_returns has not folded back yet, so draining it would free a publish credit. A loop out of credit can work on other things until this turns true. Always false outside threaded mode.

Source

pub fn publish_frame(&mut self, width: u32, height: u32) -> PublishOutcome

Threaded mode: lower the current scene into a packet and hand it to the present runtime. Credit is checked FIRST — a NoCredit return means no packet was built at all (frame_sequence does not advance). Returns NoCredit (with an error log) when the renderer is not in threaded mode.

Source

pub fn drain_present_returns(&mut self) -> usize

Threaded mode: fold every pending RenderReturns back into producer state and free the publish credit. Returns how many were drained. No-op outside threaded mode.

Source

pub fn drain_present_returns_with( &mut self, on_return: &mut dyn FnMut(u64, PresentOutcome, PresentTimings), ) -> usize

drain_present_returns, reporting each drained frame’s id, outcome and present-thread timings — the Android loop feeds its frame telemetry from this.

Source

pub fn present_thread(&mut self) -> Option<PresentThread<'_>>

The thread this renderer hands its frames to, when it presents on one (init_gpu_threaded); None when it draws on the calling thread.

Source

pub fn shutdown_present_runtime(&mut self)

Threaded mode: drain outstanding returns, stop the present thread and join it. The renderer returns to the uninitialized state.

Source

pub fn present_thread_id(&self) -> Option<i32>

The OS id of the thread that presents frames, once that thread has started, on systems whose scheduler hints name threads by one. None when frames present on the calling thread.

Source

pub fn last_published_frame_id(&self) -> u64

The producer’s monotone packet sequence: the frame_id stamped on the most recently lowered packet. After a Published outcome this is the published frame’s id (the Android loop keys its telemetry on it); it also proves a NoCredit publish never lowered a frame.

Source

pub fn last_frame_stats(&self) -> Option<RenderStatsSnapshot>

The counters of the most recent frame the renderer drew, or None before it drew one.

Source

pub fn first_screen_recorded(&self) -> bool

Whether the pipeline cache file held an earlier launch’s first screen, whose pipelines build ahead of this renderer’s first frame; false for a first launch or emptied caches, whose first frame builds its pipelines, and for a renderer that does not draw on the calling thread.

Source

pub fn first_screen_pipelines(&self) -> Option<Vec<u8>>

The pipelines this renderer’s first screen drew with, encoded for Self::build_first_screen_pipelines in a later launch. None until the first screen ends, two seconds after the first frame and later by every wait for a pipeline, and for a renderer that does not draw on the calling thread.

Source

pub fn build_first_screen_pipelines( &mut self, records: &[u8], viewport: (u32, u32), )

Builds now the pipelines one set in records names: sets Self::first_screen_pipelines wrote, one after another, each at the size its first frame drew. A web page calls this as its renderer starts, so the browser compiles them while the page composes its first screen. Of the sets drawn on this renderer’s backend by a build with the same layout of pipeline keys, the one drawn nearest to viewport pixels builds: a phone’s screen and a desktop window’s draw with different pipelines, and a frame that waits for pipelines it does not draw with comes later. A renderer that does not draw on the calling thread builds nothing.

Source

pub fn gpu_pass_timings(&self) -> GpuPassTimingReport

GPU milliseconds by pass label, aggregated since the last [GPU-PASS] print. Empty unless CRANPOSE_GPU_PASS_TIMING armed pass timing on a device with wgpu::Features::TIMESTAMP_QUERY.

Source

pub fn debug_cpu_allocation_stats(&self) -> DebugCpuAllocationStats

The sizes and capacities of the renderer’s CPU-side scene data, scratch buffers and caches, for memory diagnostics. The members of a renderer that does not draw on the calling thread cover the scene only.

Source

pub fn compile_pipelines_in_background(&mut self)

Tells the renderer that the browser compiles the pipelines it creates from now on in the background (wgpu::Device::compile_pipelines_in_background). On WebGPU the first screen draws its shapes with a general pipeline, whose one compile stands in for the specialized ones; those it builds once this is called, and draws switch to each as it lands. A renderer whose target is no browser’s builds nothing more for it.

Source

pub fn try_device(&self) -> Option<&Device>

Return the WGPU device when GPU resources are initialized. Sync backend only (desktop/web reconfigure paths); the threaded runtime owns its device on the present thread.

Trait Implementations§

Source§

impl Default for WgpuRenderer

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Renderer for WgpuRenderer

Source§

type Scene = Scene

The scene type that holds the records and the hit targets of this renderer.
Source§

type Error = WgpuRendererError

Error returned when the scene cannot be rebuilt or updated.
Source§

fn attach_app_context_services(&mut self, app_context: &AppContext)

Installs renderer-provided app services into the target AppContext. Read more
Source§

fn apply_installed_fonts(&mut self, app_context: &AppContext)

Takes in the fonts installed since the renderer last looked (see installed_fonts::install_font_file). A renderer that installed the app’s text measurer installs one with the new faces, so text lays out again with them. Read more
Source§

fn trim(&mut self)

Gives back the room the renderer’s storage holds past what it draws, beside its scene’s. AppShell calls it at rest, when no frame waits.
Source§

fn set_root_scale(&mut self, scale: f32)

Sets how many device pixels the renderer draws for one logical unit. Read more
Source§

fn scene(&self) -> &Self::Scene

The scene that holds the records and the hit targets.
Source§

fn scene_mut(&mut self) -> &mut Self::Scene

Mutable access to the scene.
Source§

fn rebuild_scene_from_applier( &mut self, applier: &mut MemoryApplier, root: NodeId, _viewport: Size, ) -> Result<(), Self::Error>

Rebuilds the scene by traversing the LayoutNode tree directly via Applier. Read more
Source§

fn update_scene_from_applier( &mut self, applier: &mut MemoryApplier, root: NodeId, _viewport: Size, updates: SceneUpdates<'_>, ) -> Result<(), Self::Error>

Updates the scene for the nodes in updates, and the hit targets when the update changed one or the geometry above one. The default implementation rebuilds the whole scene.
Source§

fn draw_dev_overlay(&mut self, overlay: &PreparedTextLayout, viewport: Size)

Draw a development overlay (e.g., FPS counter) on top of the scene. Read more
Source§

fn note_held_still(&mut self)

Tells the renderer that its app held still between the last frame and the next one: the shell asked the platform for no frame and no update. A renderer that compares frames to draw only what changed counts the frames on either side of the pause apart. Read more
Source§

fn note_pointer_held(&mut self)

Tells the renderer that a pointer is held on the app’s controls for the coming frame: the user may move it at any moment, so the frame is not one to spend on work that holds the frames after it back, such as a WebGL program link. Read more
Source§

fn set_inspector_overlay(&mut self, overlay: Option<OverlayLayer>)

Replaces the developer inspector layer drawn over the application scene. Read more
Source§

fn set_overlay_tree(&mut self, overlay: Option<LayerNode>)

Replaces the overlay with the layer tree overlay describes, as a renderer’s tests describe an overlay by hand. Read more
Source§

fn needs_frame_warmup(&self) -> bool

Returns whether renderer-side cache materialization needs a visible follow-up frame.
Source§

fn awaits_pipelines(&self) -> bool

Returns whether the last frame drew a placeholder for an effect whose pipelines are still compiling, so its picture is not final yet; the renderer asks for the frame that replaces it once they land.
Source§

fn update_visual_scene_from_applier( &mut self, applier: &mut MemoryApplier, root: NodeId, viewport: Size, updates: &[(NodeId, NodeUpdate)], ) -> Result<(), Self::Error>

Updates the scene when only what is drawn changed: nothing was composed or laid out. The default implementation calls update_scene_from_applier.
Source§

fn build_while_idle(&mut self) -> bool

Runs one step of the pipeline builds that wait for a frame, where frames run them (a WebGL page links one program at a frame’s end), while the app draws none: a page that stands still still builds what its next touch draws. Returns whether builds still wait. 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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

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

Source§

impl<T> Downcast<T> for T

Source§

fn downcast(&self) -> &T

Source§

impl<T> ErasedDestructor for T
where T: 'static,

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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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<T> Upcast<T> for T

Source§

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