Skip to main content

cranpose_render_wgpu/
lib.rs

1#![deny(missing_docs)]
2#![doc = include_str!("../README.md")]
3
4pub use offscreen::{COMPOSITION_BYTES_PER_PIXEL, offscreen_render_target_for_tests};
5pub use render::presentable_root_usages;
6mod ablation;
7mod arc_trig_fill;
8mod capture_hash;
9mod captured_frame;
10mod collect;
11mod cpu_allocation_stats;
12mod depth_gate;
13mod device_error_sentry;
14mod draw_pass;
15mod effect_renderer;
16mod fast_cores;
17mod frame;
18mod geometry;
19mod idle_pool;
20mod layer_cache;
21mod renderer_impl;
22pub use fast_cores::pin_current_thread_to_fast_cores;
23#[cfg(all(target_arch = "wasm32", feature = "gl-templates"))]
24mod first_screen_glsl;
25mod fixed_pipeline;
26mod frame_graph;
27mod frame_packet;
28mod frontend;
29mod gpu_target;
30mod host_gl;
31#[cfg(all(target_arch = "wasm32", feature = "gl-templates"))]
32pub use first_screen_glsl::{
33    FirstScreenGlslError, first_screen_stages, list_first_screen_stages, use_first_screen_glsl,
34};
35/// The GLSL templates of the built-in shader modules, which `build.rs` wrote.
36#[cfg(all(target_arch = "wasm32", feature = "gl-templates"))]
37mod gl_templates {
38    include!(concat!(env!("OUT_DIR"), "/gl_templates.rs"));
39}
40#[cfg(test)]
41#[path = "tests/gles_lowering.rs"]
42mod gles_lowering;
43mod glyph_run;
44mod glyph_run_arena;
45pub(crate) mod gpu_stats;
46mod initial_present;
47#[cfg(all(not(target_arch = "wasm32"), feature = "test-support"))]
48mod inline_present_runtime;
49mod instant_triangles;
50mod lazy_resource;
51mod mesh_fallback;
52mod offscreen;
53mod opaque_prefix;
54mod output_conversion;
55mod pipeline;
56mod pipeline_compiler;
57/// The file in which the driver's compiled pipelines, and a record of the pipelines the first
58/// screen drew with, are kept between launches.
59#[cfg(not(target_arch = "wasm32"))]
60pub mod pipeline_disk_cache;
61mod pipeline_recorder;
62mod pipeline_records;
63#[cfg(not(target_arch = "wasm32"))]
64mod present_handle;
65#[cfg(not(target_arch = "wasm32"))]
66mod present_observer;
67#[cfg(not(target_arch = "wasm32"))]
68mod present_runtime;
69#[cfg(not(target_arch = "wasm32"))]
70mod present_thread;
71mod rc_slice_pool;
72mod record_columns;
73mod render;
74mod rrect_shadow;
75mod run_geometry;
76mod run_store;
77mod scene;
78mod scene_depth;
79mod scene_pass;
80mod scissor;
81mod shader_cache;
82mod shaders;
83mod shape_pipelines;
84mod shared_shader;
85mod target_state;
86#[cfg(test)]
87mod test_support;
88#[cfg(all(not(target_arch = "wasm32"), feature = "test-support"))]
89mod test_target;
90mod text_system;
91mod thread_state;
92mod window_packets;
93
94use std::sync::Arc;
95
96pub use captured_frame::CapturedFrame;
97pub use cpu_allocation_stats::DebugCpuAllocationStats;
98use cranpose_render_common::text_fonts::TextFonts;
99use cranpose_ui_graphics::Rect;
100pub use frame_graph::pass_timing::{GpuPassTimingEntry, GpuPassTimingReport};
101pub use frame_packet::PresentTimings;
102use frame_packet::RenderReturns;
103#[doc(hidden)]
104pub use frame_packet::{CancelReason, PresentOutcome};
105use frontend::RendererFrontend;
106pub use gpu_stats::{FrameDamage, FrameStatsSnapshot as RenderStatsSnapshot, WindowRects};
107pub use gpu_target::{GpuTarget, optional_device_features};
108pub use initial_present::{clear_to_background, clear_to_default_background};
109#[cfg(all(not(target_arch = "wasm32"), feature = "test-support"))]
110pub use inline_present_runtime::InlinePresentRuntime;
111use pipeline_compiler::PipelineCompilation;
112#[cfg(not(target_arch = "wasm32"))]
113use present_handle::PresentHandle;
114#[cfg(not(target_arch = "wasm32"))]
115pub use present_observer::PresentObserver;
116#[cfg(not(target_arch = "wasm32"))]
117use present_runtime::PresentRuntimeInit;
118#[cfg(not(target_arch = "wasm32"))]
119pub use present_thread::PresentThread;
120use render::{FrameOutput, FrameSubmit, GpuRenderer, GpuRendererInit};
121pub use render::{
122    frame_clear_color, frames_presented, pipelines_created, pipelines_created_off_frame,
123};
124pub use scene::{HitRegion, Scene};
125pub use scene_pass::SCENE_DEPTH_FORMAT;
126pub use shared_shader::{shader_stages_flattened, shader_stages_folded};
127#[cfg(all(not(target_arch = "wasm32"), feature = "test-support"))]
128pub use test_target::TestImages;
129pub use text_system::WgpuTextSystem;
130
131pub(crate) fn rect_to_quad(rect: Rect) -> [[f32; 2]; 4] {
132    [
133        [rect.x, rect.y],
134        [rect.x + rect.width, rect.y],
135        [rect.x, rect.y + rect.height],
136        [rect.x + rect.width, rect.y + rect.height],
137    ]
138}
139
140/// Why a [`WgpuRenderer`] call failed.
141#[derive(Debug)]
142pub enum WgpuRendererError {
143    /// The renderer could not draw, with the reason: no GPU was initialized for synchronous
144    /// rendering, there is no scene graph, or the GPU reported an error.
145    Wgpu(String),
146}
147
148// A renderer that draws on the calling thread, and the executor its frames go
149// through.
150struct SyncPresenter {
151    renderer: GpuRenderer,
152    submit: FrameSubmit,
153}
154
155enum PresentBackend {
156    None,
157    Sync(Box<SyncPresenter>),
158    #[cfg(not(target_arch = "wasm32"))]
159    Threaded(PresentHandle),
160}
161
162impl PresentBackend {
163    // The synchronous renderer, or the error a call that needs one reports.
164    fn sync_mut(&mut self) -> Result<&mut SyncPresenter, WgpuRendererError> {
165        match self {
166            Self::Sync(sync) => Ok(sync),
167            _ => Err(WgpuRendererError::Wgpu(
168                "GPU renderer not initialized for synchronous rendering. Call init_gpu() first."
169                    .to_string(),
170            )),
171        }
172    }
173}
174
175/// What [`WgpuRenderer::publish_frame`] did.
176#[derive(Clone, Copy, Debug, PartialEq, Eq)]
177pub enum PublishOutcome {
178    /// No scene graph exists; nothing to lower.
179    NoGraph,
180    /// The depth-one slot is occupied (or the renderer is not in threaded
181    /// mode): NO packet was built — backpressure lands before lowering.
182    NoCredit,
183    /// A packet was built and handed to the present runtime.
184    Published,
185}
186
187/// WGPU-based renderer for GPU-accelerated 2D rendering.
188///
189/// This renderer supports:
190/// - GPU-accelerated shape rendering (rectangles, rounded rectangles)
191/// - Gradients (solid, linear, radial)
192/// - GPU text rendering via retained raster image batches
193/// - Cross-platform support (Desktop, Web, Android)
194pub struct WgpuRenderer {
195    frontend: RendererFrontend,
196    backend: PresentBackend,
197    renderer_epoch: u64,
198    surface_epoch: u64,
199    on_device_lost: Option<DeviceLostHandler>,
200}
201
202/// What a host runs when the device it handed a [`WgpuRenderer`] is lost,
203/// after the loss is logged. It may run on any thread.
204pub type DeviceLostHandler = Arc<dyn Fn() + Send + Sync>;
205
206impl WgpuRenderer {
207    /// Create a new WGPU renderer.
208    ///
209    /// * `fonts` – font bytes to load, ordered by priority (first = highest priority).
210    ///   Pass `&[]` to load no fonts; text will not render until fonts are provided.
211    ///
212    /// Call [`init_gpu`][Self::init_gpu] before rendering.
213    pub fn new(fonts: &[&'static [u8]]) -> Self {
214        Self::with_text_system(WgpuTextSystem::from_fonts(fonts))
215    }
216
217    /// Create a renderer over fonts an app already built.
218    pub fn with_text_fonts(fonts: TextFonts) -> Self {
219        Self::with_text_system(WgpuTextSystem::from_text_fonts(fonts))
220    }
221
222    /// Create a renderer that hands the app the fonts of `text_system`.
223    pub fn with_text_system(text_system: WgpuTextSystem) -> Self {
224        Self {
225            frontend: RendererFrontend::new(text_system.fonts().clone()),
226            backend: PresentBackend::None,
227            renderer_epoch: 0,
228            surface_epoch: 0,
229            on_device_lost: None,
230        }
231    }
232
233    /// Runs `handler` when the device of a later `init_gpu` call is lost,
234    /// so the host can open another device and hand it over.
235    pub fn set_device_lost_handler(&mut self, handler: DeviceLostHandler) {
236        self.on_device_lost = Some(handler);
237    }
238
239    fn sync_gpu_renderer(&self) -> Option<&GpuRenderer> {
240        match &self.backend {
241            PresentBackend::Sync(sync) => Some(&sync.renderer),
242            _ => None,
243        }
244    }
245
246    fn retire_live_backend(&mut self) {
247        #[allow(unused_mut, reason = "only native targets change the backend")]
248        let mut backend = std::mem::replace(&mut self.backend, PresentBackend::None);
249        #[cfg(not(target_arch = "wasm32"))]
250        if let PresentBackend::Threaded(handle) = &mut backend {
251            while let Some(returns) = handle.try_drain() {
252                self.frontend.apply_returns(returns);
253            }
254            handle.shutdown();
255        }
256        drop(backend);
257    }
258
259    /// Drops what the renderer holds on its device, for a host whose device
260    /// is gone: the frees then reach the lost device, as a WebGL context
261    /// that is lost ignores them, rather than the device that replaces it.
262    /// [`Self::init_gpu`] gives the renderer a device again.
263    pub fn release_gpu(&mut self) {
264        self.retire_live_backend();
265    }
266
267    /// Initialize GPU resources with a WGPU device and queue.
268    ///
269    /// Replacing a live renderer (Android surface recreation, device loss)
270    /// bumps the renderer epoch, so a packet built against the previous
271    /// renderer is cancelled instead of drawn.
272    pub fn init_gpu(&mut self, target: GpuTarget) {
273        self.install_gpu(target, PipelineCompilation::Background);
274    }
275
276    /// [`init_gpu`][Self::init_gpu], compiling every pipeline where it is
277    /// first needed instead of on the background compiler: no frame draws
278    /// with a stand-in, which a reference frame in a test must not.
279    #[doc(hidden)]
280    pub fn init_gpu_compiling_inline_for_tests(&mut self, target: GpuTarget) {
281        self.install_gpu(target, PipelineCompilation::Inline);
282    }
283
284    fn install_gpu(&mut self, target: GpuTarget, pipeline_compilation: PipelineCompilation) {
285        let init = self.next_gpu_init(target, pipeline_compilation);
286        let submit = FrameSubmit::new(&init);
287        self.backend = PresentBackend::Sync(Box::new(SyncPresenter {
288            renderer: GpuRenderer::new(init),
289            submit,
290        }));
291    }
292
293    /// Retires the live backend and bumps the renderer epoch, then describes
294    /// the renderer that replaces it on `target`.
295    fn next_gpu_init(
296        &mut self,
297        target: GpuTarget,
298        pipeline_compilation: PipelineCompilation,
299    ) -> GpuRendererInit {
300        self.retire_live_backend();
301        self.renderer_epoch = self.renderer_epoch.wrapping_add(1);
302        target.renderer_init(
303            self.renderer_epoch,
304            pipeline_compilation,
305            self.on_device_lost.clone(),
306        )
307    }
308
309    /// [`init_gpu`][Self::init_gpu] for the threaded present runtime
310    /// (Android): the same epoch bump and planner replacement hygiene, but
311    /// instead of constructing a `GpuRenderer` here, everything it needs —
312    /// all owned, all `Send` — crosses to a spawned present thread that
313    /// constructs its own (its `Rc` caches are thread-confined). Frames
314    /// then flow through [`publish_frame`][Self::publish_frame] /
315    /// [`drain_present_returns`][Self::drain_present_returns] under the
316    /// depth-one credit protocol instead of [`render`][Self::render].
317    ///
318    /// * `waker` — wakes the producer's event loop after every returns
319    ///   send (the Android frame waker).
320    /// * `clock` — producer's monotonic nanosecond clock, so present-side
321    ///   [`PresentTimings`] share the producer telemetry's clock domain;
322    ///   `None` leaves timings at zero.
323    /// * `observer` — runs on the present thread around every present to the
324    ///   surface.
325    #[cfg(not(target_arch = "wasm32"))]
326    pub fn init_gpu_threaded(
327        &mut self,
328        target: GpuTarget,
329        waker: Arc<dyn Fn() + Send + Sync>,
330        clock: Option<Arc<dyn Fn() -> i64 + Send + Sync>>,
331        observer: Option<Box<dyn PresentObserver>>,
332    ) -> Result<(), WgpuRendererError> {
333        let init = PresentRuntimeInit {
334            gpu: self.next_gpu_init(target, PipelineCompilation::Background),
335            clock,
336            observer,
337        };
338        let handle = PresentHandle::spawn(init, waker).map_err(WgpuRendererError::Wgpu)?;
339        self.backend = PresentBackend::Threaded(handle);
340        Ok(())
341    }
342
343    #[cfg(all(not(target_arch = "wasm32"), feature = "test-support"))]
344    #[doc(hidden)]
345    pub fn init_gpu_inline_for_tests(&mut self, target: GpuTarget) -> InlinePresentRuntime {
346        let init = PresentRuntimeInit {
347            gpu: self.next_gpu_init(target, PipelineCompilation::Background),
348            clock: None,
349            observer: None,
350        };
351        let (handle, state, msg_rx) = PresentHandle::new_inline(init, Arc::new(|| {}));
352        self.backend = PresentBackend::Threaded(handle);
353        InlinePresentRuntime::new(state, msg_rx)
354    }
355
356    /// Record that the surface was reconfigured (resize, format change,
357    /// swapchain recreation): bumps the surface epoch stamped into every
358    /// subsequent packet, so a packet built against the previous
359    /// configuration is cancelled by the present stage instead of drawn.
360    pub fn note_surface_reconfigured(&mut self) {
361        self.surface_epoch = self.surface_epoch.wrapping_add(1);
362    }
363
364    /// Clears each frame to nothing instead of the framework's background,
365    /// for a window whose surface composites with the desktop behind it. A
366    /// renderer starts opaque; `false` puts the background back. Takes
367    /// effect from the next frame, on either present backend.
368    pub fn set_transparent_background(&mut self, transparent: bool) {
369        self.frontend.transparent_background = transparent;
370    }
371
372    /// The scale from logical to device pixels the renderer draws the root with, as last set
373    /// by `Renderer::set_root_scale`. It starts at `1.0`.
374    pub fn root_scale(&self) -> f32 {
375        self.frontend.root_scale
376    }
377
378    /// Render the scene to a texture view.
379    ///
380    /// Producer first, present second: the frontend collects the frame into
381    /// a `frame_packet::FramePacket` (root and dev overlay alike), the GPU
382    /// renderer consumes it, and the present stage's returns fold back into
383    /// the frontend afterwards.
384    pub fn render(
385        &mut self,
386        texture: &wgpu::Texture,
387        view: &wgpu::TextureView,
388        width: u32,
389        height: u32,
390    ) -> Result<(), WgpuRendererError> {
391        self.render_frame(texture, view, width, height, frame::ImageContent::Untracked)
392    }
393
394    /// Renders the frame into a surface's presentable image `frame`, through
395    /// `view`. When the image carries the composition format and the capture
396    /// usages, the scene renders into it directly and no output conversion
397    /// pass runs. When the surface hands the image back with the frame it
398    /// last presented (`wgpu::Surface::keep_presented_images`), the frame
399    /// draws only what changed since that frame. When the surface hands its
400    /// images out cleared, as a WebGPU canvas does, and the frames change a
401    /// small part of a window drawn over more than twice, the renderer keeps
402    /// the frame in a texture of its own, draws only what changed there and
403    /// copies it into the image; see [`release_kept_copy`](Self::release_kept_copy).
404    pub fn render_surface_texture(
405        &mut self,
406        frame: &wgpu::SurfaceTexture,
407        view: &wgpu::TextureView,
408        width: u32,
409        height: u32,
410    ) -> Result<(), WgpuRendererError> {
411        let image = frame::ImageContent::of(frame);
412        self.render_frame(&frame.texture, view, width, height, image)
413    }
414
415    /// Clears `view` to the color a frame clears to before it draws. `view`
416    /// is the image of a surface that just took a frame through
417    /// [`render_surface_texture`](Self::render_surface_texture). The
418    /// renderer drops its copy of that frame, so the next frame draws whole.
419    /// A web page hides so a first frame that left out the draws of
420    /// pipelines still compiling in the browser.
421    #[cfg(target_arch = "wasm32")]
422    pub fn hide_drawn_frame(&mut self, view: &wgpu::TextureView) {
423        let Some(gpu_renderer) = self.sync_gpu_renderer() else {
424            return;
425        };
426        clear_to_background(
427            &gpu_renderer.device,
428            &gpu_renderer.queue,
429            view,
430            frame_clear_color(self.frontend.transparent_background),
431        );
432        self.release_kept_copy();
433    }
434
435    /// Presents a surface image this renderer drew with
436    /// [`render_surface_texture`](Self::render_surface_texture), on the queue
437    /// that recorded it.
438    ///
439    /// Before [`init_gpu`](Self::init_gpu) there is no queue, and the image is
440    /// released without being shown.
441    pub fn present(&self, frame: wgpu::SurfaceTexture) {
442        match self.sync_gpu_renderer() {
443            Some(gpu_renderer) => gpu_renderer.queue.present(frame),
444            None => log::debug!("surface image released: the renderer has no GPU queue"),
445        }
446    }
447
448    /// Draws a swapchain image the way the present runtime does on a surface
449    /// that keeps presented images: `index` is its place in a swapchain of
450    /// `images` and `kept` says it holds the frame drawn into it last.
451    #[doc(hidden)]
452    pub fn render_swapchain_image_for_tests(
453        &mut self,
454        texture: &wgpu::Texture,
455        view: &wgpu::TextureView,
456        index: u32,
457        images: u32,
458        kept: bool,
459    ) -> Result<(), WgpuRendererError> {
460        self.render_frame(
461            texture,
462            view,
463            texture.width(),
464            texture.height(),
465            frame::ImageContent::Numbered(frame::PresentedImage {
466                index,
467                kept,
468                images,
469            }),
470        )
471    }
472
473    /// Draws an image the way a surface that hands out its images cleared,
474    /// as a WebGPU canvas does, has it drawn.
475    #[doc(hidden)]
476    pub fn render_cleared_image_for_tests(
477        &mut self,
478        texture: &wgpu::Texture,
479        view: &wgpu::TextureView,
480    ) -> Result<(), WgpuRendererError> {
481        self.render_frame(
482            texture,
483            view,
484            texture.width(),
485            texture.height(),
486            frame::ImageContent::Cleared,
487        )
488    }
489
490    /// Lets go of the texture that keeps the last frame for a surface whose
491    /// images come cleared (see
492    /// [`render_surface_texture`](Self::render_surface_texture)), a window of
493    /// memory. A runtime calls it once its app holds still; the next frame
494    /// draws whole.
495    pub fn release_kept_copy(&mut self) {
496        if let PresentBackend::Sync(sync) = &mut self.backend {
497            sync.renderer.release_kept_copy();
498            self.frontend.forget_held();
499        }
500    }
501
502    fn render_frame(
503        &mut self,
504        texture: &wgpu::Texture,
505        view: &wgpu::TextureView,
506        width: u32,
507        height: u32,
508        image: frame::ImageContent,
509    ) -> Result<(), WgpuRendererError> {
510        self.frontend.landings = self.landings();
511        let SyncPresenter {
512            renderer: gpu_renderer,
513            submit,
514        } = self.backend.sync_mut()?;
515        let epochs = (self.renderer_epoch, self.surface_epoch);
516        let output = FrameOutput::display(texture, view, image);
517        let draw = |packet, returns: &mut RenderReturns| {
518            gpu_renderer.render(submit, (width, height), packet, epochs.1, returns, output)
519        };
520        self.frontend
521            .draw_window((width, height), epochs, image, draw)
522            .ok_or_else(|| WgpuRendererError::Wgpu("scene graph is missing".to_string()))?
523            .map_err(WgpuRendererError::Wgpu)
524    }
525
526    /// Whether the surface already shows the current scene at `width` by
527    /// `height` device pixels: the frame drawn last into a surface that keeps
528    /// its presented images, with nothing changed since. A platform asks
529    /// before it takes the surface's next image, and when the surface shows
530    /// the scene it takes no image, draws nothing and presents nothing.
531    /// Otherwise the frame drawn next starts from the scene this collected.
532    pub fn shows_scene(&mut self, width: u32, height: u32) -> bool {
533        self.frontend.landings = self.landings();
534        let PresentBackend::Sync(sync) = &mut self.backend else {
535            return false;
536        };
537        let Some(packet) =
538            self.frontend
539                .take_packet(width, height, self.renderer_epoch, self.surface_epoch)
540        else {
541            return false;
542        };
543        let shown = sync.renderer.shows(&packet, (width, height));
544        if shown {
545            self.frontend.recycle(packet);
546        } else {
547            self.frontend.keep_packet(packet);
548        }
549        shown
550    }
551
552    /// Render the current scene into an RGBA pixel buffer for robot tests.
553    ///
554    /// Uses the renderer's configured root scale.
555    pub fn capture_frame(
556        &mut self,
557        width: u32,
558        height: u32,
559    ) -> Result<CapturedFrame, WgpuRendererError> {
560        self.capture_frame_with_scale(width, height, self.frontend.root_scale)
561    }
562
563    /// Builds every pipeline the pipeline cache file records on the
564    /// background compiler, and returns whether they were all built before
565    /// `timeout`, or before `stop` said to stop. An app runs it after an
566    /// update, before its next launch, so that launch finds them compiled;
567    /// the renderer writes the file when it is dropped, and drops the builds
568    /// not started. It draws nothing, and needs a renderer initialized for
569    /// synchronous rendering.
570    #[cfg(not(target_arch = "wasm32"))]
571    pub fn prepare_recorded_pipelines(
572        &mut self,
573        timeout: std::time::Duration,
574        stop: &dyn Fn() -> bool,
575    ) -> bool {
576        let PresentBackend::Sync(sync) = &mut self.backend else {
577            return false;
578        };
579        let gpu_renderer = &mut sync.renderer;
580        let deadline = web_time::Instant::now() + timeout;
581        let mut compiling = gpu_renderer.prepare_recorded();
582        while compiling {
583            if web_time::Instant::now() >= deadline || stop() {
584                return false;
585            }
586            std::thread::sleep(std::time::Duration::from_millis(10));
587            compiling = gpu_renderer.pipelines.compiling();
588        }
589        true
590    }
591
592    /// Render the current scene into an RGBA pixel buffer with an explicit scale.
593    ///
594    /// `width` and `height` are in device pixels and `root_scale` is the scale from logical to
595    /// device pixels. Needs a renderer initialized for synchronous rendering.
596    pub fn capture_frame_with_scale(
597        &mut self,
598        width: u32,
599        height: u32,
600        root_scale: f32,
601    ) -> Result<CapturedFrame, WgpuRendererError> {
602        let SyncPresenter {
603            renderer: gpu_renderer,
604            submit,
605        } = self.backend.sync_mut()?;
606        let packet = self
607            .frontend
608            .build_frame_packet_with_scale(
609                (width, height, root_scale),
610                self.renderer_epoch,
611                self.surface_epoch,
612                frontend::PacketFor::Capture,
613            )
614            .ok_or_else(|| WgpuRendererError::Wgpu("scene graph is missing".to_string()))?;
615        let mut returns = RenderReturns::default();
616        let result = gpu_renderer.render_to_rgba_pixels(
617            submit,
618            (width, height),
619            packet,
620            self.surface_epoch,
621            &mut returns,
622        );
623        self.frontend.apply_returns(returns);
624        let pixels = result.map_err(WgpuRendererError::Wgpu)?;
625        Ok(CapturedFrame {
626            width,
627            height,
628            pixels,
629            stats: gpu_renderer.last_frame_stats(),
630        })
631    }
632
633    /// Threaded mode: whether the present thread takes a packet now. Two
634    /// packets go in flight at most.
635    /// The Android loop checks this BEFORE `shell.update()` so
636    /// backpressure lands before the expensive update/lowering work.
637    /// Always `true` on the sync path, which has no slot to fill.
638    #[cfg(not(target_arch = "wasm32"))]
639    pub fn has_frame_credit(&self) -> bool {
640        match &self.backend {
641            PresentBackend::Threaded(handle) => handle.has_credit(),
642            PresentBackend::Sync(_) | PresentBackend::None => true,
643        }
644    }
645
646    /// Threaded mode: whether the present thread has handed back a frame
647    /// that [`drain_present_returns`][Self::drain_present_returns] has not
648    /// folded back yet, so draining it would free a publish credit. A loop
649    /// out of credit can work on other things until this turns true.
650    /// Always `false` outside threaded mode.
651    #[cfg(not(target_arch = "wasm32"))]
652    pub fn frame_credit_returned(&self) -> bool {
653        match &self.backend {
654            PresentBackend::Threaded(handle) => handle.has_undrained_return(),
655            PresentBackend::Sync(_) | PresentBackend::None => false,
656        }
657    }
658
659    /// Threaded mode: lower the current scene into a packet and hand it to
660    /// the present runtime. Credit is checked FIRST — a `NoCredit` return
661    /// means no packet was built at all (`frame_sequence` does not
662    /// advance). Returns `NoCredit` (with an error log) when the renderer
663    /// is not in threaded mode.
664    #[cfg(not(target_arch = "wasm32"))]
665    pub fn publish_frame(&mut self, width: u32, height: u32) -> PublishOutcome {
666        self.frontend.landings = self.landings();
667        let PresentBackend::Threaded(handle) = &mut self.backend else {
668            log::error!("publish_frame called without a threaded present runtime");
669            return PublishOutcome::NoCredit;
670        };
671        if !handle.has_credit() {
672            return PublishOutcome::NoCredit;
673        }
674        let Some(packet) = self.frontend.build_frame_packet(
675            width,
676            height,
677            self.renderer_epoch,
678            self.surface_epoch,
679        ) else {
680            return PublishOutcome::NoGraph;
681        };
682        match handle.publish(packet) {
683            Ok(()) => PublishOutcome::Published,
684            Err(packet) => {
685                let mut returns = RenderReturns::default();
686                GpuRenderer::cancel_packet(*packet, CancelReason::SurfaceUnavailable, &mut returns);
687                self.frontend.apply_returns(returns);
688                log::error!("present runtime unavailable; frame recovered, not published");
689                PublishOutcome::NoCredit
690            }
691        }
692    }
693
694    /// Threaded mode: fold every pending `RenderReturns` back into
695    /// producer state and free the publish credit. Returns how many were
696    /// drained. No-op outside threaded mode.
697    #[cfg(not(target_arch = "wasm32"))]
698    pub fn drain_present_returns(&mut self) -> usize {
699        self.drain_present_returns_with(&mut |_, _, _| {})
700    }
701
702    /// [`drain_present_returns`][Self::drain_present_returns], reporting
703    /// each drained frame's id, outcome and present-thread timings — the
704    /// Android loop feeds its frame telemetry from this.
705    #[cfg(not(target_arch = "wasm32"))]
706    pub fn drain_present_returns_with(
707        &mut self,
708        on_return: &mut dyn FnMut(u64, PresentOutcome, PresentTimings),
709    ) -> usize {
710        let mut drained = 0;
711        loop {
712            let returns = {
713                let PresentBackend::Threaded(handle) = &mut self.backend else {
714                    break;
715                };
716                match handle.try_drain() {
717                    Some(returns) => returns,
718                    None => break,
719                }
720            };
721            drained += 1;
722            let frame_id = returns.frame_id;
723            let outcome = returns.outcome;
724            let timings = returns.timings;
725            self.frontend.apply_returns(returns);
726            on_return(frame_id, outcome, timings);
727        }
728        drained
729    }
730
731    /// The thread this renderer hands its frames to, when it presents on one
732    /// ([`init_gpu_threaded`][Self::init_gpu_threaded]); `None` when it
733    /// draws on the calling thread.
734    #[cfg(not(target_arch = "wasm32"))]
735    pub fn present_thread(&mut self) -> Option<PresentThread<'_>> {
736        let PresentBackend::Threaded(handle) = &mut self.backend else {
737            return None;
738        };
739        Some(PresentThread {
740            handle,
741            surface_epoch: &mut self.surface_epoch,
742        })
743    }
744
745    /// Threaded mode: drain outstanding returns, stop the present thread
746    /// and join it. The renderer returns to the uninitialized state.
747    #[cfg(not(target_arch = "wasm32"))]
748    pub fn shutdown_present_runtime(&mut self) {
749        if matches!(self.backend, PresentBackend::Threaded(_)) {
750            self.retire_live_backend();
751        }
752    }
753
754    /// The OS id of the thread that presents frames, once that thread has
755    /// started, on systems whose scheduler hints name threads by one.
756    /// `None` when frames present on the calling thread.
757    pub fn present_thread_id(&self) -> Option<i32> {
758        match &self.backend {
759            #[cfg(not(target_arch = "wasm32"))]
760            PresentBackend::Threaded(handle) => {
761                let id = handle
762                    .status()
763                    .thread_id
764                    .load(std::sync::atomic::Ordering::Relaxed);
765                (id != 0).then_some(id)
766            }
767            _ => None,
768        }
769    }
770
771    /// The producer's monotone packet sequence: the `frame_id` stamped on
772    /// the most recently lowered packet. After a `Published` outcome this
773    /// is the published frame's id (the Android loop keys its telemetry on
774    /// it); it also proves a `NoCredit` publish never lowered a frame.
775    pub fn last_published_frame_id(&self) -> u64 {
776        self.frontend.frame_sequence
777    }
778
779    /// The counters of the most recent frame the renderer drew, or `None` before it drew one.
780    pub fn last_frame_stats(&self) -> Option<RenderStatsSnapshot> {
781        match &self.backend {
782            PresentBackend::Sync(sync) => sync.renderer.last_frame_stats(),
783            #[cfg(not(target_arch = "wasm32"))]
784            PresentBackend::Threaded(handle) => *handle
785                .status()
786                .last_frame_stats
787                .lock()
788                .unwrap_or_else(std::sync::PoisonError::into_inner),
789            PresentBackend::None => None,
790        }
791    }
792
793    /// Whether the pipeline cache file held an earlier launch's first screen,
794    /// whose pipelines build ahead of this renderer's first frame; `false`
795    /// for a first launch or emptied caches, whose first frame builds its
796    /// pipelines, and for a renderer that does not draw on the calling
797    /// thread.
798    #[cfg(not(target_arch = "wasm32"))]
799    pub fn first_screen_recorded(&self) -> bool {
800        self.sync_gpu_renderer()
801            .is_some_and(GpuRenderer::first_screen_recorded)
802    }
803
804    /// The pipelines this renderer's first screen drew with, encoded for
805    /// [`Self::build_first_screen_pipelines`] in a later launch. `None`
806    /// until the first screen ends, two seconds after the first frame and
807    /// later by every wait for a pipeline, and for a renderer that does not
808    /// draw on the calling thread.
809    pub fn first_screen_pipelines(&self) -> Option<Vec<u8>> {
810        self.sync_gpu_renderer()
811            .and_then(|renderer| renderer.pipelines.first_screen_pipelines())
812    }
813
814    /// Builds now the pipelines one set in `records` names: sets
815    /// [`Self::first_screen_pipelines`] wrote, one after another, each at the
816    /// size its first frame drew. A web page calls this as its renderer
817    /// starts, so the browser compiles them while the page composes its
818    /// first screen. Of the sets drawn on this renderer's backend by a build
819    /// with the same layout of pipeline keys, the one drawn nearest to
820    /// `viewport` pixels builds: a phone's screen and a desktop window's
821    /// draw with different pipelines, and a frame that waits for pipelines
822    /// it does not draw with comes later. A renderer that does not draw on
823    /// the calling thread builds nothing.
824    pub fn build_first_screen_pipelines(&mut self, records: &[u8], viewport: (u32, u32)) {
825        if let PresentBackend::Sync(sync) = &mut self.backend {
826            sync.renderer.build_first_screen(records, viewport);
827        }
828    }
829
830    /// GPU milliseconds by pass label, aggregated since the last `[GPU-PASS]`
831    /// print. Empty unless `CRANPOSE_GPU_PASS_TIMING` armed pass timing on a
832    /// device with [`wgpu::Features::TIMESTAMP_QUERY`].
833    pub fn gpu_pass_timings(&self) -> GpuPassTimingReport {
834        match &self.backend {
835            PresentBackend::Sync(sync) => sync.submit.executor.pass_timing_report(),
836            _ => GpuPassTimingReport::default(),
837        }
838    }
839
840    /// The sizes and capacities of the renderer's CPU-side scene data, scratch buffers and
841    /// caches, for memory diagnostics. The members of a renderer that does not draw on the
842    /// calling thread cover the scene only.
843    pub fn debug_cpu_allocation_stats(&self) -> DebugCpuAllocationStats {
844        let mut stats = self
845            .sync_gpu_renderer()
846            .map_or_default(GpuRenderer::debug_cpu_allocation_stats);
847        stats.scene_graph_node_count = self.frontend.scene.store().node_count();
848        stats.scene_graph_heap_bytes = self.frontend.scene.store().heap_bytes();
849        stats.scene_hits = self.frontend.scene.hit_storage();
850        stats
851    }
852
853    /// Starts a frame drawn while none has shown whole yet. Such a frame
854    /// builds the pipelines it expects a later frame to need at its end, so
855    /// the browser compiles them behind the frame's own.
856    #[cfg(target_arch = "wasm32")]
857    pub fn begin_first_frame(&self) {
858        if let Some(gpu_renderer) = self.sync_gpu_renderer() {
859            gpu_renderer.pipelines.compiler.begin_first_frame();
860        }
861    }
862
863    /// Tells the renderer that the pipelines the browser compiled in the
864    /// background landed (`wgpu::Device::compile_pipelines_in_background`).
865    /// Earlier frames left out the draws that use them: the next frame drops
866    /// what those frames drew and kept, and draws again what they left out.
867    #[cfg(target_arch = "wasm32")]
868    pub fn background_pipelines_landed(&mut self) {
869        if let PresentBackend::Sync(sync) = &mut self.backend {
870            sync.renderer.background_pipelines_landed();
871        }
872    }
873
874    /// Tells the renderer that the browser compiles the pipelines it creates
875    /// from now on in the background (`wgpu::Device::compile_pipelines_in_background`).
876    /// On WebGPU the first screen draws its shapes with a general pipeline,
877    /// whose one compile stands in for the specialized ones; those it builds
878    /// once this is called, and draws switch to each as it lands. A
879    /// renderer whose target is no browser's builds nothing more for it.
880    pub fn compile_pipelines_in_background(&mut self) {
881        if let PresentBackend::Sync(sync) = &mut self.backend {
882            sync.renderer.pipelines.compile_pipelines_in_background();
883        }
884    }
885
886    /// Return the WGPU device when GPU resources are initialized.
887    /// Sync backend only (desktop/web reconfigure paths); the threaded
888    /// runtime owns its device on the present thread.
889    pub fn try_device(&self) -> Option<&wgpu::Device> {
890        self.sync_gpu_renderer().map(|r| &*r.device)
891    }
892
893    #[doc(hidden)]
894    pub fn try_queue_for_tests(&self) -> Option<&wgpu::Queue> {
895        self.sync_gpu_renderer().map(|r| &*r.queue)
896    }
897
898    #[doc(hidden)]
899    pub fn device_error_count_for_tests(&self) -> u64 {
900        self.sync_gpu_renderer()
901            .map_or(0, GpuRenderer::device_error_count)
902    }
903
904    #[doc(hidden)]
905    pub fn build_frame_packet_for_tests(
906        &mut self,
907        width: u32,
908        height: u32,
909    ) -> Option<HeldFramePacket> {
910        self.frontend.landings = self.landings();
911        self.frontend
912            .build_frame_packet(width, height, self.renderer_epoch, self.surface_epoch)
913            .map(HeldFramePacket)
914    }
915
916    // The renderer's count of pipeline landings, which a window packet built
917    // now culls by.
918    fn landings(&mut self) -> Option<u64> {
919        match &mut self.backend {
920            PresentBackend::Sync(sync) => Some(sync.renderer.pipelines.count_landings()),
921            #[cfg(not(target_arch = "wasm32"))]
922            PresentBackend::Threaded(handle) => {
923                handle.status().landing.get().map(|landing| landing.built())
924            }
925            PresentBackend::None => None,
926        }
927    }
928
929    /// Return a producer-built packet without presenting it, as a target
930    /// that keeps its frames returns a packet whose damage it drew. This
931    /// exercises the bounded scene-storage recycler and the damage back-off
932    /// that normal present returns drive, in offline producer benchmarks.
933    ///
934    /// ```
935    /// use cranpose_render_wgpu::{HeldFramePacket, WgpuRenderer};
936    ///
937    /// fn return_without_presenting(renderer: &mut WgpuRenderer, packet: HeldFramePacket) {
938    ///     renderer.return_held_packet_for_tests(packet);
939    /// }
940    /// ```
941    #[doc(hidden)]
942    pub fn return_held_packet_for_tests(&mut self, packet: HeldFramePacket) {
943        self.frontend
944            .apply_returns(RenderReturns::drawn_in_place(packet.0));
945    }
946
947    #[doc(hidden)]
948    pub fn render_held_packet_for_tests(
949        &mut self,
950        texture: &wgpu::Texture,
951        view: &wgpu::TextureView,
952        width: u32,
953        height: u32,
954        packet: HeldFramePacket,
955    ) -> Result<PresentOutcome, WgpuRendererError> {
956        let SyncPresenter {
957            renderer: gpu_renderer,
958            submit,
959        } = self.backend.sync_mut()?;
960        let mut returns = RenderReturns::default();
961        let result = gpu_renderer.render(
962            submit,
963            (width, height),
964            packet.0,
965            self.surface_epoch,
966            &mut returns,
967            FrameOutput::display(texture, view, frame::ImageContent::Untracked),
968        );
969        let outcome = returns.outcome;
970        self.frontend.apply_returns(returns);
971        result.map_err(WgpuRendererError::Wgpu)?;
972        Ok(outcome)
973    }
974}
975
976#[doc(hidden)]
977pub struct HeldFramePacket(frame_packet::FramePacket);
978
979impl Default for WgpuRenderer {
980    fn default() -> Self {
981        Self::new(&[])
982    }
983}
984
985#[cfg(test)]
986#[path = "tests/wgpu_tests.rs"]
987mod tests;