bevy_react_core 0.7.0

The core bridge of bevy-react (drive bevy_ui from React over an embedded V8 runtime). Apps depend on the `bevy-react` crate.
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
//! Named **offscreen render targets**: the live (or snapshot) output of a Bevy
//! camera drawing into a GPU texture, shown in the UI by any node carrying a
//! [`TargetView`] (a `<portal>` element — the `bevy_react_portal` crate — or a
//! `backgroundImage: { texture }`), so the UI can embed a minimap, a
//! picture-in-picture, or a per-item 3D preview.
//!
//! ## Ownership split
//!
//! The core owns the **texture registry** ([`RenderTargets`]) and the
//! view↔texture **binding**. The consuming app owns the cameras, meshes, and
//! render layers: it [`create`](RenderTargets::create)s a named target, spawns a
//! camera pointed at [`RenderTarget::camera_target`], tags that camera with
//! [`PortalCamera`], and (for snapshots) [`invalidate`](RenderTargets::invalidate)s
//! or [`set_mode`](RenderTargets::set_mode)s it. React never invents target names —
//! it receives them from the app over the typed event channel and echoes them back
//! as `<portal target={name} />`.
//!
//! ## Render model
//!
//! Each target is [`RenderMode::Live`] (its camera renders every frame **while a
//! `<portal>` showing it is visible** — minimaps, rotating previews; a portal that
//! is `display: none`, `Visibility::Hidden`, scrolled entirely out of its clip, or
//! unmounted costs nothing) or [`RenderMode::Snapshot`] (renders once when
//! registered or invalidated, then its camera is deactivated and the texture
//! reused — cheap for static thumbnails). [`drive_target_cameras`] toggles
//! `Camera::is_active`; [`drive_render_targets`] drives resolution.
//!
//! ## Resolution
//!
//! Each target's [`Resolution`] is [`Auto`](Resolution::Auto) (the texture is sized
//! to the binding portal's laid-out box, like the canvas — crisp output and correct
//! camera aspect for free) or [`Fixed`](Resolution::Fixed) (a fixed cost, for a
//! target shared by several portals).

use bevy::camera::visibility::InheritedVisibility;
use bevy::camera::{ImageRenderTarget, RenderTarget as BevyRenderTarget};
use bevy::image::{Image, TRANSPARENT_IMAGE_HANDLE};
use bevy::platform::collections::HashMap;
use bevy::platform::collections::HashSet;
use bevy::prelude::*;
use bevy::render::render_resource::{Extent3d, TextureFormat};
use bevy::ui::widget::ImageNode;
use bevy::ui::{CalculatedClip, ComputedNode, UiGlobalTransform};

/// Largest render-target dimension we allocate, in physical pixels — a guard
/// against a degenerate layout asking for an enormous texture.
const MAX_DIM: u32 = 2048;

/// Quantization step for [`Resolution::Auto`] sizing, in physical pixels. The
/// texture is sized to the next multiple of this, so small sub-pixel layout
/// jitter during a resize doesn't reallocate the GPU texture every frame.
const SIZE_STEP: u32 = 16;

/// How often a target's camera renders into its texture.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RenderMode {
    /// The camera renders every frame a `<portal>` showing the target is visible
    /// (minimaps, rotating/animated previews); see [`drive_target_cameras`].
    Live,
    /// The camera renders once when the target is registered or
    /// [`invalidate`](RenderTargets::invalidate)d, then deactivates and the
    /// texture is reused (static thumbnails — cheap for many slots).
    Snapshot,
}

/// How a target's texture resolution is chosen.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Resolution {
    /// Track the binding portal's laid-out physical size (crisp + correct aspect).
    /// Assumes one portal per target; with several, the last to bind wins.
    Auto,
    /// A fixed texture size, regardless of how the portal is laid out.
    Fixed(UVec2),
}

/// Parameters for [`RenderTargets::create`].
#[derive(Clone, Copy, Debug)]
pub struct RenderTargetSpec {
    /// Resolution policy (default [`Resolution::Auto`]).
    pub size: Resolution,
    /// Render model (default [`RenderMode::Live`]).
    pub mode: RenderMode,
    /// Texture format. Default [`TextureFormat::Rgba8UnormSrgb`] — display-ready
    /// for a UI thumbnail. Use an HDR format (e.g. `Rgba16Float`) if the camera
    /// needs bloom/HDR before tonemapping.
    pub format: TextureFormat,
}

impl Default for RenderTargetSpec {
    fn default() -> Self {
        Self {
            size: Resolution::Auto,
            mode: RenderMode::Live,
            format: TextureFormat::Rgba8UnormSrgb,
        }
    }
}

/// A handle to a freshly [`create`](RenderTargets::create)d target. Use
/// [`camera_target`](Self::camera_target) to point a camera at it.
#[derive(Clone, Debug)]
pub struct RenderTarget {
    /// The backing render-target image (also stored in the registry).
    pub handle: Handle<Image>,
}

impl RenderTarget {
    /// The [`bevy::camera::RenderTarget`] to set on a camera's `target`
    /// so it renders into this texture.
    pub fn camera_target(&self) -> BevyRenderTarget {
        BevyRenderTarget::Image(ImageRenderTarget {
            handle: self.handle.clone(),
            scale_factor: 1.0,
        })
    }
}

/// One registered render target.
struct Entry {
    handle: Handle<Image>,
    mode: RenderMode,
    resolution: Resolution,
    /// The portal node currently displaying this target (for [`Resolution::Auto`]).
    binder: Option<Entity>,
    /// Set when the texture should (re)render: on create, on resize, on
    /// [`invalidate`](RenderTargets::invalidate), or on a `Live → Snapshot` switch.
    dirty: bool,
    /// Last physical size we sized an [`Resolution::Auto`] texture to.
    last_size: UVec2,
}

/// The registry of named offscreen render targets. Insert it (the plugin does)
/// and have app systems [`create`](Self::create) targets as game state demands.
#[derive(Resource, Default)]
pub struct RenderTargets {
    entries: HashMap<String, Entry>,
}

impl RenderTargets {
    /// Allocate a render-target texture and register it under `name`, returning a
    /// [`RenderTarget`] whose [`camera_target`](RenderTarget::camera_target) a
    /// camera should point at. Re-creating an existing name replaces it.
    pub fn create(
        &mut self,
        images: &mut Assets<Image>,
        name: impl Into<String>,
        spec: RenderTargetSpec,
    ) -> RenderTarget {
        // An Auto target starts tiny; `drive_render_targets` resizes it to the
        // portal once laid out. A Fixed target is allocated at its final size.
        let size = match spec.size {
            Resolution::Fixed(s) => s.max(UVec2::ONE).min(UVec2::splat(MAX_DIM)),
            Resolution::Auto => UVec2::splat(SIZE_STEP),
        };
        let image = Image::new_target_texture(size.x, size.y, spec.format, None);
        let handle = images.add(image);
        self.entries.insert(
            name.into(),
            Entry {
                handle: handle.clone(),
                mode: spec.mode,
                resolution: spec.size,
                binder: None,
                dirty: true,
                last_size: size,
            },
        );
        RenderTarget { handle }
    }

    /// Register an **app-owned texture** under `name` — a procedurally
    /// generated, pre-rendered, or loaded `Image` the app already holds — so
    /// a `<portal target>` or a `backgroundImage` `{ texture }` source can
    /// display it. Static content: nothing renders into, resizes, or
    /// invalidates it (the entry is inert to [`drive_render_targets`]); for
    /// live/continuously-updating content use [`create`](Self::create) with a
    /// camera — and prefer a `<portal>` on the UI side. Re-registering an
    /// existing name replaces it.
    pub fn register(&mut self, name: impl Into<String>, handle: Handle<Image>) {
        self.entries.insert(
            name.into(),
            Entry {
                handle,
                mode: RenderMode::Snapshot,
                resolution: Resolution::Fixed(UVec2::ONE),
                binder: None,
                dirty: false,
                last_size: UVec2::ONE,
            },
        );
    }

    /// The backing texture handle for `name`, if registered.
    pub fn get(&self, name: &str) -> Option<Handle<Image>> {
        self.entries.get(name).map(|e| e.handle.clone())
    }

    /// Mark a target for one more render (a [`RenderMode::Snapshot`] re-captures;
    /// a [`RenderMode::Live`] target is unaffected — it renders every frame anyway).
    pub fn invalidate(&mut self, name: &str) {
        if let Some(e) = self.entries.get_mut(name) {
            e.dirty = true;
        }
    }

    /// Switch a target's render model at runtime. `Snapshot → Live` reactivates
    /// the camera; `Live → Snapshot` renders one last frame, then freezes.
    pub fn set_mode(&mut self, name: &str, mode: RenderMode) {
        if let Some(e) = self.entries.get_mut(name) {
            if e.mode != mode {
                e.dirty = true; // render once at the moment of the switch
            }
            e.mode = mode;
        }
    }

    /// Drop a target. The app is responsible for despawning the camera/scene it
    /// spawned for it; portals bound to the name revert to a blank placeholder.
    pub fn remove(&mut self, name: &str) {
        self.entries.remove(name);
    }
}

/// Marks a camera as the renderer for a named target, so [`drive_render_targets`]
/// can control its activity for [`RenderMode::Snapshot`]. The app inserts it on
/// the camera it spawns for a target.
#[derive(Component, Clone, Debug)]
pub struct PortalCamera(pub String);

/// Marks a node whose `ImageNode` **shows** the named render target: a
/// `<portal>` stamps it from its `target` attribute; [`bind_target_views`]
/// keeps the node's [`ImageNode`] pointed at the registry's texture for the
/// name, and [`drive_target_cameras`] runs a live target's camera only while
/// a view of it is showing.
#[derive(Component, Clone, Debug)]
pub struct TargetView(pub String);

/// Point every `<portal>`'s [`ImageNode`] at the texture for its target name (or
/// bevy's 1×1 transparent image when the name isn't registered), and record the portal as the
/// target's binder for [`Resolution::Auto`] sizing. Only writes `image` when it
/// actually changes, so it doesn't needlessly re-extract the node every frame.
///
/// This is what decouples ordering: a portal may mount before its target exists
/// and rebinds the instant it appears (and reverts to the placeholder on
/// [`remove`](RenderTargets::remove)).
pub fn bind_target_views(
    mut targets: ResMut<RenderTargets>,
    mut portals: Query<(Entity, &TargetView, &mut ImageNode)>,
) {
    for (entity, portal, mut node) in &mut portals {
        let desired = targets
            .entries
            .get(&portal.0)
            .map(|e| e.handle.clone())
            .unwrap_or(TRANSPARENT_IMAGE_HANDLE);
        if node.image != desired {
            node.image = desired;
        }
        if let Some(entry) = targets.entries.get_mut(&portal.0) {
            entry.binder = Some(entity);
        }
    }
}

/// Drive resolution each frame: for [`Resolution::Auto`] targets, size the texture
/// to the binding portal's laid-out physical size (quantized to [`SIZE_STEP`]) and
/// mark the target dirty on change. Runs in `Update`, before bevy's `camera_system`
/// reads the target's size, so the camera renders at the new size the same frame.
/// Camera activity is [`drive_target_cameras`]'s job.
pub fn drive_render_targets(
    mut targets: ResMut<RenderTargets>,
    mut images: ResMut<Assets<Image>>,
    nodes: Query<&ComputedNode>,
) {
    for entry in targets.entries.values_mut() {
        if entry.resolution != Resolution::Auto {
            continue;
        }
        let Some(binder) = entry.binder else { continue };
        let Ok(node) = nodes.get(binder) else {
            continue;
        };
        let want = quantize_size(node.size());
        if want.x == 0 || want.y == 0 || want == entry.last_size {
            continue;
        }
        if let Some(mut image) = images.get_mut(&entry.handle) {
            image.resize(Extent3d {
                width: want.x,
                height: want.y,
                depth_or_array_layers: 1,
            });
            entry.last_size = want;
            entry.dirty = true;
        }
    }
}

/// Set each [`PortalCamera`]'s `is_active` for this frame's render:
/// - [`RenderMode::Live`]: on while at least one `<portal>` bound to the target is
///   **showing** — `InheritedVisibility` visible, laid out non-empty (`display:
///   none` is empty), and not entirely outside its inherited [`CalculatedClip`]
///   (scrolled away). Nothing samples a hidden portal's texture, so its camera's
///   full render pass would be waste; an unmounted portal counts as hidden.
/// - [`RenderMode::Snapshot`]: on for exactly the frame `dirty` is cleared (create,
///   resize, [`invalidate`](RenderTargets::invalidate), mode switch), then off —
///   regardless of binders, so a re-snapshot is ready before it scrolls into view.
///
/// Scheduled in `PostUpdate` after bevy_ui's layout + clipping and bevy's
/// visibility propagation, so the gate reads **this frame's** geometry and
/// visibility, and before bevy's view culling (`CheckVisibility`) and directional
/// shadow cascade build (`UpdateDirectionalLightCascades`), which only prepare
/// cameras that are already `is_active` — a camera activated after them has no
/// cascades for extraction to read (`prepare_lights` panics) and no visible
/// entities. So a portal that becomes visible renders, fully, the same frame. [`register`](RenderTargets::register)ed
/// app-owned entries are Snapshot + never dirty: untouched.
pub fn drive_target_cameras(
    mut targets: ResMut<RenderTargets>,
    portals: Query<(
        &TargetView,
        &InheritedVisibility,
        &ComputedNode,
        &UiGlobalTransform,
        Option<&CalculatedClip>,
    )>,
    mut cameras: Query<(&PortalCamera, &mut Camera)>,
) {
    // Targets with at least one showing portal this frame.
    let mut showing: HashSet<&str> = HashSet::default();
    for (portal, visibility, node, transform, clip) in &portals {
        if visibility.get() && !node.is_empty() && !clipped_out(node, transform, clip) {
            showing.insert(portal.0.as_str());
        }
    }

    for (cam, mut camera) in &mut cameras {
        let Some(entry) = targets.entries.get_mut(&cam.0) else {
            continue;
        };
        let active = match entry.mode {
            RenderMode::Live => showing.contains(cam.0.as_str()),
            RenderMode::Snapshot => {
                // Active for exactly the frame we clear `dirty`, so the camera
                // renders once; off until the next invalidate/resize.
                let dirty = entry.dirty;
                entry.dirty = false;
                dirty
            }
        };
        if camera.is_active != active {
            camera.is_active = active;
        }
    }
}

/// Whether the node's border box lies entirely outside its inherited clip rect —
/// both in physical px, the space `CalculatedClip` and `UiGlobalTransform` share.
fn clipped_out(
    node: &ComputedNode,
    transform: &UiGlobalTransform,
    clip: Option<&CalculatedClip>,
) -> bool {
    let Some(clip) = clip else {
        return false;
    };
    let half = node.size() / 2.0;
    let corners = [
        Vec2::new(-half.x, -half.y),
        Vec2::new(half.x, -half.y),
        Vec2::new(-half.x, half.y),
        half,
    ];
    let rect = corners.iter().fold(Rect::EMPTY, |rect, corner| {
        rect.union_point(transform.transform_point2(*corner))
    });
    clip.clip.intersect(rect).is_empty()
}

/// Round a laid-out physical size up to the next [`SIZE_STEP`] multiple, clamped
/// to `[SIZE_STEP, MAX_DIM]` on each axis.
fn quantize_size(size: Vec2) -> UVec2 {
    let q = |v: f32| {
        let px = v.round().max(0.0) as u32;
        let stepped = px.div_ceil(SIZE_STEP) * SIZE_STEP;
        stepped.clamp(SIZE_STEP, MAX_DIM)
    };
    UVec2::new(q(size.x), q(size.y))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn test_app() -> App {
        let mut app = App::new();
        app.add_plugins((MinimalPlugins, AssetPlugin::default()));
        app.init_asset::<Image>();
        app.init_resource::<RenderTargets>();
        app
    }

    /// `create` registers a target and `get` returns its handle; `remove` drops it.
    #[test]
    fn create_get_remove() {
        let mut app = test_app();
        let handle = app
            .world_mut()
            .resource_scope(|world, mut targets: Mut<RenderTargets>| {
                let mut images = world.resource_mut::<Assets<Image>>();
                targets
                    .create(&mut images, "follow", RenderTargetSpec::default())
                    .handle
            });
        let targets = app.world().resource::<RenderTargets>();
        assert_eq!(targets.get("follow"), Some(handle));
        assert_eq!(targets.get("nope"), None);

        app.world_mut()
            .resource_mut::<RenderTargets>()
            .remove("follow");
        assert_eq!(app.world().resource::<RenderTargets>().get("follow"), None);
    }

    /// `register` exposes an app-owned handle under a name (static content):
    /// `get` resolves it, `drive_render_targets` leaves it untouched, and
    /// `remove` drops it.
    #[test]
    fn register_app_texture_is_inert() {
        let mut app = test_app();
        app.add_systems(Update, (drive_render_targets, drive_target_cameras).chain());
        let handle = {
            let mut images = app.world_mut().resource_mut::<Assets<Image>>();
            images.add(crate::raster::blank_image())
        };
        app.world_mut()
            .resource_mut::<RenderTargets>()
            .register("checker", handle.clone());
        assert_eq!(
            app.world().resource::<RenderTargets>().get("checker"),
            Some(handle.clone())
        );

        // A camera-less, Fixed-resolution entry: the drive system must not
        // resize or otherwise touch it.
        app.update();
        assert_eq!(
            app.world().resource::<RenderTargets>().get("checker"),
            Some(handle),
            "the registered handle survives the drive system"
        );

        app.world_mut()
            .resource_mut::<RenderTargets>()
            .remove("checker");
        assert_eq!(app.world().resource::<RenderTargets>().get("checker"), None);
    }

    /// `set_mode` flips the mode and marks dirty only when it actually changes;
    /// `invalidate` always marks dirty.
    #[test]
    fn set_mode_and_invalidate_mark_dirty() {
        let mut app = test_app();
        app.world_mut()
            .resource_scope(|world, mut targets: Mut<RenderTargets>| {
                let mut images = world.resource_mut::<Assets<Image>>();
                targets.create(
                    &mut images,
                    "follow",
                    RenderTargetSpec {
                        mode: RenderMode::Live,
                        ..default()
                    },
                );
            });

        let mut targets = app.world_mut().resource_mut::<RenderTargets>();
        // A fresh target is dirty; clear it by pretending a render happened.
        targets.entries.get_mut("follow").unwrap().dirty = false;
        targets.set_mode("follow", RenderMode::Live); // no change → still clean
        assert!(!targets.entries["follow"].dirty);
        targets.set_mode("follow", RenderMode::Snapshot); // change → dirty
        assert!(targets.entries["follow"].dirty);
        assert_eq!(targets.entries["follow"].mode, RenderMode::Snapshot);

        targets.entries.get_mut("follow").unwrap().dirty = false;
        targets.invalidate("follow");
        assert!(targets.entries["follow"].dirty);
    }

    /// `bind_target_views` points an `TargetView`'s `ImageNode` at the registered texture,
    /// records the binder, and reverts to the placeholder after the target is gone.
    #[test]
    fn bind_portals_binds_and_reverts() {
        let mut app = test_app();
        app.add_systems(Update, bind_target_views);

        let target_handle =
            app.world_mut()
                .resource_scope(|world, mut targets: Mut<RenderTargets>| {
                    let mut images = world.resource_mut::<Assets<Image>>();
                    targets
                        .create(&mut images, "follow", RenderTargetSpec::default())
                        .handle
                });
        let placeholder = TRANSPARENT_IMAGE_HANDLE;
        let portal = app
            .world_mut()
            .spawn((
                TargetView("follow".into()),
                ImageNode::new(placeholder.clone()),
            ))
            .id();

        app.update(); // bind_target_views runs
        assert_eq!(
            app.world().entity(portal).get::<ImageNode>().unwrap().image,
            target_handle,
            "portal binds to the registered target texture"
        );
        assert_eq!(
            app.world().resource::<RenderTargets>().entries["follow"].binder,
            Some(portal),
            "the portal is recorded as the target's binder"
        );

        app.world_mut()
            .resource_mut::<RenderTargets>()
            .remove("follow");
        app.update();
        assert_eq!(
            app.world().entity(portal).get::<ImageNode>().unwrap().image,
            placeholder,
            "a removed target reverts the portal to the placeholder"
        );
    }

    /// `drive_target_cameras` renders a snapshot camera for exactly one frame after
    /// it is created/invalidated (no portal need be showing).
    #[test]
    fn snapshot_camera_renders_once_then_deactivates() {
        let mut app = test_app();
        app.add_systems(Update, (drive_render_targets, drive_target_cameras).chain());
        app.world_mut()
            .resource_scope(|world, mut targets: Mut<RenderTargets>| {
                let mut images = world.resource_mut::<Assets<Image>>();
                targets.create(
                    &mut images,
                    "shot",
                    RenderTargetSpec {
                        mode: RenderMode::Snapshot,
                        ..default()
                    },
                );
            });
        let cam = app
            .world_mut()
            .spawn((PortalCamera("shot".into()), Camera::default()))
            .id();

        // Frame 1: the fresh (dirty) target activates its camera for one render.
        app.update();
        assert!(
            app.world().entity(cam).get::<Camera>().unwrap().is_active,
            "a dirty snapshot renders this frame"
        );
        // Frame 2: no longer dirty → camera deactivates.
        app.update();
        assert!(
            !app.world().entity(cam).get::<Camera>().unwrap().is_active,
            "a clean snapshot stops rendering"
        );

        // Invalidate → renders one more frame.
        app.world_mut()
            .resource_mut::<RenderTargets>()
            .invalidate("shot");
        app.update();
        assert!(
            app.world().entity(cam).get::<Camera>().unwrap().is_active,
            "invalidate re-renders the snapshot once"
        );
    }

    /// A live camera renders only while a `<portal>` showing its target is
    /// visible: mounted, `InheritedVisibility` visible, laid out non-empty, and
    /// not scrolled entirely out of its clip.
    #[test]
    fn live_camera_renders_only_while_a_portal_is_showing() {
        let mut app = test_app();
        app.add_systems(Update, (drive_render_targets, drive_target_cameras).chain());
        app.world_mut()
            .resource_scope(|world, mut targets: Mut<RenderTargets>| {
                let mut images = world.resource_mut::<Assets<Image>>();
                targets.create(&mut images, "live", RenderTargetSpec::default());
            });
        let cam = app
            .world_mut()
            .spawn((PortalCamera("live".into()), Camera::default()))
            .id();
        let active = |app: &App| app.world().entity(cam).get::<Camera>().unwrap().is_active;

        app.update();
        assert!(
            !active(&app),
            "no portal shows the target → the camera idles"
        );

        let shown = ComputedNode {
            size: Vec2::splat(64.0),
            ..default()
        };
        let portal = app
            .world_mut()
            .spawn((
                TargetView("live".into()),
                InheritedVisibility::VISIBLE,
                shown,
                UiGlobalTransform::default(),
            ))
            .id();
        app.update();
        assert!(active(&app), "a visible portal turns the camera on");

        app.world_mut()
            .entity_mut(portal)
            .insert(InheritedVisibility::HIDDEN);
        app.update();
        assert!(!active(&app), "a hidden portal turns it off");

        app.world_mut()
            .entity_mut(portal)
            .insert((InheritedVisibility::VISIBLE, ComputedNode::default()));
        app.update();
        assert!(
            !active(&app),
            "an empty (display: none) portal keeps it off"
        );

        // Node box spans (-32..32)²; a clip rect entirely to its right hides it.
        app.world_mut().entity_mut(portal).insert((
            shown,
            CalculatedClip {
                clip: Rect::new(100.0, -10.0, 200.0, 10.0),
            },
        ));
        app.update();
        assert!(
            !active(&app),
            "a portal scrolled out of its clip keeps it off"
        );

        app.world_mut().entity_mut(portal).insert(CalculatedClip {
            clip: Rect::new(0.0, 0.0, 200.0, 200.0),
        });
        app.update();
        assert!(active(&app), "a partly clipped portal turns it back on");

        app.world_mut().entity_mut(portal).despawn();
        app.update();
        assert!(!active(&app), "an unmounted portal turns it off");
    }

    #[test]
    fn quantize_rounds_up_to_step_and_clamps() {
        assert_eq!(quantize_size(Vec2::new(1.0, 1.0)), UVec2::splat(SIZE_STEP));
        assert_eq!(quantize_size(Vec2::new(17.0, 31.0)), UVec2::new(32, 32));
        assert_eq!(quantize_size(Vec2::new(0.0, 0.0)), UVec2::splat(SIZE_STEP));
        assert_eq!(
            quantize_size(Vec2::new(99999.0, 10.0)),
            UVec2::new(MAX_DIM, SIZE_STEP)
        );
    }
}