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
674
675
676
677
678
679
680
//! The imperative apply engine — [`apply_animated_nodes`], stage by stage.
//!
//! Each frame, every [`AnimatedNode`]'s bindings are resolved against the
//! shared-value table and written onto the entity's components in a fixed
//! stage order (the order is semantic — see the orchestrator body). The
//! property table (`super::props`) decides which stage owns each property;
//! this module owns the write mechanics.

use std::collections::HashMap;

use bevy::ecs::query::QueryData;
use bevy::prelude::*;
use bevy::ui::UiTransform;

use super::protocol::{AnimatableProperty, AnimatedBindings, Binding};
#[cfg(test)]
mod ext_tests;
mod filter_params;
mod gradient;
mod node_colors;
#[cfg(test)]
mod tests;

use filter_params::apply_filter_params;
use node_colors::stage_node_and_colors;

use super::{AnimatedNode, SharedValues, build_ui_transform, eval_color, eval_scalar, props};

/// The components an animated node can drive. A `QueryData` struct (rather than a
/// tuple) so a new animatable target component is one field, not a tuple-arity
/// problem. Every visual/layout target is optional except `UiTransform` (required
/// by [`AnimatedNode`]).
#[derive(QueryData)]
#[query_data(mutable)]
pub(crate) struct AnimTargets {
    transform: &'static mut UiTransform,
    bg: Option<&'static mut BackgroundColor>,
    border: Option<&'static mut BorderColor>,
    text: Option<&'static mut TextColor>,
    image: Option<&'static mut ImageNode>,
    node: Option<&'static mut Node>,
    // On a promoted layer root (see `crate::layer`) an animated `opacity`
    // drives the composite-time group alpha instead of the color folds.
    promoted: Option<&'static crate::layer::PromotedLayer>,
    layer_alpha: Option<&'static mut crate::layer::LayerGroupAlpha>,
    /// The packed filter passes per-param `filter[<i>].<param>` bindings write
    /// into. Promoted-root-only by construction: the chain only exists on
    /// promoted roots (`crate::filters::resolve_chains`).
    resolved_filter: Option<&'static mut crate::filters::ResolvedFilterChain>,
    /// The backdrop analog: `backdropFilter[<i>].<param>` bindings write into
    /// this chain (projected to the shared inner type at the call site).
    resolved_backdrop: Option<&'static mut crate::filters::ResolvedBackdropChain>,
    /// The morph analog: `morphFilter.<param>` bindings write into the
    /// resolved morph's single pass (projected like the backdrop).
    resolved_morph: Option<&'static mut crate::filters::ResolvedMorphChain>,
    /// Reconciler identity, for attributing `filterBinding` validation
    /// warnings to the node's devtools inspector.
    rnode: Option<&'static crate::bridge::ReactNode>,
    /// The composite-time 3D transform params (`transform3d.<field>` bindings
    /// overwrite single fields; `sync_transform3d_matrices` derives the
    /// matrix + composite-only dirt from the change — no dirt push here).
    transform3d: Option<&'static mut crate::layer::transform3d::LayerTransform3d>,
    /// The feature-owned bindings' publish slot — stage 5 evaluates every
    /// `Ext` binding and compare-writes the scalars here for the owning
    /// feature's consumer (see [`DrivenExtValues`](crate::ext::DrivenExtValues)).
    /// Stamped with the bindings exactly when any `Ext` binding exists.
    ext: Option<&'static mut crate::ext::DrivenExtValues>,
    /// The gradient engines' input stamp (the resolver's UNfolded lists +
    /// the static fold opacity) — stage 6's rebuild base.
    gradient_input: Option<&'static crate::ui_map::GradientTargets>,
    /// The folded surface components stage 6 compare-writes.
    bg_gradient: Option<&'static mut bevy::ui::BackgroundGradient>,
    border_gradient: Option<&'static mut bevy::ui::BorderGradient>,
}

/// The applier's wake filter: a change tick on the bindings or on any
/// component [`AnimTargets`] reads or writes (one entry per target field —
/// add the field's component here when adding a field).
type AnyTargetChanged = Or<(
    Changed<AnimatedNode>,
    Changed<UiTransform>,
    Changed<BackgroundColor>,
    Changed<BorderColor>,
    Changed<TextColor>,
    Changed<ImageNode>,
    Changed<Node>,
    Changed<crate::layer::PromotedLayer>,
    Changed<crate::layer::LayerGroupAlpha>,
    Changed<crate::filters::ResolvedFilterChain>,
    Changed<crate::filters::ResolvedBackdropChain>,
    Changed<crate::filters::ResolvedMorphChain>,
    Changed<crate::layer::transform3d::LayerTransform3d>,
    Changed<crate::ext::DrivenExtValues>,
    Or<(
        Changed<crate::ui_map::GradientTargets>,
        Changed<bevy::ui::BackgroundGradient>,
        Changed<bevy::ui::BorderGradient>,
    )>,
)>;

/// The removal half of the wake set: a target component (or the bindings)
/// vanishing since the last run — same field list as [`AnyTargetChanged`].
#[derive(bevy::ecs::system::SystemParam)]
pub(crate) struct RemovedTargets<'w, 's> {
    anim: RemovedComponents<'w, 's, AnimatedNode>,
    bg: RemovedComponents<'w, 's, BackgroundColor>,
    border: RemovedComponents<'w, 's, BorderColor>,
    text: RemovedComponents<'w, 's, TextColor>,
    image: RemovedComponents<'w, 's, ImageNode>,
    node: RemovedComponents<'w, 's, Node>,
    promoted: RemovedComponents<'w, 's, crate::layer::PromotedLayer>,
    layer_alpha: RemovedComponents<'w, 's, crate::layer::LayerGroupAlpha>,
    resolved_filter: RemovedComponents<'w, 's, crate::filters::ResolvedFilterChain>,
    resolved_backdrop: RemovedComponents<'w, 's, crate::filters::ResolvedBackdropChain>,
    resolved_morph: RemovedComponents<'w, 's, crate::filters::ResolvedMorphChain>,
    transform3d: RemovedComponents<'w, 's, crate::layer::transform3d::LayerTransform3d>,
    ext: RemovedComponents<'w, 's, crate::ext::DrivenExtValues>,
    gradient_input: RemovedComponents<'w, 's, crate::ui_map::GradientTargets>,
    bg_gradient: RemovedComponents<'w, 's, bevy::ui::BackgroundGradient>,
    border_gradient: RemovedComponents<'w, 's, bevy::ui::BorderGradient>,
}

impl RemovedTargets<'_, '_> {
    super::removed_any!(
        anim,
        bg,
        border,
        text,
        image,
        node,
        promoted,
        layer_alpha,
        resolved_filter,
        resolved_backdrop,
        resolved_morph,
        transform3d,
        ext,
        gradient_input,
        bg_gradient,
        border_gradient
    );
}

/// Bind-time validation memory for a warn-once stage: which entities'
/// bindings have been validated, each with a stamp of per-entity stage state
/// `S` whose drift re-triggers validation. Stage 4 stamps the chains'
/// POST-apply version pair (a re-resolve mismatches and re-validates; its own
/// bump doesn't — see the stamp call); the gradient stage needs no state (`S = ()`,
/// where "stamp drifted" degenerates to "not yet stamped"). One type, one
/// prune idiom, two stages.
pub(crate) struct ValidationMemory<S>(HashMap<Entity, S>);

impl<S> Default for ValidationMemory<S> {
    fn default() -> Self {
        Self(HashMap::new())
    }
}

impl<S: PartialEq> ValidationMemory<S> {
    /// Whether validation must re-run for this entity: never stamped, or the
    /// stage state drifted from the last stamp. (The caller ORs in its own
    /// binding-restamp signal.)
    pub(super) fn should_validate(&self, entity: Entity, current: &S) -> bool {
        self.0.get(&entity) != Some(current)
    }

    /// Record the post-apply state. Written when validation ran this frame
    /// (freshly validated) or when the state moved under a settled memory —
    /// so a stage's own writes never read as drift next frame.
    pub(super) fn stamp(&mut self, entity: Entity, validated_now: bool, pre: &S, post: S) {
        if validated_now || &post != pre {
            self.0.insert(entity, post);
        }
    }

    /// Drop memory for entities no longer carrying this stage's bindings
    /// (despawned, or the bindings were removed), so a later re-appearance
    /// re-validates (and re-warns) and the map stays bounded.
    pub(super) fn prune(&mut self, live: &[Entity]) {
        if self.0.len() > live.len() {
            self.0.retain(|e, _| live.contains(e));
        }
    }
}

/// Apply every animated node's bindings — the body IS the ordered stage
/// list, and the order is semantic: transform group (1), transform3d group
/// (1b), the opacity pre-resolve (stage 3's value, computed early so stage 2
/// can bake it — see the comment at the call), node fields + colors (2),
/// opacity's final alpha (3), filter/backdrop params (4), shape attrs (5),
/// gradient leaves (6 — after the opacity pre-resolve so the driven alpha
/// folds in), then the validation-memory prunes.
#[allow(clippy::type_complexity, clippy::too_many_arguments)]
pub(crate) fn apply_animated_nodes(
    mut commands: Commands,
    values: Res<SharedValues>,
    mut dirt: ResMut<crate::layer::LayerContentDirt>,
    // Bind-time validation memory for the filter-param stage: entity → the
    // chain's POST-apply version (None = no chain) as of the last frame.
    // Warnings re-fire only when the bindings restamp or the chain
    // re-resolves — never per frame: stage 4's own version bump (an actively
    // animating valid binding) is stamped back after the apply so it never
    // reads as a re-resolve.
    mut validated: Local<ValidationMemory<(Option<u32>, Option<u32>, Option<u32>)>>,
    // The gradient-leaf analog (stage 6): same degenerate `S = ()` gate —
    // the stamp is rebuilt from every gradient style change, which also
    // restamps the bindings, so no state pair is needed.
    mut gradient_validated: Local<ValidationMemory<()>>,
    // `p0`: the idle gate's wake set (see the body) — any animated node
    // whose bindings or any target component changed since this system
    // last ran. `p1`: the walk itself. A `ParamSet` because the change
    // filters read what the walk writes.
    mut queries: ParamSet<(
        Query<(), (With<AnimatedNode>, AnyTargetChanged)>,
        Query<(Entity, Ref<AnimatedNode>, AnimTargets)>,
    )>,
    mut removed: RemovedTargets,
) {
    // Idle gate: every stage is "evaluate the bindings, compare, write on a
    // difference" — when no shared value moved since the last run
    // (`SharedValues` is only marked changed by a command or a live tick —
    // see `drain_animation_commands`/`tick_animations`), no node's bindings
    // or target components changed under the last writes, and no target
    // component vanished (a removal leaves no change tick; stage 2
    // re-inserts a removed background/border), every write below would be a
    // no-op. Skipping the walk keeps the re-assert contracts intact: a
    // re-render's static snap, a promotion flip, a chain re-resolve or a
    // gradient restamp all tick a component in the wake set, and the walk
    // runs the same frame as before. The validation-memory prunes only run
    // with the walk, over the complete lists — nothing was removed on a
    // skipped frame (`RemovedComponents<AnimatedNode>` is in the wake set).
    if !values.is_changed() && queries.p0().is_empty() && !removed.any() {
        return;
    }
    let mut filter_bound: Vec<Entity> = Vec::new();
    let mut gradient_bound: Vec<Entity> = Vec::new();
    let mut query = queries.p1();
    for (entity, anim, mut t) in &mut query {
        let b = &anim.0;
        let promoted = t.promoted.is_some();

        stage_transform(entity, b, &values, promoted, &mut dirt, &mut t);
        stage_transform3d(b, &values, &mut t);

        // Opacity owns the final alpha across background/text/image (stage 3).
        // Resolved once up front so stage 2 can bake it into any color it writes —
        // otherwise the two stages would ping-pong the alpha every frame and the
        // compare-before-write guards would never settle. On a promoted layer
        // root the alpha targets the group instead: colors keep their own
        // alpha and stage 3 writes `LayerGroupAlpha`.
        let opacity_alpha = b
            .get(AnimatableProperty::Opacity)
            .and_then(|x| eval_scalar(x, &values));

        stage_node_and_colors(
            entity,
            &mut commands,
            b,
            &values,
            opacity_alpha,
            promoted,
            &mut dirt,
            &mut t,
        );
        // Stage 3 — opacity owns the final alpha.
        if let Some(alpha) = opacity_alpha {
            write_final_alpha(
                entity,
                alpha,
                promoted,
                t.layer_alpha.as_mut(),
                t.bg.as_mut(),
                t.text.as_mut(),
                t.image.as_mut(),
                &mut dirt,
            );
        }
        stage_filter_params(
            entity,
            anim.is_changed(),
            b,
            &values,
            &mut validated,
            &mut filter_bound,
            &mut dirt,
            &mut t,
        );
        stage_ext(b, &values, &mut t);
        stage_gradient_params(
            entity,
            anim.is_changed(),
            b,
            &values,
            opacity_alpha,
            promoted,
            &mut gradient_validated,
            &mut gradient_bound,
            &mut dirt,
            &mut t,
        );
    }
    validated.prune(&filter_bound);
    gradient_validated.prune(&gradient_bound);
}

/// Classify a real `UiTransform` write for the layer cache: a promoted
/// root's own pure translation only moves its composite quad — content of
/// the *enclosing* capture, not its own — while scale/rotate change the
/// captured pixels (the rect doesn't track them). Shared by stage 1 here and
/// the transition engine's transform channel (`crate::transition`): the two
/// `UiTransform` writers must classify identically.
pub(crate) fn push_transform_dirt(
    entity: Entity,
    old: &UiTransform,
    new: &UiTransform,
    promoted: bool,
    dirt: &mut crate::layer::LayerContentDirt,
) {
    let translate_only = old.scale == new.scale && old.rotation == new.rotation;
    if promoted && translate_only {
        dirt.composite_only.push(entity);
    } else {
        dirt.nodes.push(entity);
    }
}

/// Land the final opacity `alpha`: the group alpha on a promoted layer root
/// (composite-only dirt — it multiplies the cached texture at composite time;
/// it IS content of an enclosing layer, if any), else the alpha of the
/// background/text/image colors (content dirt). Compare-before-write through
/// `Deref`, so a settled alpha marks nothing changed. Shared by stage 3 here
/// and the transition engine's opacity channel: the two final-alpha writers
/// must agree.
#[allow(clippy::too_many_arguments)]
pub(crate) fn write_final_alpha(
    entity: Entity,
    alpha: f32,
    promoted: bool,
    layer_alpha: Option<&mut Mut<crate::layer::LayerGroupAlpha>>,
    bg: Option<&mut Mut<BackgroundColor>>,
    text: Option<&mut Mut<TextColor>>,
    image: Option<&mut Mut<ImageNode>>,
    dirt: &mut crate::layer::LayerContentDirt,
) {
    if promoted {
        if let Some(la) = layer_alpha
            && la.0 != alpha
        {
            la.0 = alpha;
            dirt.composite_only.push(entity);
        }
        return;
    }
    let mut wrote = false;
    if let Some(c) = bg
        && c.0.alpha() != alpha
    {
        c.0 = c.0.with_alpha(alpha);
        wrote = true;
    }
    if let Some(tc) = text
        && tc.0.alpha() != alpha
    {
        tc.0 = tc.0.with_alpha(alpha);
        wrote = true;
    }
    if let Some(img) = image
        && img.color.alpha() != alpha
    {
        img.color = img.color.with_alpha(alpha);
        wrote = true;
    }
    if wrote {
        dirt.nodes.push(entity);
    }
}

/// Stage 1 — transform group: rebuild the whole `UiTransform` from the six
/// channels each frame (unbound channels stay at identity). Grouped because
/// scale precedence (`scale` vs `scaleX`/`scaleY`) needs all channels at once.
/// Compare-before-write (here and in every stage below): the read goes
/// through `Deref` (no change mark), only the assignment through `DerefMut`
/// — so a settled binding doesn't dirty change detection every frame.
fn stage_transform(
    entity: Entity,
    b: &AnimatedBindings,
    values: &SharedValues,
    promoted: bool,
    dirt: &mut crate::layer::LayerContentDirt,
    t: &mut AnimTargetsItem,
) {
    use AnimatableProperty as P;
    if !b.has_stage(props::PropStage::Transform) {
        return;
    }
    let new = build_ui_transform(
        b.get(P::TranslateX)
            .and_then(|x| eval_scalar(x, values))
            .map(Val::Px),
        b.get(P::TranslateY)
            .and_then(|x| eval_scalar(x, values))
            .map(Val::Px),
        b.get(P::Scale).and_then(|x| eval_scalar(x, values)),
        b.get(P::ScaleX).and_then(|x| eval_scalar(x, values)),
        b.get(P::ScaleY).and_then(|x| eval_scalar(x, values)),
        // Degrees on the wire (like declarative `transform.rotate` and
        // the `transform3d` rotations), radians in `UiTransform`.
        b.get(P::Rotate)
            .and_then(|x| eval_scalar(x, values))
            .map(f32::to_radians),
    );
    if *t.transform != new {
        push_transform_dirt(entity, &t.transform, &new, promoted, dirt);
        *t.transform = new;
    }
}

/// Stage 1b — transform3d group: bound fields overwrite the current
/// params (the static style base — the transition engine parks its
/// whole channel group while any binding exists), unbound fields keep
/// it. Values arrive in the declarative wire units: px lengths,
/// DEGREES for rotations (converted to the stored radians), raw
/// scalars. No dirt push — the matrix sync detects the change.
fn stage_transform3d(b: &AnimatedBindings, values: &SharedValues, t: &mut AnimTargetsItem) {
    use AnimatableProperty as P;
    if !b.has_stage(props::PropStage::Transform3d) {
        return;
    }
    let Some(t3d) = &mut t.transform3d else {
        return;
    };
    use crate::animations::protocol::Transform3dField as F;
    use crate::protocol::animatable::Animatable::Static;
    use crate::protocol::{transform::Transform3dOrigin, units::Angle, units::Length};
    let mut new = t3d.0.clone();
    for (property, binding) in b.iter() {
        if !matches!(property, P::Transform3d(_)) {
            continue;
        }
        let Some(v) = eval_scalar(binding, values) else {
            continue;
        };
        let deg = || Some(Static(Angle::from_radians(v.to_radians())));
        let origin =
            |o: &crate::protocol::transform::Transform3d| o.origin.clone().unwrap_or_default();
        // Field writes generate from the property table's t3d rows
        // (the same rows that drive the transition channel group —
        // `angle` fields arrive as wire degrees, stored as radians;
        // `num` fields write raw, perspective included: bindings are
        // imperative, the transition engine's orthographic snap
        // doesn't apply here). Origin axes stay literal: each writes
        // its axis and preserves the other.
        macro_rules! rule {
            ($prop:tt, (t3d $f:ident num $d:tt)) => {
                if property == &$prop {
                    new.$f = Some(Static(v));
                }
            };
            ($prop:tt, (t3d $f:ident angle)) => {
                if property == &$prop {
                    new.$f = deg();
                }
            };
            ($prop:tt, (t3d_origin x)) => {
                if property == &$prop {
                    new.origin = Some(Transform3dOrigin {
                        x: Static(Length::Px(v)),
                        y: origin(&new).y,
                    });
                }
            };
            ($prop:tt, (t3d_origin y)) => {
                if property == &$prop {
                    new.origin = Some(Transform3dOrigin {
                        x: origin(&new).x,
                        y: Static(Length::Px(v)),
                    });
                }
            };
            ($prop:tt, $other:tt) => {};
        }
        macro_rules! walk {
            ($(($prop:tt, $acc:tt, $write:tt, $stage:ident, $park:ident),)*) => {
                $(rule!($prop, $acc);)*
            };
        }
        props::with_animatable_props!(walk);
    }
    if t3d.0 != new {
        t3d.0 = new;
    }
}

/// Stage 4 — per-param filter bindings (`filter[<i>].<param>`): write
/// the evaluated values straight into the resolved chain's packed
/// params (promoted-root-only by construction — the chain only exists
/// there). Values are applied in the param's wire unit: logical px for
/// `Length` slots (× `chain.scale`, the resolver's physical-px
/// rewrite), degrees for `Angle` slots (→ packed radians), raw
/// scalars, rgba via `interpolateColor` for `Color` slots. A binding
/// addresses a WIRE chain position, so it writes the named slot in
/// every pass with that `wire_index` (blur's H+V both carry `radius`).
/// Compare-before-write; a real change bumps `version` once and
/// pushes composite-only dirt — the capture holds unfiltered content,
/// so `dirt.nodes` is never touched. Because this runs every frame
/// after `resolve_chains`, a style delta that rebuilt the chain
/// mid-animation is re-asserted the same frame. While any such binding
/// exists the whole-value `filter` transition channel is parked
/// (`skip_filter` in `transition.rs`'s `drive_transitions`), so this
/// stage and that ease never interleave on one node.
#[allow(clippy::too_many_arguments)]
fn stage_filter_params(
    entity: Entity,
    anim_changed: bool,
    b: &AnimatedBindings,
    values: &SharedValues,
    validated: &mut ValidationMemory<(Option<u32>, Option<u32>, Option<u32>)>,
    filter_bound: &mut Vec<Entity>,
    dirt: &mut crate::layer::LayerContentDirt,
    t: &mut AnimTargetsItem,
) {
    let has_filter = b.has_stage(props::PropStage::Filter);
    let has_backdrop = b.has_stage(props::PropStage::Backdrop);
    let has_morph = b.has_stage(props::PropStage::Morph);
    if !(has_filter || has_backdrop || has_morph) {
        return;
    }
    filter_bound.push(entity);
    // Bind-time validation gate: warn when the bindings restamped
    // (`Ref` change tick — `apply_animated` re-inserts on prop
    // updates) or any chain re-resolved/appeared/vanished. One
    // shared gate for the three domains: the version triple is the key.
    let pre = (
        t.resolved_filter.as_ref().map(|c| c.version),
        t.resolved_backdrop.as_ref().map(|c| c.0.version),
        t.resolved_morph.as_ref().map(|c| c.0.version),
    );
    let validate = anim_changed || validated.should_validate(entity, &pre);
    if has_filter {
        apply_filter_params(
            entity,
            b,
            values,
            t.resolved_filter.as_mut(),
            t.rnode,
            validate,
            dirt,
            filter_params::ChainDomain::Filter,
        );
    }
    if has_backdrop {
        let mut backdrop = t
            .resolved_backdrop
            .as_mut()
            .map(|m| m.reborrow().map_unchanged(|b| &mut b.0));
        apply_filter_params(
            entity,
            b,
            values,
            backdrop.as_mut(),
            t.rnode,
            validate,
            dirt,
            filter_params::ChainDomain::Backdrop,
        );
    }
    if has_morph {
        let mut morph = t
            .resolved_morph
            .as_mut()
            .map(|m| m.reborrow().map_unchanged(|b| &mut b.0));
        apply_filter_params(
            entity,
            b,
            values,
            morph.as_mut(),
            t.rnode,
            validate,
            dirt,
            filter_params::ChainDomain::Morph,
        );
    }
    // Stamp the POST-write versions: the applies above bump `version`
    // themselves on a changed frame, and stamping the pre-write value
    // would make that bump look like a re-resolve next frame —
    // re-warning invalid bindings every animated frame. A real
    // re-resolve (the resolver runs before this stage) still lands
    // between this read and the next frame's `pre`, so it mismatches
    // and re-validates.
    let post = (
        t.resolved_filter.as_ref().map(|c| c.version),
        t.resolved_backdrop.as_ref().map(|c| c.0.version),
        t.resolved_morph.as_ref().map(|c| c.0.version),
    );
    validated.stamp(entity, validate, &pre, post);
}

/// Stage 5 — feature-owned bindings (`Ext { domain, name }`): evaluate each
/// against the shared values and **publish** the results into the entity's
/// [`DrivenExtValues`](crate::ext::DrivenExtValues), compare-before-write
/// (a settled frame never ticks it). The binding picks the kind: an
/// `interpolateColor` publishes a color, anything else a scalar. The owning
/// feature's consumer system — ordered after `AnimationSet::Apply`, so the
/// value lands the same frame — writes them where they belong and validates
/// its own bindings (the core knows nothing about the domain's fields, so a
/// color bound to a numeric field is the consumer's warning to give). A
/// missing shared value publishes nothing; the consumer sees the gap.
/// Nothing is dirtied here: the consumer's write is the repaint signal.
fn stage_ext(b: &AnimatedBindings, values: &SharedValues, t: &mut AnimTargetsItem) {
    use crate::ext::{DrivenExt, DrivenValue};
    let Some(ext) = t.ext.as_mut() else {
        return; // Stamped exactly when an `Ext` binding exists.
    };
    let next: Vec<DrivenExt> = b
        .iter()
        .filter_map(|(property, binding)| {
            let AnimatableProperty::Ext { domain, name } = property else {
                return None;
            };
            let value = match binding {
                Binding::InterpolateColor { .. } => {
                    DrivenValue::Color(eval_color(binding, values)?)
                }
                _ => DrivenValue::Scalar(eval_scalar(binding, values)?),
            };
            Some(DrivenExt {
                domain,
                name: name.clone(),
                value,
            })
        })
        .collect();
    // One `deref_mut`, only on a real change.
    if ext.0 != next {
        ext.0 = next;
    }
}

/// Stage 6 — gradient-leaf bindings (`backgroundGradient[<i>]` /
/// `borderGradient[<i>]` leaves): rebuild each bound surface's folded
/// component from the `GradientTargets` stamp with the driven leaves
/// overwritten, fold opacity (the driven alpha when unpromoted, else the
/// stamp's static fold), and compare-write — content dirt on a real change
/// (gradients are captured pixels). See `gradient` for the unit contract
/// and the defensive validation (`gradientBinding`, warn once per
/// restamp). While any gradient binding exists that surface's whole-value
/// transition channel is parked (`ChannelId::{Background,Border}Gradient`).
#[allow(clippy::too_many_arguments)]
fn stage_gradient_params(
    entity: Entity,
    anim_changed: bool,
    b: &AnimatedBindings,
    values: &SharedValues,
    opacity_alpha: Option<f32>,
    promoted: bool,
    gradient_validated: &mut ValidationMemory<()>,
    gradient_bound: &mut Vec<Entity>,
    dirt: &mut crate::layer::LayerContentDirt,
    t: &mut AnimTargetsItem,
) {
    if !b.has_stage(props::PropStage::Gradient) {
        return;
    }
    gradient_bound.push(entity);
    let validate = anim_changed || gradient_validated.should_validate(entity, &());
    gradient::apply_gradient_params(
        entity,
        b,
        values,
        t.gradient_input,
        t.bg_gradient.as_mut(),
        t.border_gradient.as_mut(),
        opacity_alpha,
        promoted,
        t.rnode,
        validate,
        dirt,
    );
    gradient_validated.stamp(entity, validate, &(), ());
}