uzor-render-hub 1.2.0

uzor-render-hub: unified rendering backend hub — auto-detects GPU, instantiates the right backend (vello-gpu / vello-hybrid / wgpu-instanced / vello-cpu / tiny-skia), submits frames, collects metrics.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
//! Per-window persistent render state.
//!
//! [`WindowRenderState`] is a **flat struct** that holds all initialized
//! renderer slots plus a [`SurfaceMode`] (GPU swapchain or CPU software
//! buffer).  The active backend is a runtime field — switching backends is
//! done by updating `state.active` through [`RenderHub::set_active`] rather
//! than by recreating the entire state.
//!
//! # Design rationale
//!
//! The old `WindowRenderState` was a 5-variant enum where each variant owned
//! exactly one renderer.  The flat struct replaces this with five `Option<>`
//! slots so multiple renderers can be initialized at the same time, enabling
//! live backend switching without a re-init cycle.
//!
//! ## Send + Sync story
//!
//! `WindowRenderState` is `Send` because:
//! - All wgpu types (`RenderSurface`, devices, queues) are `Send`.
//! - `vello::Renderer`, `vello_hybrid::Renderer`, `InstancedRenderer` are
//!   `Send`.
//! - CPU contexts (`VelloCpuRenderContext`, `TinySkiaCpuRenderContext`) are
//!   `Send`.
//!
//! `WindowRenderState` is **not** `Sync` — it contains interior-mutable GPU
//! state that is not safe to share across threads.  This is fine; the runtime
//! always drives one window from one thread.

use uzor_render_tiny_skia::TinySkiaCpuRenderContext;
use uzor_render_vello_cpu::VelloCpuRenderContext;
use uzor_render_vello_gpu::VelloGpuRenderContext;
use uzor_render_vello_hybrid::VelloHybridRenderContext;
use uzor_render_wgpu_instanced::{InstancedRenderContext, InstancedRenderer};
#[cfg(not(target_arch = "wasm32"))]
use uzor_window_hub::lifecycle::SoftwarePresenter;
use vello::util::{RenderContext as VelloRenderContext, RenderSurface};
use vello::{Renderer as VelloRenderer, Scene};

use crate::backend::RenderBackend;

#[cfg(target_arch = "wasm32")]
use uzor_render_canvas2d::Canvas2dRenderContext;

/// Local alias for vello's GPU device pool.
///
/// vello calls this type `RenderContext`, but that name collides with our
/// public `uzor::render::RenderContext` (the widget draw trait).
pub type GpuDevicePool = VelloRenderContext;

// ── SurfaceMode ───────────────────────────────────────────────────────────────

/// How the window surface is presented.
///
/// All backends that have a GPU adapter available share the same wgpu swapchain
/// — CPU backends upload their pixels via `queue.write_texture` into the same
/// `target_texture`, then the blitter copies to the swapchain (mlc pattern).
///
/// On machines with no GPU the `Software` variant is used instead: only
/// `TinySkia` and `VelloCpu` can run in this mode.  The `Software` variant is
/// not available on `wasm32` (softbuffer is desktop-only).
///
/// On `wasm32` the `Canvas2d` variant is used for DOM canvas rendering.
pub enum SurfaceMode {
    /// wgpu swapchain — used by all backends when a GPU adapter is available.
    ///
    /// CPU backends (VelloCpu, TinySkia) write their pixels via
    /// `queue.write_texture` into `surface.target_texture`, then the blitter
    /// copies the target texture to the swapchain (mlc gpu_submit.rs pattern,
    /// lines 235–258).
    Gpu {
        /// wgpu instance + device pool.
        gpu_pool: GpuDevicePool,
        /// wgpu swapchain bound to the OS window.  `'static` because the window
        /// is kept alive by `WinitWindowProvider` for the entire runtime duration.
        surface: RenderSurface<'static>,
        /// Device index into `gpu_pool.devices`.
        dev_id: usize,
    },
    /// softbuffer software surface — only valid when no GPU is present.
    ///
    /// Only `TinySkia` and `VelloCpu` can render in this mode.
    /// The `presenter` is called once per frame to push the CPU-rasterized
    /// pixel buffer to the OS window.
    #[cfg(not(target_arch = "wasm32"))]
    Software {
        /// Opaque OS window presenter (softbuffer on desktop).
        presenter: Box<dyn SoftwarePresenter>,
        /// Physical width of the software buffer in pixels.
        width: u32,
        /// Physical height of the software buffer in pixels.
        height: u32,
    },
    /// DOM canvas surface (wasm32 only).
    ///
    /// The [`Canvas2dRenderContext`] draws directly into the HTML canvas element.
    /// No GPU swapchain or software buffer is needed — the browser presents the
    /// canvas automatically after each RAF callback.
    #[cfg(target_arch = "wasm32")]
    Canvas2d {
        /// The HTML canvas element being rendered into.
        canvas: web_sys::HtmlCanvasElement,
    },
}

// ── Per-frame context — caller-built, hub-consumed ────────────────────────────

/// Backend-specific render context the caller fills each frame.
///
/// `VelloGpu` borrows the vello scene; the others are owned.
pub enum BackendContext<'a> {
    /// GPU-backed vello scene context.
    VelloGpu(VelloGpuRenderContext<'a>),
    /// vello hybrid context.
    VelloHybrid(VelloHybridRenderContext),
    /// Wgpu instanced draw context.
    Instanced(InstancedRenderContext),
    /// vello CPU context.
    VelloCpu(VelloCpuRenderContext),
    /// tiny-skia CPU context.
    TinySkia(TinySkiaCpuRenderContext),
}

impl<'a> BackendContext<'a> {
    /// Build a `VelloGpu` context from a mutable scene reference.
    pub fn vello_gpu(scene: &'a mut Scene, offset_x: f64, offset_y: f64) -> Self {
        Self::VelloGpu(VelloGpuRenderContext::new(scene, offset_x, offset_y))
    }
    /// Build a `VelloHybrid` context.
    pub fn vello_hybrid(dpr: f64) -> Self {
        Self::VelloHybrid(VelloHybridRenderContext::new(dpr))
    }
    /// Build an `Instanced` context.
    pub fn instanced(screen_w: f32, screen_h: f32, offset_x: f32, offset_y: f32) -> Self {
        Self::Instanced(InstancedRenderContext::new(screen_w, screen_h, offset_x, offset_y))
    }
    /// Build a `VelloCpu` context.
    pub fn vello_cpu(dpr: f64) -> Self {
        Self::VelloCpu(VelloCpuRenderContext::new(dpr))
    }
    /// Build a `TinySkia` context with its own pixel buffer.
    pub fn tiny_skia(width: u32, height: u32, dpr: f64) -> Self {
        Self::TinySkia(TinySkiaCpuRenderContext::new(width, height, dpr))
    }
}

// ── WindowRenderState ─────────────────────────────────────────────────────────

/// Flat per-window render state that holds **all** initialized renderer slots.
///
/// At most one renderer per slot is initialized at any time; slots that are not
/// relevant to the current backend remain `None`.
///
/// # Frame lifecycle
///
/// 1. Call [`begin_frame`](Self::begin_frame) once at the start of each frame.
/// 2. Fill the scene / CPU buffer via the backend-specific accessor.
/// 3. Call [`crate::submit_frame`] to present.
///
/// # Live backend switching
///
/// Update `state.active` (via [`RenderHub::set_active`]) before the next frame.
/// The renderer for the new backend must already be initialized (`Some`); if it
/// is not, [`crate::submit_frame`] will emit a warning and skip the frame.
pub struct WindowRenderState {
    // ── Surface ───────────────────────────────────────────────────────────────
    /// How the frame is presented to the OS window.
    pub(crate) surface: SurfaceMode,

    // ── GPU renderer slots ────────────────────────────────────────────────────
    /// vello GPU renderer (initialized when `VelloGpu` is in the pool).
    pub(crate) vello_gpu_renderer: Option<VelloRenderer>,
    /// vello hybrid renderer (lazy-init on first submit; needs texture format).
    pub(crate) vello_hybrid_renderer: Option<vello_hybrid::Renderer>,
    /// Wgpu instanced renderer (lazy-init on first submit; needs texture format).
    pub(crate) instanced_renderer: Option<InstancedRenderer>,

    // ── CPU renderer slots ────────────────────────────────────────────────────
    /// vello CPU render context.
    pub(crate) vello_cpu_ctx: Option<VelloCpuRenderContext>,
    /// tiny-skia CPU render context.
    pub(crate) tiny_skia_ctx: Option<TinySkiaCpuRenderContext>,

    // ── Canvas 2D context (wasm32 only) ───────────────────────────────────────
    /// HTML Canvas 2D render context.  Only populated when `active` is
    /// [`RenderBackend::Canvas2d`].
    #[cfg(target_arch = "wasm32")]
    pub(crate) canvas2d_ctx: Option<Canvas2dRenderContext>,

    // ── Shared vello scene ────────────────────────────────────────────────────
    /// Per-frame vello scene, reset each frame.  Shared by GPU and Hybrid.
    pub(crate) scene: Scene,

    // ── VelloHybrid per-frame context ─────────────────────────────────────────
    /// vello-hybrid per-frame render context (rebuilt each frame).
    pub(crate) vello_hybrid_ctx: VelloHybridRenderContext,

    // ── Active backend ────────────────────────────────────────────────────────
    /// Currently active backend (set by `RenderHub::set_active`).
    pub(crate) active: RenderBackend,
}

impl WindowRenderState {
    // ── Constructors ──────────────────────────────────────────────────────────

    /// Build a GPU-mode state with vello GPU renderer initialized.
    pub fn new_gpu(
        gpu_pool: GpuDevicePool,
        surface: RenderSurface<'static>,
        renderer: VelloRenderer,
        dev_id: usize,
    ) -> Self {
        Self {
            surface: SurfaceMode::Gpu { gpu_pool, surface, dev_id },
            vello_gpu_renderer: Some(renderer),
            vello_hybrid_renderer: None,
            instanced_renderer: None,
            vello_cpu_ctx: None,
            tiny_skia_ctx: None,
            #[cfg(target_arch = "wasm32")]
            canvas2d_ctx: None,
            scene: Scene::new(),
            vello_hybrid_ctx: VelloHybridRenderContext::new(1.0),
            active: RenderBackend::VelloGpu,
        }
    }

    /// Build a GPU-mode state without a vello GPU renderer.
    ///
    /// Used for `VelloHybrid` and `WgpuInstanced` where the renderer is
    /// lazy-initialized on the first submit.
    pub fn new_gpu_no_vello(
        gpu_pool: GpuDevicePool,
        surface: RenderSurface<'static>,
        dev_id: usize,
        active: RenderBackend,
        dpr: f64,
    ) -> Self {
        Self {
            surface: SurfaceMode::Gpu { gpu_pool, surface, dev_id },
            vello_gpu_renderer: None,
            vello_hybrid_renderer: None,
            instanced_renderer: None,
            vello_cpu_ctx: None,
            tiny_skia_ctx: None,
            #[cfg(target_arch = "wasm32")]
            canvas2d_ctx: None,
            scene: Scene::new(),
            vello_hybrid_ctx: VelloHybridRenderContext::new(dpr),
            active,
        }
    }

    /// Build a CPU-only (tiny-skia) state with a software presenter.
    ///
    /// `presenter` is the [`SoftwarePresenter`] obtained from
    /// [`WindowProvider::create_software_presenter`](uzor_window_hub::lifecycle::WindowProvider::create_software_presenter).
    /// It is called once per frame to blit the CPU-rasterized pixels to the OS window.
    ///
    /// Available on native targets only — use the Canvas 2D path on wasm32.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn new_cpu(width: u32, height: u32, presenter: Box<dyn SoftwarePresenter>) -> Self {
        Self {
            surface: SurfaceMode::Software { presenter, width, height },
            vello_gpu_renderer: None,
            vello_hybrid_renderer: None,
            instanced_renderer: None,
            vello_cpu_ctx: None,
            tiny_skia_ctx: Some(TinySkiaCpuRenderContext::new(width, height, 1.0)),
            scene: Scene::new(),
            vello_hybrid_ctx: VelloHybridRenderContext::new(1.0),
            active: RenderBackend::TinySkia,
        }
    }

    /// Build a CPU-only (vello-cpu) state with a software presenter.
    ///
    /// `presenter` is the [`SoftwarePresenter`] obtained from
    /// [`WindowProvider::create_software_presenter`](uzor_window_hub::lifecycle::WindowProvider::create_software_presenter).
    /// It is called once per frame to blit the CPU-rasterized pixels to the OS window.
    ///
    /// Available on native targets only — use the Canvas 2D path on wasm32.
    #[cfg(not(target_arch = "wasm32"))]
    pub fn new_vello_cpu(dpr: f64, presenter: Box<dyn SoftwarePresenter>) -> Self {
        Self {
            surface: SurfaceMode::Software { presenter, width: 0, height: 0 },
            vello_gpu_renderer: None,
            vello_hybrid_renderer: None,
            instanced_renderer: None,
            vello_cpu_ctx: Some(VelloCpuRenderContext::new(dpr)),
            tiny_skia_ctx: None,
            scene: Scene::new(),
            vello_hybrid_ctx: VelloHybridRenderContext::new(dpr),
            active: RenderBackend::VelloCpu,
        }
    }

    /// Build a GPU-mode state for vello-hybrid (renderer lazy-init).
    pub fn new_vello_hybrid(
        gpu_pool: GpuDevicePool,
        surface: RenderSurface<'static>,
        dev_id: usize,
        dpr: f64,
    ) -> Self {
        Self::new_gpu_no_vello(gpu_pool, surface, dev_id, RenderBackend::VelloHybrid, dpr)
    }

    /// Build a GPU-mode state for wgpu-instanced (renderer lazy-init).
    pub fn new_wgpu_instanced(
        gpu_pool: GpuDevicePool,
        surface: RenderSurface<'static>,
        dev_id: usize,
    ) -> Self {
        Self::new_gpu_no_vello(gpu_pool, surface, dev_id, RenderBackend::InstancedWgpu, 1.0)
    }

    /// Build a Canvas 2D state for DOM canvas rendering (wasm32 only).
    ///
    /// The `canvas` element is the HTML canvas being rendered into.
    /// The `ctx` is a [`Canvas2dRenderContext`] wrapping the
    /// `CanvasRenderingContext2d` obtained from `canvas.getContext("2d")`.
    #[cfg(target_arch = "wasm32")]
    pub fn new_canvas2d(
        canvas: web_sys::HtmlCanvasElement,
        ctx: Canvas2dRenderContext,
    ) -> Self {
        Self {
            surface: SurfaceMode::Canvas2d { canvas },
            vello_gpu_renderer: None,
            vello_hybrid_renderer: None,
            instanced_renderer: None,
            vello_cpu_ctx: None,
            tiny_skia_ctx: None,
            canvas2d_ctx: Some(ctx),
            scene: Scene::new(),
            vello_hybrid_ctx: VelloHybridRenderContext::new(1.0),
            active: RenderBackend::Canvas2d,
        }
    }

    // ── Accessors ─────────────────────────────────────────────────────────────

    /// The active [`RenderBackend`] for this window.
    pub fn backend(&self) -> RenderBackend {
        self.active
    }

    /// Set the active backend (live switching).
    ///
    /// The caller is responsible for ensuring the corresponding renderer slot
    /// is initialized before the next frame.
    pub fn set_active(&mut self, backend: RenderBackend) {
        self.active = backend;
    }

    /// Mutable reference to the vello `Scene` (used by VelloGpu / VelloHybrid).
    pub fn scene_mut(&mut self) -> Option<&mut Scene> {
        match self.active {
            RenderBackend::VelloGpu | RenderBackend::VelloHybrid => Some(&mut self.scene),
            _ => None,
        }
    }

    /// Shared reference to the vello `Scene`.
    pub fn scene(&self) -> Option<&Scene> {
        match self.active {
            RenderBackend::VelloGpu | RenderBackend::VelloHybrid => Some(&self.scene),
            _ => None,
        }
    }

    /// Mutable reference to the tiny-skia CPU context.
    pub fn cpu_ctx_mut(&mut self) -> Option<&mut TinySkiaCpuRenderContext> {
        self.tiny_skia_ctx.as_mut()
    }

    /// Shared reference to the tiny-skia CPU context.
    pub fn cpu_ctx(&self) -> Option<&TinySkiaCpuRenderContext> {
        self.tiny_skia_ctx.as_ref()
    }

    /// Mutable reference to the vello-cpu context.
    pub fn vello_cpu_ctx_mut(&mut self) -> Option<&mut VelloCpuRenderContext> {
        self.vello_cpu_ctx.as_mut()
    }

    /// Shared reference to the vello-cpu context.
    pub fn vello_cpu_ctx(&self) -> Option<&VelloCpuRenderContext> {
        self.vello_cpu_ctx.as_ref()
    }

    /// Mutable reference to the vello-hybrid per-frame context.
    pub fn vello_hybrid_ctx_mut(&mut self) -> Option<&mut VelloHybridRenderContext> {
        if matches!(self.active, RenderBackend::VelloHybrid) {
            Some(&mut self.vello_hybrid_ctx)
        } else {
            None
        }
    }

    /// Mutable reference to the Canvas 2D render context (wasm32 only).
    ///
    /// Returns `Some` only when `active` is [`RenderBackend::Canvas2d`] and
    /// the context has been initialized.
    #[cfg(target_arch = "wasm32")]
    pub fn canvas2d_ctx_mut(&mut self) -> Option<&mut Canvas2dRenderContext> {
        if matches!(self.active, RenderBackend::Canvas2d) {
            self.canvas2d_ctx.as_mut()
        } else {
            None
        }
    }

    /// Shared reference to the Canvas 2D render context (wasm32 only).
    #[cfg(target_arch = "wasm32")]
    pub fn canvas2d_ctx(&self) -> Option<&Canvas2dRenderContext> {
        if matches!(self.active, RenderBackend::Canvas2d) {
            self.canvas2d_ctx.as_ref()
        } else {
            None
        }
    }

    // ── Unified render-context accessor ──────────────────────────────────────

    /// Call `f` with a `&mut dyn RenderContext` wired to the active backend.
    ///
    /// This is the ergonomic entry point for user code inside `App::ui`.
    /// Widget L3 helpers (e.g. `register_layout_manager_button`) accept
    /// `&mut dyn RenderContext`; pass the argument you receive here directly
    /// to those helpers:
    ///
    /// ```rust,ignore
    /// fn ui(&mut self, layout: &mut LayoutManager<NoPanel>, state: &mut WindowRenderState) {
    ///     state.with_render_context(|render| {
    ///         register_layout_manager_button(layout, render, "btn", rect, &layer, &view, &settings);
    ///     });
    /// }
    /// ```
    ///
    /// Returns `None` only when the active backend is `InstancedWgpu` (which
    /// does not expose a `RenderContext`-compatible draw API) or when the
    /// corresponding context slot is uninitialised.
    pub fn with_render_context<R>(
        &mut self,
        f: impl FnOnce(&mut dyn uzor::render::RenderContext) -> R,
    ) -> Option<R> {
        match self.active {
            RenderBackend::VelloGpu | RenderBackend::VelloHybrid => {
                let mut ctx = VelloGpuRenderContext::new(&mut self.scene, 0.0, 0.0);
                Some(f(&mut ctx))
            }
            RenderBackend::VelloCpu => {
                self.vello_cpu_ctx.as_mut().map(|c| f(c))
            }
            RenderBackend::TinySkia => {
                self.tiny_skia_ctx.as_mut().map(|c| f(c))
            }
            RenderBackend::InstancedWgpu => None,
            #[cfg(target_arch = "wasm32")]
            RenderBackend::Canvas2d => {
                self.canvas2d_ctx.as_mut().map(|c| f(c))
            }
            #[cfg(not(target_arch = "wasm32"))]
            RenderBackend::Canvas2d => None,
        }
    }

    // ── Surface lifecycle ─────────────────────────────────────────────────────

    /// Resize the underlying surface to match the window's new physical size.
    ///
    /// For GPU surfaces this re-creates the wgpu swapchain. For software
    /// surfaces it forwards to `SoftwarePresenter::resize` and updates the
    /// stored `width`/`height`.  Caller is responsible for ensuring no GPU
    /// frame is in flight when this is called.
    pub fn resize_surface(&mut self, width: u32, height: u32) {
        if width == 0 || height == 0 {
            return;
        }
        match &mut self.surface {
            SurfaceMode::Gpu { gpu_pool, surface, .. } => {
                gpu_pool.resize_surface(surface, width, height);
            }
            #[cfg(not(target_arch = "wasm32"))]
            SurfaceMode::Software { presenter, width: w, height: h } => {
                presenter.resize(width, height);
                *w = width;
                *h = height;
            }
            #[cfg(target_arch = "wasm32")]
            SurfaceMode::Canvas2d { .. } => {
                // The canvas element resize is handled by the DOM layout —
                // nothing to do here.
            }
        }
    }

    // ── Frame lifecycle ───────────────────────────────────────────────────────

    /// Reset per-frame artifacts.  Call at the top of each frame.
    pub fn begin_frame(&mut self) {
        match self.active {
            RenderBackend::VelloGpu => self.scene.reset(),
            RenderBackend::VelloHybrid => {
                // vello_hybrid_ctx is rebuilt by the caller filling it each frame.
            }
            RenderBackend::VelloCpu
            | RenderBackend::TinySkia
            | RenderBackend::InstancedWgpu => {
                // CPU pixel buffers and instanced commands are rebuilt by caller.
            }
            RenderBackend::Canvas2d => {
                // Canvas 2D draw calls are issued directly via canvas2d_ctx_mut().
                // No per-frame reset needed — the browser auto-clears as needed.
            }
        }
    }
}