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