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