feature: data binding keyframes (#13097) 864d68d032 feature: add support for data binding keyframes Co-authored-by: hernan <hernan@rive.app>
diff --git a/.rive_head b/.rive_head index 7bd4a76..5b0c429 100644 --- a/.rive_head +++ b/.rive_head
@@ -1 +1 @@ -e94936fac8f750b763db4255ac2e5a3787f43ac2 +864d68d032e9a63589285a9ba8aaa87ba763a9f9
diff --git a/dev/defs/animation/keyframe_bool.json b/dev/defs/animation/keyframe_bool.json index bdf1d68..dc7e46d 100644 --- a/dev/defs/animation/keyframe_bool.json +++ b/dev/defs/animation/keyframe_bool.json
@@ -13,7 +13,8 @@ "key": { "int": 181, "string": "value" - } + }, + "bindable": true } } } \ No newline at end of file
diff --git a/dev/defs/animation/keyframe_color.json b/dev/defs/animation/keyframe_color.json index c456254..c549c88 100644 --- a/dev/defs/animation/keyframe_color.json +++ b/dev/defs/animation/keyframe_color.json
@@ -12,7 +12,8 @@ "key": { "int": 88, "string": "value" - } + }, + "bindable": true } } } \ No newline at end of file
diff --git a/dev/defs/animation/keyframe_double.json b/dev/defs/animation/keyframe_double.json index 4ea3405..87a8b52 100644 --- a/dev/defs/animation/keyframe_double.json +++ b/dev/defs/animation/keyframe_double.json
@@ -12,7 +12,8 @@ "key": { "int": 70, "string": "value" - } + }, + "bindable": true } } } \ No newline at end of file
diff --git a/dev/defs/animation/keyframe_string.json b/dev/defs/animation/keyframe_string.json index c4b301a..ca8ca29 100644 --- a/dev/defs/animation/keyframe_string.json +++ b/dev/defs/animation/keyframe_string.json
@@ -13,7 +13,8 @@ "key": { "int": 280, "string": "value" - } + }, + "bindable": true } } } \ No newline at end of file
diff --git a/include/rive/animation/animation_state_instance.hpp b/include/rive/animation/animation_state_instance.hpp index bab0ade..0937a29 100644 --- a/include/rive/animation/animation_state_instance.hpp +++ b/include/rive/animation/animation_state_instance.hpp
@@ -36,6 +36,12 @@ { return &m_AnimationInstance; } + + void forEachAnimationInstance( + const std::function<void(LinearAnimationInstance*)>& callback) override + { + callback(&m_AnimationInstance); + } }; } // namespace rive #endif \ No newline at end of file
diff --git a/include/rive/animation/blend_state_instance.hpp b/include/rive/animation/blend_state_instance.hpp index dcaa1ba..42005d4 100644 --- a/include/rive/animation/blend_state_instance.hpp +++ b/include/rive/animation/blend_state_instance.hpp
@@ -105,6 +105,15 @@ } } + void forEachAnimationInstance( + const std::function<void(LinearAnimationInstance*)>& callback) override + { + for (auto& animation : m_AnimationInstances) + { + callback(&animation.m_AnimationInstance); + } + } + // Find the animationInstance that corresponds to the blendAnimation. const LinearAnimationInstance* animationInstance( const BlendAnimation* blendAnimation) const
diff --git a/include/rive/animation/interpolating_keyframe.hpp b/include/rive/animation/interpolating_keyframe.hpp index 7684604..9cbc485 100644 --- a/include/rive/animation/interpolating_keyframe.hpp +++ b/include/rive/animation/interpolating_keyframe.hpp
@@ -19,7 +19,10 @@ KeyFrameInterpolator* effectiveInterpolator( const LinearAnimationInstance* context) const; - virtual void apply(Core* object, int propertyKey, float mix) = 0; + virtual void apply(Core* object, + int propertyKey, + float mix, + const LinearAnimationInstance* context = nullptr) = 0; virtual void applyInterpolation( Core* object, int propertyKey,
diff --git a/include/rive/animation/keyed_property.hpp b/include/rive/animation/keyed_property.hpp index 35a9859..8e4dbae 100644 --- a/include/rive/animation/keyed_property.hpp +++ b/include/rive/animation/keyed_property.hpp
@@ -42,6 +42,12 @@ return nullptr; } + size_t numKeyFrames() const { return m_keyFrames.size(); } + KeyFrame* getKeyFrame(size_t index) const + { + return index < m_keyFrames.size() ? m_keyFrames[index].get() : nullptr; + } + private: int closestFrameIndex(float seconds, int exactOffset = 0) const; std::vector<std::unique_ptr<KeyFrame>> m_keyFrames;
diff --git a/include/rive/animation/keyframe_bool.hpp b/include/rive/animation/keyframe_bool.hpp index fa993d8..7c628bd 100644 --- a/include/rive/animation/keyframe_bool.hpp +++ b/include/rive/animation/keyframe_bool.hpp
@@ -7,7 +7,10 @@ class KeyFrameBool : public KeyFrameBoolBase { public: - void apply(Core* object, int propertyKey, float mix) override; + void apply(Core* object, + int propertyKey, + float mix, + const LinearAnimationInstance* context = nullptr) override; void applyInterpolation( Core* object, int propertyKey, @@ -15,6 +18,10 @@ const KeyFrame* nextFrame, float mix, const LinearAnimationInstance* context = nullptr) override; + + // Returns the data-bound value for this keyframe in the given instance + // context if one exists, otherwise the authored value(). + bool effectiveValue(const LinearAnimationInstance* context) const; }; } // namespace rive
diff --git a/include/rive/animation/keyframe_color.hpp b/include/rive/animation/keyframe_color.hpp index 1b858d7..28416ed 100644 --- a/include/rive/animation/keyframe_color.hpp +++ b/include/rive/animation/keyframe_color.hpp
@@ -6,7 +6,10 @@ class KeyFrameColor : public KeyFrameColorBase { public: - void apply(Core* object, int propertyKey, float mix) override; + void apply(Core* object, + int propertyKey, + float mix, + const LinearAnimationInstance* context = nullptr) override; void applyInterpolation( Core* object, int propertyKey, @@ -14,6 +17,10 @@ const KeyFrame* nextFrame, float mix, const LinearAnimationInstance* context = nullptr) override; + + // Returns the data-bound value for this keyframe in the given instance + // context if one exists, otherwise the authored value(). + int effectiveValue(const LinearAnimationInstance* context) const; }; } // namespace rive
diff --git a/include/rive/animation/keyframe_double.hpp b/include/rive/animation/keyframe_double.hpp index ba27c12..d2f1b3b 100644 --- a/include/rive/animation/keyframe_double.hpp +++ b/include/rive/animation/keyframe_double.hpp
@@ -6,7 +6,10 @@ class KeyFrameDouble : public KeyFrameDoubleBase { public: - void apply(Core* object, int propertyKey, float mix) override; + void apply(Core* object, + int propertyKey, + float mix, + const LinearAnimationInstance* context = nullptr) override; void applyInterpolation( Core* object, int propertyKey, @@ -14,6 +17,10 @@ const KeyFrame* nextFrame, float mix, const LinearAnimationInstance* context = nullptr) override; + + // Returns the data-bound value for this keyframe in the given instance + // context if one exists, otherwise the authored value(). + float effectiveValue(const LinearAnimationInstance* context) const; }; } // namespace rive
diff --git a/include/rive/animation/keyframe_id.hpp b/include/rive/animation/keyframe_id.hpp index 399f30c..5398601 100644 --- a/include/rive/animation/keyframe_id.hpp +++ b/include/rive/animation/keyframe_id.hpp
@@ -7,7 +7,10 @@ class KeyFrameId : public KeyFrameIdBase { public: - void apply(Core* object, int propertyKey, float mix) override; + void apply(Core* object, + int propertyKey, + float mix, + const LinearAnimationInstance* context = nullptr) override; void applyInterpolation( Core* object, int propertyKey,
diff --git a/include/rive/animation/keyframe_string.hpp b/include/rive/animation/keyframe_string.hpp index a62d452..1910385 100644 --- a/include/rive/animation/keyframe_string.hpp +++ b/include/rive/animation/keyframe_string.hpp
@@ -7,7 +7,10 @@ class KeyFrameString : public KeyFrameStringBase { public: - void apply(Core* object, int propertyKey, float mix) override; + void apply(Core* object, + int propertyKey, + float mix, + const LinearAnimationInstance* context = nullptr) override; void applyInterpolation( Core* object, int propertyKey, @@ -15,6 +18,11 @@ const KeyFrame* nextFrame, float mix, const LinearAnimationInstance* context = nullptr) override; + + // Returns the data-bound value for this keyframe in the given instance + // context if one exists, otherwise the authored value(). + const std::string& effectiveValue( + const LinearAnimationInstance* context) const; }; } // namespace rive
diff --git a/include/rive/animation/keyframe_uint.hpp b/include/rive/animation/keyframe_uint.hpp index 62e0e26..783a527 100644 --- a/include/rive/animation/keyframe_uint.hpp +++ b/include/rive/animation/keyframe_uint.hpp
@@ -7,7 +7,10 @@ class KeyFrameUint : public KeyFrameUintBase { public: - void apply(Core* object, int propertyKey, float mix) override; + void apply(Core* object, + int propertyKey, + float mix, + const LinearAnimationInstance* context = nullptr) override; void applyInterpolation( Core* object, int propertyKey,
diff --git a/include/rive/animation/linear_animation_instance.hpp b/include/rive/animation/linear_animation_instance.hpp index 086a5aa..88adeee 100644 --- a/include/rive/animation/linear_animation_instance.hpp +++ b/include/rive/animation/linear_animation_instance.hpp
@@ -16,6 +16,8 @@ class InterpolatingKeyFrame; class ScriptedInterpolator; class DataBind; +class KeyFrame; +class BindableProperty; class LinearAnimationInstance : public Scene, public NestedEventNotifier { @@ -36,6 +38,16 @@ // Returns a pointer to the instance's animation const LinearAnimation* animation() const { return m_animation; } + // Per-instance holder that receives the data-bound value for a keyframe in + // this animation instance. Populated by StateMachineInstance when the + // owning state instance is created (only state-machine-driven LAIs are + // bound); the cloned data bind targets the holder, and keyframes read it + // via effectiveValue(context). The holder is owned by this LAI and freed in + // the destructor. + void addKeyFrameValueHolder(const KeyFrame* keyframe, + BindableProperty* holder); + BindableProperty* keyFrameValueHolder(const KeyFrame* keyframe) const; + // Returns the current point in time at which this instance has advance // to float time() const { return m_time; } @@ -158,6 +170,16 @@ // Object call (addDataBind only ever appends). `mutable` so it can // populate from the const apply() path. Not copied by the copy ctor. mutable std::vector<DataBind*> m_clonedArtboardDataBinds; + + // Per-keyframe holders receiving data-bound values for this instance. Keyed + // by the shared KeyFrame*. Owned here and deleted in the destructor (after + // the StateMachineInstance has removed the data binds that target them). + // Lazy unique_ptr => the common case (no bound keyframes) is an 8 B null + // pointer + a single nullptr check on the apply hot path, instead of an + // inline empty map. Mirrors m_scriptedInterpolatorInstances above. + // Not copied by the copy ctor — a copied LAI starts unbound. + std::unique_ptr<std::unordered_map<const KeyFrame*, BindableProperty*>> + m_keyFrameValueHolders; }; } // namespace rive #endif
diff --git a/include/rive/animation/state_instance.hpp b/include/rive/animation/state_instance.hpp index 064ca6d..0ba43b1 100644 --- a/include/rive/animation/state_instance.hpp +++ b/include/rive/animation/state_instance.hpp
@@ -3,6 +3,7 @@ #include <string> #include <stddef.h> +#include <functional> #include "rive/rive_types.hpp" #include "rive/span.hpp" @@ -11,6 +12,7 @@ class LayerState; class StateMachineInstance; class ArtboardInstance; +class LinearAnimationInstance; /// Represents an instance of a state tracked by the State Machine. class StateInstance @@ -30,6 +32,14 @@ virtual bool keepGoing() const = 0; virtual void clearSpilledTime() {} + /// Invokes [callback] for each LinearAnimationInstance this state drives. + /// Used by StateMachineInstance to build/tear down keyframe value data + /// binds over the lifetime of the state instance. Default is a no-op for + /// states with no animation (entry/exit/any). + virtual void forEachAnimationInstance( + const std::function<void(LinearAnimationInstance*)>& callback) + {} + const LayerState* state() const; }; } // namespace rive
diff --git a/include/rive/animation/state_machine_instance.hpp b/include/rive/animation/state_machine_instance.hpp index 8e4a6d6..ea94d03 100644 --- a/include/rive/animation/state_machine_instance.hpp +++ b/include/rive/animation/state_machine_instance.hpp
@@ -47,6 +47,7 @@ class EventReport; class DataBind; class BindableProperty; +class StateInstance; class HitDrawable; class ListenerViewModel; class ScriptedListenerAction; @@ -240,6 +241,19 @@ BindablePropertyNumber* findTransitionPropertyInstance( const StateTransition* transition, uint32_t propertyKey) const; + + /// Builds keyframe-value data binds for every LinearAnimationInstance the + /// given state instance drives: clones each keyframe-targeting DataBind + /// from the source artboard, creates a per-LAI holder for the keyframe + /// value, reroutes the clone to the holder, and adds it to this state + /// machine's data bind container so it advances each frame. No-op for + /// states without bound keyframes. Called when a state instance is created. + void buildStateKeyFrameBinds(StateInstance* stateInstance); + /// Removes and deletes the keyframe-value data binds created for the given + /// state instance. Called before the state instance (and its LAIs/holders) + /// are destroyed. + void removeStateKeyFrameBinds(StateInstance* stateInstance); + bool hasListeners() { return m_hitComponents.size() > 0; } bool hasFocusNodes(); bool focusNext(); @@ -396,6 +410,12 @@ std::unordered_map<const Core*, std::unordered_map<uint32_t, BindablePropertyNumber*>> m_transitionPropertyInstances; + /// Keyframe-value data binds cloned per state instance, keyed by the + /// StateInstance whose LinearAnimationInstance(s) own the target holders. + /// Owned by this state machine's data bind container; built when a state + /// instance is created and removed+deleted when it is destroyed. + std::unordered_map<StateInstance*, std::vector<DataBind*>> + m_stateKeyFrameDataBinds; uint8_t m_drawOrderChangeCounter = 0; void unbind(); void removeEventListeners();
diff --git a/include/rive/artboard.hpp b/include/rive/artboard.hpp index 25e9f6c..e2f6cb5 100644 --- a/include/rive/artboard.hpp +++ b/include/rive/artboard.hpp
@@ -25,6 +25,7 @@ #include "rive/lua/scripting_vm.hpp" #include <queue> +#include <unordered_map> #include <unordered_set> #include <vector>
diff --git a/src/animation/keyed_property.cpp b/src/animation/keyed_property.cpp index 1883f98..12f7d3d 100644 --- a/src/animation/keyed_property.cpp +++ b/src/animation/keyed_property.cpp
@@ -118,7 +118,7 @@ if (idx == 0) { static_cast<InterpolatingKeyFrame*>(m_keyFrames[0].get()) - ->apply(object, pk, actualMix); + ->apply(object, pk, actualMix, context); } else { @@ -130,13 +130,13 @@ static_cast<InterpolatingKeyFrame*>(m_keyFrames[idx].get()); if (seconds == toFrame->seconds()) { - toFrame->apply(object, pk, actualMix); + toFrame->apply(object, pk, actualMix, context); } else { if (fromFrame->interpolationType() == 0) { - fromFrame->apply(object, pk, actualMix); + fromFrame->apply(object, pk, actualMix, context); } else { @@ -152,7 +152,7 @@ else { static_cast<InterpolatingKeyFrame*>(m_keyFrames[idx - 1].get()) - ->apply(object, pk, actualMix); + ->apply(object, pk, actualMix, context); } } }
diff --git a/src/animation/keyframe_bool.cpp b/src/animation/keyframe_bool.cpp index 2e69ec5..43d1cf0 100644 --- a/src/animation/keyframe_bool.cpp +++ b/src/animation/keyframe_bool.cpp
@@ -1,11 +1,28 @@ #include "rive/animation/keyframe_bool.hpp" #include "rive/generated/core_registry.hpp" +#include "rive/animation/linear_animation_instance.hpp" +#include "rive/data_bind/bindable_property_boolean.hpp" using namespace rive; -void KeyFrameBool::apply(Core* object, int propertyKey, float mix) +bool KeyFrameBool::effectiveValue(const LinearAnimationInstance* context) const { - CoreRegistry::setBool(object, propertyKey, value()); + if (context != nullptr) + { + if (auto* holder = context->keyFrameValueHolder(this)) + { + return holder->as<BindablePropertyBoolean>()->propertyValue(); + } + } + return value(); +} + +void KeyFrameBool::apply(Core* object, + int propertyKey, + float mix, + const LinearAnimationInstance* context) +{ + CoreRegistry::setBool(object, propertyKey, effectiveValue(context)); } void KeyFrameBool::applyInterpolation(Core* object, @@ -15,6 +32,5 @@ float mix, const LinearAnimationInstance* context) { - (void)context; - CoreRegistry::setBool(object, propertyKey, value()); + CoreRegistry::setBool(object, propertyKey, effectiveValue(context)); } \ No newline at end of file
diff --git a/src/animation/keyframe_color.cpp b/src/animation/keyframe_color.cpp index 91ec544..70fc4b0 100644 --- a/src/animation/keyframe_color.cpp +++ b/src/animation/keyframe_color.cpp
@@ -1,6 +1,8 @@ #include "rive/animation/keyframe_color.hpp" #include "rive/generated/core_registry.hpp" #include "rive/shapes/paint/color.hpp" +#include "rive/animation/linear_animation_instance.hpp" +#include "rive/data_bind/bindable_property_color.hpp" using namespace rive; @@ -18,9 +20,24 @@ } } -void KeyFrameColor::apply(Core* object, int propertyKey, float mix) +int KeyFrameColor::effectiveValue(const LinearAnimationInstance* context) const { - applyColor(object, propertyKey, mix, value()); + if (context != nullptr) + { + if (auto* holder = context->keyFrameValueHolder(this)) + { + return holder->as<BindablePropertyColor>()->propertyValue(); + } + } + return value(); +} + +void KeyFrameColor::apply(Core* object, + int propertyKey, + float mix, + const LinearAnimationInstance* context) +{ + applyColor(object, propertyKey, mix, effectiveValue(context)); } void KeyFrameColor::applyInterpolation(Core* object, @@ -32,6 +49,8 @@ { auto kfc = nextFrame->as<KeyFrameColor>(); const KeyFrameColor& nextColor = *kfc; + int fromValue = effectiveValue(context); + int toValue = nextColor.effectiveValue(context); float f = (currentTime - seconds()) / (nextColor.seconds() - seconds()); if (KeyFrameInterpolator* keyframeInterpolator = @@ -40,8 +59,5 @@ f = keyframeInterpolator->transform(f); } - applyColor(object, - propertyKey, - mix, - colorLerp(value(), nextColor.value(), f)); + applyColor(object, propertyKey, mix, colorLerp(fromValue, toValue, f)); } \ No newline at end of file
diff --git a/src/animation/keyframe_double.cpp b/src/animation/keyframe_double.cpp index 1ee3749..7e4c5b0 100644 --- a/src/animation/keyframe_double.cpp +++ b/src/animation/keyframe_double.cpp
@@ -1,5 +1,7 @@ #include "rive/animation/keyframe_double.hpp" #include "rive/generated/core_registry.hpp" +#include "rive/animation/linear_animation_instance.hpp" +#include "rive/data_bind/bindable_property_number.hpp" using namespace rive; @@ -24,9 +26,25 @@ } } -void KeyFrameDouble::apply(Core* object, int propertyKey, float mix) +float KeyFrameDouble::effectiveValue( + const LinearAnimationInstance* context) const { - applyDouble(object, propertyKey, mix, value()); + if (context != nullptr) + { + if (auto* holder = context->keyFrameValueHolder(this)) + { + return holder->as<BindablePropertyNumber>()->propertyValue(); + } + } + return value(); +} + +void KeyFrameDouble::apply(Core* object, + int propertyKey, + float mix, + const LinearAnimationInstance* context) +{ + applyDouble(object, propertyKey, mix, effectiveValue(context)); } void KeyFrameDouble::applyInterpolation(Core* object, @@ -38,19 +56,20 @@ { auto kfd = nextFrame->as<KeyFrameDouble>(); const KeyFrameDouble& nextDouble = *kfd; + float fromValue = effectiveValue(context); + float toValue = nextDouble.effectiveValue(context); float f = (currentTime - seconds()) / (nextDouble.seconds() - seconds()); float frameValue; if (KeyFrameInterpolator* keyframeInterpolator = effectiveInterpolator(context)) { - frameValue = keyframeInterpolator->transformValue(value(), - nextDouble.value(), - f); + frameValue = + keyframeInterpolator->transformValue(fromValue, toValue, f); } else { - frameValue = value() + (nextDouble.value() - value()) * f; + frameValue = fromValue + (toValue - fromValue) * f; } applyDouble(object, propertyKey, mix, frameValue);
diff --git a/src/animation/keyframe_id.cpp b/src/animation/keyframe_id.cpp index a1aabd7..3b05227 100644 --- a/src/animation/keyframe_id.cpp +++ b/src/animation/keyframe_id.cpp
@@ -3,8 +3,12 @@ using namespace rive; -void KeyFrameId::apply(Core* object, int propertyKey, float mix) +void KeyFrameId::apply(Core* object, + int propertyKey, + float mix, + const LinearAnimationInstance* context) { + (void)context; CoreRegistry::setUint(object, propertyKey, value()); }
diff --git a/src/animation/keyframe_string.cpp b/src/animation/keyframe_string.cpp index caa4e20..0644090 100644 --- a/src/animation/keyframe_string.cpp +++ b/src/animation/keyframe_string.cpp
@@ -1,11 +1,29 @@ #include "rive/animation/keyframe_string.hpp" #include "rive/generated/core_registry.hpp" +#include "rive/animation/linear_animation_instance.hpp" +#include "rive/data_bind/bindable_property_string.hpp" using namespace rive; -void KeyFrameString::apply(Core* object, int propertyKey, float mix) +const std::string& KeyFrameString::effectiveValue( + const LinearAnimationInstance* context) const { - CoreRegistry::setString(object, propertyKey, value()); + if (context != nullptr) + { + if (auto* holder = context->keyFrameValueHolder(this)) + { + return holder->as<BindablePropertyString>()->propertyValue(); + } + } + return value(); +} + +void KeyFrameString::apply(Core* object, + int propertyKey, + float mix, + const LinearAnimationInstance* context) +{ + CoreRegistry::setString(object, propertyKey, effectiveValue(context)); } void KeyFrameString::applyInterpolation(Core* object, @@ -15,6 +33,5 @@ float mix, const LinearAnimationInstance* context) { - (void)context; - CoreRegistry::setString(object, propertyKey, value()); + CoreRegistry::setString(object, propertyKey, effectiveValue(context)); } \ No newline at end of file
diff --git a/src/animation/keyframe_uint.cpp b/src/animation/keyframe_uint.cpp index 4268f9f..f4e0fa8 100644 --- a/src/animation/keyframe_uint.cpp +++ b/src/animation/keyframe_uint.cpp
@@ -3,8 +3,12 @@ using namespace rive; -void KeyFrameUint::apply(Core* object, int propertyKey, float mix) +void KeyFrameUint::apply(Core* object, + int propertyKey, + float mix, + const LinearAnimationInstance* context) { + (void)context; CoreRegistry::setUint(object, propertyKey, value()); }
diff --git a/src/animation/linear_animation_instance.cpp b/src/animation/linear_animation_instance.cpp index 623c2ab..cec1db9 100644 --- a/src/animation/linear_animation_instance.cpp +++ b/src/animation/linear_animation_instance.cpp
@@ -5,6 +5,7 @@ #include "rive/animation/keyed_callback_reporter.hpp" #include "rive/assets/script_asset.hpp" #include "rive/data_bind/data_bind.hpp" +#include "rive/data_bind/bindable_property.hpp" #include "rive/profiler/profiler_macros.h" #include "rive/scripted/scripted_interpolator.hpp" @@ -62,6 +63,41 @@ m_clonedArtboardDataBinds.clear(); // m_scriptedInterpolatorInstances destructs here via unique_ptr; safe now // that no DataBind still points at the clones' CustomPropertys. + + // Keyframe value holders are owned here. The StateMachineInstance has + // already removed+deleted the data binds that target them (on + // state-instance removal, or via deleteDataBinds() before the layers in its + // destructor), so deleting the holders now is safe. The unique_ptr frees + // the map itself. + if (m_keyFrameValueHolders != nullptr) + { + for (auto& pair : *m_keyFrameValueHolders) + { + delete pair.second; + } + } +} + +void LinearAnimationInstance::addKeyFrameValueHolder(const KeyFrame* keyframe, + BindableProperty* holder) +{ + if (m_keyFrameValueHolders == nullptr) + { + m_keyFrameValueHolders = std::make_unique< + std::unordered_map<const KeyFrame*, BindableProperty*>>(); + } + (*m_keyFrameValueHolders)[keyframe] = holder; +} + +BindableProperty* LinearAnimationInstance::keyFrameValueHolder( + const KeyFrame* keyframe) const +{ + if (m_keyFrameValueHolders == nullptr) + { + return nullptr; + } + auto it = m_keyFrameValueHolders->find(keyframe); + return it != m_keyFrameValueHolders->end() ? it->second : nullptr; } // Returns a per-(this LAI, keyframe) stateful clone of the given shared
diff --git a/src/animation/state_machine_instance.cpp b/src/animation/state_machine_instance.cpp index 9afa31e..c4f3f23 100644 --- a/src/animation/state_machine_instance.cpp +++ b/src/animation/state_machine_instance.cpp
@@ -4,6 +4,20 @@ #include "rive/animation/animation_state.hpp" #include "rive/animation/any_state.hpp" #include "rive/animation/keyframe_interpolator.hpp" +#include "rive/animation/keyframe.hpp" +#include "rive/animation/keyframe_double.hpp" +#include "rive/animation/keyframe_color.hpp" +#include "rive/animation/keyframe_bool.hpp" +#include "rive/animation/keyframe_string.hpp" +#include "rive/animation/keyed_object.hpp" +#include "rive/animation/keyed_property.hpp" +#include "rive/animation/linear_animation.hpp" +#include "rive/animation/linear_animation_instance.hpp" +#include "rive/data_bind/bindable_property_number.hpp" +#include "rive/data_bind/bindable_property_color.hpp" +#include "rive/data_bind/bindable_property_boolean.hpp" +#include "rive/data_bind/bindable_property_string.hpp" +#include "rive/data_bind/converters/data_converter.hpp" #include "rive/animation/entry_state.hpp" #include "rive/animation/exit_state.hpp" #include "rive/animation/layer_state_flags.hpp" @@ -155,6 +169,7 @@ assert(m_layer == nullptr); m_anyStateInstance = layer->anyState()->makeInstance(instance).release(); + stateMachineInstance->buildStateKeyFrameBinds(m_anyStateInstance); m_layer = layer; changeState(m_layer->entryState()); } @@ -163,11 +178,13 @@ { if (m_stateFrom != m_anyStateInstance && m_stateFrom != m_currentState) { + m_stateMachineInstance->removeStateKeyFrameBinds(m_stateFrom); delete m_stateFrom; } m_stateFrom = nullptr; if (m_currentState != m_anyStateInstance) { + m_stateMachineInstance->removeStateKeyFrameBinds(m_currentState); delete m_currentState; } m_currentState = nullptr; @@ -383,6 +400,7 @@ // Fire start events for the state we're changing to. if (m_currentState != nullptr) { + m_stateMachineInstance->buildStateKeyFrameBinds(m_currentState); fireEvents(StateMachineFireOccurance::atStart, m_currentState->state()->events()); performListenerActions(StateMachineFireOccurance::atStart, @@ -555,6 +573,7 @@ if (m_stateFrom != m_anyStateInstance) { // Old state from is done. + m_stateMachineInstance->removeStateKeyFrameBinds(m_stateFrom); delete m_stateFrom; } m_stateFrom = outState; @@ -2148,6 +2167,10 @@ listenerGroup.reset(); } deleteDataBinds(); + // The keyframe-value binds were just deleted by deleteDataBinds(); drop the + // now-stale tracking pointers before the layers (and their LAIs/holders) + // are destroyed below. + m_stateKeyFrameDataBinds.clear(); delete[] m_layers; for (auto pair : m_bindablePropertyInstances) { @@ -3213,6 +3236,159 @@ return nullptr; } +// The BindableProperty value property key matching a keyframe's value type, or +// 0 for unsupported keyframe types (e.g. id/uint), which are left unbound. +static uint32_t keyFrameHolderPropertyKey(uint16_t keyFrameType) +{ + switch (keyFrameType) + { + case KeyFrameDoubleBase::typeKey: + return BindablePropertyNumberBase::propertyValuePropertyKey; + case KeyFrameColorBase::typeKey: + return BindablePropertyColorBase::propertyValuePropertyKey; + case KeyFrameBoolBase::typeKey: + return BindablePropertyBooleanBase::propertyValuePropertyKey; + case KeyFrameStringBase::typeKey: + return BindablePropertyStringBase::propertyValuePropertyKey; + default: + return 0; + } +} + +// Creates the BindableProperty holder matching a keyframe's value type. +static BindableProperty* makeKeyFrameValueHolder(uint16_t keyFrameType) +{ + switch (keyFrameType) + { + case KeyFrameDoubleBase::typeKey: + return new BindablePropertyNumber(); + case KeyFrameColorBase::typeKey: + return new BindablePropertyColor(); + case KeyFrameBoolBase::typeKey: + return new BindablePropertyBoolean(); + case KeyFrameStringBase::typeKey: + return new BindablePropertyString(); + default: + return nullptr; + } +} + +void StateMachineInstance::buildStateKeyFrameBinds(StateInstance* stateInstance) +{ + if (stateInstance == nullptr || m_artboardInstance == nullptr) + { + return; + } + // Keyframe-targeting data binds are serialized on the source artboard (they + // target the shared, never-cloned keyframes), so resolve them from there. + const Artboard* source = m_artboardInstance->artboardSource(); + if (source == nullptr) + { + return; + } + + // Pre-index the source artboard's keyframe-targeting data binds once, keyed + // by their target keyframe. A keyframe holds a single value, so keep the + // first bind per target (emplace does not overwrite). This turns the + // per-keyframe lookup below from an O(numDataBinds) scan into O(1), so + // building a state's binds is O(numKeyFrames + numDataBinds) instead of + // O(numKeyFrames * numDataBinds). Filtering to keyframe targets keeps the + // index small (most data binds target components, not keyframes). + std::unordered_map<const Core*, DataBind*> firstBindByTarget; + for (auto dataBind : source->dataBinds()) + { + auto target = dataBind->target(); + if (target == nullptr || !target->is<KeyFrame>()) + { + continue; + } + firstBindByTarget.emplace(target, dataBind); + } + if (firstBindByTarget.empty()) + { + // No keyframe is data bound anywhere; skip the keyframe walk entirely. + return; + } + + stateInstance->forEachAnimationInstance( + [this, stateInstance, &firstBindByTarget]( + LinearAnimationInstance* animationInstance) { + const LinearAnimation* animation = animationInstance->animation(); + if (animation == nullptr) + { + return; + } + for (size_t o = 0; o < animation->numKeyedObjects(); o++) + { + const KeyedObject* keyedObject = animation->getObject(o); + if (keyedObject == nullptr) + { + continue; + } + for (size_t p = 0; p < keyedObject->numKeyedProperties(); p++) + { + const KeyedProperty* keyedProperty = + keyedObject->getProperty(p); + if (keyedProperty == nullptr) + { + continue; + } + for (size_t k = 0; k < keyedProperty->numKeyFrames(); k++) + { + KeyFrame* keyframe = keyedProperty->getKeyFrame(k); + uint32_t holderPropertyKey = + keyFrameHolderPropertyKey(keyframe->coreType()); + if (holderPropertyKey == 0) + { + continue; + } + auto found = firstBindByTarget.find(keyframe); + if (found == firstBindByTarget.end()) + { + continue; + } + DataBind* dataBind = found->second; + auto holder = + makeKeyFrameValueHolder(keyframe->coreType()); + animationInstance->addKeyFrameValueHolder(keyframe, + holder); + auto dataBindClone = + static_cast<DataBind*>(dataBind->clone()); + dataBindClone->file(dataBind->file()); + dataBindClone->target(holder); + dataBindClone->propertyKey(holderPropertyKey); + dataBindClone->initialize(); + if (dataBind->converter() != nullptr) + { + dataBindClone->converter(dataBind->converter() + ->clone() + ->as<DataConverter>()); + } + addDataBind(dataBindClone); + m_stateKeyFrameDataBinds[stateInstance].push_back( + dataBindClone); + } + } + } + }); +} + +void StateMachineInstance::removeStateKeyFrameBinds( + StateInstance* stateInstance) +{ + auto it = m_stateKeyFrameDataBinds.find(stateInstance); + if (it == m_stateKeyFrameDataBinds.end()) + { + return; + } + for (auto* dataBind : it->second) + { + removeDataBind(dataBind); + delete dataBind; + } + m_stateKeyFrameDataBinds.erase(it); +} + bool StateMachineInstance::hasFocusNodes() { auto* fm = focusManager();
diff --git a/src/artboard.cpp b/src/artboard.cpp index 08db63b..6e6e2fd 100644 --- a/src/artboard.cpp +++ b/src/artboard.cpp
@@ -1057,6 +1057,7 @@ } } } + void Artboard::host(ArtboardHost* artboardHost) { addedToHost();
diff --git a/tests/unit_tests/assets/data_bind_keyframes_test.riv b/tests/unit_tests/assets/data_bind_keyframes_test.riv new file mode 100644 index 0000000..f35f0b7 --- /dev/null +++ b/tests/unit_tests/assets/data_bind_keyframes_test.riv Binary files differ
diff --git a/tests/unit_tests/runtime/data_binding_keyframes.cpp b/tests/unit_tests/runtime/data_binding_keyframes.cpp new file mode 100644 index 0000000..26c21d0 --- /dev/null +++ b/tests/unit_tests/runtime/data_binding_keyframes.cpp
@@ -0,0 +1,226 @@ +#include <rive/file.hpp> +#include <rive/viewmodel/viewmodel_instance_string.hpp> +#include <rive/viewmodel/viewmodel_instance_number.hpp> +#include <rive/viewmodel/viewmodel_instance_color.hpp> +#include "rive/animation/state_machine_instance.hpp" +#include "rive/animation/linear_animation_instance.hpp" +#include "rive/nested_artboard.hpp" +#include "rive/text/text_value_run.hpp" +#include "rive/node.hpp" +#include "rive_file_reader.hpp" +#include "utils/serializing_factory.hpp" +#include <catch.hpp> +#include <cstdio> +#include <cstring> + +using namespace rive; + +// The fixture (assets/data_bind_keyframes_test.riv) plays, via a state machine, +// one animation that keyframes a text run's text and a node's x. Those keyframe +// values are data bound to the default view model: the text run's start/end +// string keyframes bind to `keyfTextStart`/`keyfrTextEnd`, and the node's start +// x keyframe binds to `startX`. At time 0 the start keyframes apply, so the +// bound start values are what land on the targets; the node then tweens from +// the bound start toward its (authored) end. + +TEST_CASE("Data binding keyframes", "[silver]") +{ + SerializingFactory silver; + auto file = ReadRiveFile("assets/data_bind_keyframes_test.riv", &silver); + + auto artboard = file->artboardDefault(); + REQUIRE(artboard != nullptr); + + silver.frameSize(artboard->width(), artboard->height()); + + auto stateMachine = artboard->stateMachineAt(0); + + auto vmi = file->createDefaultViewModelInstance(artboard.get()); + auto renderer = silver.makeRenderer(); + + stateMachine->bindViewModelInstance(vmi); + stateMachine->advanceAndApply(0.016f); + artboard->draw(renderer.get()); + + int frames = (int)(1.0f / 0.2f); + for (int i = 0; i < frames; i++) + { + silver.addFrame(); + stateMachine->advanceAndApply(0.2f); + artboard->draw(renderer.get()); + } + + auto keyfTextStartProp = + vmi->propertyValue("keyfTextStart")->as<ViewModelInstanceString>(); + keyfTextStartProp->propertyValue("updated--text"); + + auto colorStartProp = + vmi->propertyValue("colorStart")->as<ViewModelInstanceColor>(); + auto yellowColor = (255 << 24) | (255 << 16) | (255 << 8); + colorStartProp->propertyValue(yellowColor); + + auto startXProp = + vmi->propertyValue("startX")->as<ViewModelInstanceNumber>(); + startXProp->propertyValue(100); + + for (int i = 0; i < frames; i++) + { + silver.addFrame(); + stateMachine->advanceAndApply(0.2f); + artboard->draw(renderer.get()); + } + + CHECK(silver.matches("data_bind_keyframes_test")); +} + +// ---- helpers ------------------------------------------------------------- + +static TextValueRun* firstTextRun(Artboard* artboard) +{ + auto runs = artboard->find<TextValueRun>(); + return runs.empty() ? nullptr : runs[0]; +} + +static bool anyNodeHasX(Artboard* artboard, float x) +{ + for (auto* node : artboard->find<Node>()) + { + if (node->x() == Approx(x)) + { + return true; + } + } + return false; +} + +static void setStartText(rcp<ViewModelInstance> vmi, const std::string& text) +{ + vmi->propertyValue("keyfTextStart") + ->as<ViewModelInstanceString>() + ->propertyValue(text); +} + +static void setStartX(rcp<ViewModelInstance> vmi, float x) +{ + vmi->propertyValue("startX")->as<ViewModelInstanceNumber>()->propertyValue( + x); +} + +// ---- behavioral tests ---------------------------------------------------- + +TEST_CASE("keyframe value binds resolve view-model values on the first frame", + "[data binding]") +{ + auto file = ReadRiveFile("assets/data_bind_keyframes_test.riv"); + auto artboard = file->artboardDefault(); + REQUIRE(artboard != nullptr); + auto sm = artboard->stateMachineAt(0); + REQUIRE(sm != nullptr); + auto vmi = file->createDefaultViewModelInstance(artboard.get()); + REQUIRE(vmi != nullptr); + + // Distinctive sentinels set before binding, so the very first applied frame + // must reflect them (holders are primed when the data bind is added). + setStartText(vmi, "SENTINEL_START"); + setStartX(vmi, 424242.0f); + + sm->bindViewModelInstance(vmi); + sm->advanceAndApply(0.0f); + + auto* run = firstTextRun(artboard.get()); + REQUIRE(run != nullptr); + CHECK(run->text() == "SENTINEL_START"); // KeyFrameString bind + CHECK(anyNodeHasX(artboard.get(), 424242.0f)); // KeyFrameDouble bind +} + +TEST_CASE("keyframe value binds update when the source view-model changes", + "[data binding]") +{ + auto file = ReadRiveFile("assets/data_bind_keyframes_test.riv"); + auto artboard = file->artboardDefault(); + REQUIRE(artboard != nullptr); + auto sm = artboard->stateMachineAt(0); + auto vmi = file->createDefaultViewModelInstance(artboard.get()); + + setStartText(vmi, "first"); + setStartX(vmi, 10.0f); + sm->bindViewModelInstance(vmi); + sm->advanceAndApply(0.0f); + + auto* run = firstTextRun(artboard.get()); + REQUIRE(run != nullptr); + REQUIRE(run->text() == "first"); + REQUIRE(anyNodeHasX(artboard.get(), 10.0f)); + + // Change the sources; dt=0 keeps the playhead on the start keyframe, so the + // exact new bound values must land after the next advance. + setStartText(vmi, "second"); + setStartX(vmi, 987.0f); + sm->advanceAndApply(0.0f); + + CHECK(run->text() == "second"); + CHECK(anyNodeHasX(artboard.get(), 987.0f)); +} + +TEST_CASE("keyframe interpolation reads the data-bound start value", + "[data binding]") +{ + auto file = ReadRiveFile("assets/data_bind_keyframes_test.riv"); + auto artboard = file->artboardDefault(); + REQUIRE(artboard != nullptr); + auto sm = artboard->stateMachineAt(0); + auto vmi = file->createDefaultViewModelInstance(artboard.get()); + + // A large, distinctive start value the authored keyframe would never + // produce. The node tweens from this bound start toward its authored end, + // so once it's into the tween its x must be strictly between the two, + // proving the interpolation's from-endpoint is the bound value (not the + // authored one). + const float boundStart = 100000.0f; + setStartX(vmi, boundStart); + sm->bindViewModelInstance(vmi); + + sm->advanceAndApply(0.0f); + REQUIRE(anyNodeHasX(artboard.get(), boundStart)); // start endpoint applied + + sm->advanceAndApply(0.5f); // well into the tween + bool inTween = false; + for (auto* node : artboard->find<Node>()) + { + // Moved off the bound start but still dominated by it => interpolating + // from the bound value. + if (node->x() > 50000.0f && node->x() < boundStart) + { + inTween = true; + break; + } + } + CHECK(inTween); +} + +TEST_CASE("standalone animation instance ignores keyframe value binds", + "[data binding]") +{ + auto file = ReadRiveFile("assets/data_bind_keyframes_test.riv"); + auto artboard = file->artboardDefault(); + REQUIRE(artboard != nullptr); + REQUIRE(artboard->animationCount() > 0); + + auto vmi = file->createDefaultViewModelInstance(artboard.get()); + setStartText(vmi, "SHOULD_NOT_BIND"); + setStartX(vmi, 424242.0f); + // Bind the artboard's data context but drive playback via a *standalone* + // LinearAnimationInstance (not a state machine). Keyframe value binds are + // built only for state-machine-driven instances, so the authored keyframe + // values must apply here instead of the bound ones. + artboard->bindViewModelInstance(vmi); + + auto animation = artboard->animationAt(0); + REQUIRE(animation != nullptr); + animation->advanceAndApply(0.0f); + + auto* run = firstTextRun(artboard.get()); + REQUIRE(run != nullptr); + CHECK(run->text() != "SHOULD_NOT_BIND"); + CHECK_FALSE(anyNodeHasX(artboard.get(), 424242.0f)); +}
diff --git a/tests/unit_tests/silvers/data_bind_keyframes_test.sriv b/tests/unit_tests/silvers/data_bind_keyframes_test.sriv new file mode 100644 index 0000000..820ff45 --- /dev/null +++ b/tests/unit_tests/silvers/data_bind_keyframes_test.sriv Binary files differ