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