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