Skip to main content

cranpose_render_wgpu/
lib.rs

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