Nnnnn gamepad input support (#12646) 867dce9f73 * feature(UAT): add gamepad support Co-authored-by: hernan <hernan@rive.app>
diff --git a/.rive_head b/.rive_head index a9f10f6..8cad039 100644 --- a/.rive_head +++ b/.rive_head
@@ -1 +1 @@ -195d4fcb25427e309307e07670afb060c6886fec +867dce9f736ed8ec73f271d9a034a30b65e385a4
diff --git a/dev/defs/animation/listener_types/listener_input_type_gamepad.json b/dev/defs/animation/listener_types/listener_input_type_gamepad.json new file mode 100644 index 0000000..2a1a472 --- /dev/null +++ b/dev/defs/animation/listener_types/listener_input_type_gamepad.json
@@ -0,0 +1,8 @@ +{ + "name": "ListenerInputTypeGamepad", + "key": { + "int": 973, + "string": "listenerinputtypegamepad" + }, + "extends": "animation/listener_types/listener_input_type.json" +} \ No newline at end of file
diff --git a/dev/defs/inputs/gamepad_input.json b/dev/defs/inputs/gamepad_input.json new file mode 100644 index 0000000..28c19f0 --- /dev/null +++ b/dev/defs/inputs/gamepad_input.json
@@ -0,0 +1,46 @@ +{ + "name": "GamepadInput", + "key": { + "int": 974, + "string": "gamepadinput" + }, + "extends": "inputs/user_input.json", + "properties": { + "kind": { + "type": "uint", + "initialValue": "0", + "key": { + "int": 1021, + "string": "kind" + }, + "description": "Which gamepad event kind this filter selects (button, axis, connected, disconnected); see GamepadInputKind" + }, + "mapping": { + "type": "uint", + "initialValue": "0", + "key": { + "int": 1018, + "string": "mapping" + }, + "description": "How inputIndex is interpreted for button/axis kinds: 0 = W3C standard slot, 1 = raw W3C index" + }, + "inputIndex": { + "type": "uint", + "initialValue": "0", + "key": { + "int": 1019, + "string": "inputindex" + }, + "description": "Button or axis index; meaning depends on kind and mapping" + }, + "buttonPhase": { + "type": "uint", + "initialValue": "1", + "key": { + "int": 1020, + "string": "buttonphase" + }, + "description": "bit flag for button phases to match (down, up); only used when kind = button" + } + } +} \ No newline at end of file
diff --git a/include/rive/animation/gamepad_listener_group.hpp b/include/rive/animation/gamepad_listener_group.hpp new file mode 100644 index 0000000..552f14f --- /dev/null +++ b/include/rive/animation/gamepad_listener_group.hpp
@@ -0,0 +1,37 @@ +#ifndef _RIVE_GAMEPAD_LISTENER_GROUP_HPP_ +#define _RIVE_GAMEPAD_LISTENER_GROUP_HPP_ + +#include "rive/input/gamepad_listener.hpp" + +namespace rive +{ +class FocusData; +class StateMachineListener; +class StateMachineInstance; + +/// Routes gamepad snapshots to a state machine listener on `FocusData`, +/// mirroring `KeyboardListenerGroup`. +class GamepadListenerGroup : public GamepadListener +{ +public: + GamepadListenerGroup(FocusData* focusData, + const StateMachineListener* listener, + StateMachineInstance* stateMachineInstance); + ~GamepadListenerGroup() override; + + const StateMachineListener* listener() const { return m_listener; } + FocusData* focusData() const { return m_focusData; } + + bool gamepadDispatch( + const ListenerInvocation& invocation, + ScriptedDrawable** outDispatchedScriptedDrawable = nullptr) override; + +private: + FocusData* m_focusData; + const StateMachineListener* m_listener; + StateMachineInstance* m_stateMachineInstance; +}; + +} // namespace rive + +#endif
diff --git a/include/rive/animation/listener_invocation.hpp b/include/rive/animation/listener_invocation.hpp index 560f93f..176c0fe 100644 --- a/include/rive/animation/listener_invocation.hpp +++ b/include/rive/animation/listener_invocation.hpp
@@ -3,6 +3,8 @@ #include "rive/animation/semantic_listener_group.hpp" #include "rive/input/focusable.hpp" +#include "rive/input/gamepad_snapshot.hpp" +#include "rive/input/standard_gamepad.hpp" #include "rive/listener_type.hpp" #include "rive/math/vec2d.hpp" @@ -16,6 +18,8 @@ class Event; class FocusListenerGroup; class ListenerViewModel; +class SemanticListenerGroup; +enum class SemanticActionType : uint8_t; /// Discriminator for what triggered a listener's actions. Not to be confused /// with `rive::Event` (file/timeline event objects). enum class ListenerInvocationKind : uint8_t @@ -27,8 +31,10 @@ reportedEvent = 4, viewModelChange = 5, none = 6, - gamepad = 7, - semantic = 8, + gamepadConnected = 7, + gamepadEvent = 8, + gamepadDisconnected = 9, + semantic = 10, }; struct PointerInvocation @@ -76,11 +82,29 @@ struct NoneInvocation {}; -struct GamepadInvocation +/// Full snapshot when a gamepad is first seen in the embedder. +struct GamepadConnectedInvocation +{ + GamepadSnapshot snapshot{}; +}; + +/// One changed button or axis after all deltas in an `update` record are +/// applied. `hasStandard*Intent` is set when the device is standard-mapped +/// and the W3C index is a known standard button or stick/trigger slot. +struct GamepadEventInvocation +{ + /// State after this update record is fully applied. + GamepadSnapshot fullState{}; + GamepadInputChange change{}; + bool hasStandardButtonIntent = false; + StandardGamepadButton standardButton{}; + bool hasStandardAxisIntent = false; + StandardGamepadAxis standardAxis{}; +}; + +struct GamepadDisconnectedInvocation { int deviceId = 0; - uint64_t buttonMask = 0; - float axis0 = 0.f; }; struct SemanticInvocation @@ -96,7 +120,9 @@ ReportedEventInvocation, ViewModelChangeInvocation, NoneInvocation, - GamepadInvocation, + GamepadConnectedInvocation, + GamepadEventInvocation, + GamepadDisconnectedInvocation, SemanticInvocation>; /// Payload for a single run of listener actions (pointer, keyboard, reported @@ -119,11 +145,11 @@ float delaySeconds); static ListenerInvocation viewModelChange(ListenerViewModel* source); static ListenerInvocation none(); - static ListenerInvocation gamepad(int deviceId, - uint64_t buttonMask, - float axis0); static ListenerInvocation semantic(SemanticListenerGroup* group, SemanticActionType actionType); + static ListenerInvocation gamepadConnected(const GamepadSnapshot& snapshot); + static ListenerInvocation gamepadEvent(GamepadEventInvocation value); + static ListenerInvocation gamepadDisconnected(int deviceId); ListenerInvocationKind kind() const; @@ -134,7 +160,9 @@ const ReportedEventInvocation* asReportedEvent() const; const ViewModelChangeInvocation* asViewModelChange() const; const NoneInvocation* asNone() const; - const GamepadInvocation* asGamepad() const; + const GamepadConnectedInvocation* asGamepadConnected() const; + const GamepadEventInvocation* asGamepadEvent() const; + const GamepadDisconnectedInvocation* asGamepadDisconnected() const; const SemanticInvocation* asSemantic() const; const ListenerInvocationStorage& storage() const { return m_storage; } @@ -180,9 +208,17 @@ { return ListenerInvocationKind::none; } - else if constexpr (std::is_same_v<T, GamepadInvocation>) + else if constexpr (std::is_same_v<T, GamepadConnectedInvocation>) { - return ListenerInvocationKind::gamepad; + return ListenerInvocationKind::gamepadConnected; + } + else if constexpr (std::is_same_v<T, GamepadEventInvocation>) + { + return ListenerInvocationKind::gamepadEvent; + } + else if constexpr (std::is_same_v<T, GamepadDisconnectedInvocation>) + { + return ListenerInvocationKind::gamepadDisconnected; } else if constexpr (std::is_same_v<T, SemanticInvocation>) { @@ -233,9 +269,21 @@ return std::get_if<NoneInvocation>(&m_storage); } -inline const GamepadInvocation* ListenerInvocation::asGamepad() const +inline const GamepadConnectedInvocation* ListenerInvocation:: + asGamepadConnected() const { - return std::get_if<GamepadInvocation>(&m_storage); + return std::get_if<GamepadConnectedInvocation>(&m_storage); +} + +inline const GamepadEventInvocation* ListenerInvocation::asGamepadEvent() const +{ + return std::get_if<GamepadEventInvocation>(&m_storage); +} + +inline const GamepadDisconnectedInvocation* ListenerInvocation:: + asGamepadDisconnected() const +{ + return std::get_if<GamepadDisconnectedInvocation>(&m_storage); } inline const SemanticInvocation* ListenerInvocation::asSemantic() const
diff --git a/include/rive/animation/listener_types/listener_input_type_gamepad.hpp b/include/rive/animation/listener_types/listener_input_type_gamepad.hpp new file mode 100644 index 0000000..5a9d87e --- /dev/null +++ b/include/rive/animation/listener_types/listener_input_type_gamepad.hpp
@@ -0,0 +1,44 @@ +#ifndef _RIVE_LISTENER_INPUT_TYPE_GAMEPAD_HPP_ +#define _RIVE_LISTENER_INPUT_TYPE_GAMEPAD_HPP_ + +#include "rive/generated/animation/listener_types/listener_input_type_gamepad_base.hpp" + +#include <cstdint> +#include <vector> + +namespace rive +{ + +class GamepadInput; +class ListenerInvocation; +class StateMachineListener; + +class ListenerInputTypeGamepad : public ListenerInputTypeGamepadBase +{ +public: + size_t gamepadInputCount() const { return m_gamepadInputs.size(); } + const GamepadInput* gamepadInput(size_t index) const; + void addGamepadInput(GamepadInput* input); + + /// True if `phase` (a `GamepadButtonPhaseMask`) opted in to the current + /// press / release transition. + static bool gamepadButtonPhaseMatches(uint32_t phase, bool isPressed); + + /// True if `input` selects the field/event represented by `invocation`. + static bool gamepadInputMatches(const GamepadInput& input, + const ListenerInvocation& invocation); + + /// True if any `ListenerInputTypeGamepad` on `listener` matches the + /// invocation. An empty input list on any `ListenerInputTypeGamepad` + /// matches any gamepad event (catch-all, preserves legacy behavior). + static bool gamepadListenerConstraintsMet( + const StateMachineListener* listener, + const ListenerInvocation& invocation); + +private: + std::vector<GamepadInput*> m_gamepadInputs; +}; + +} // namespace rive + +#endif
diff --git a/include/rive/animation/state_machine_instance.hpp b/include/rive/animation/state_machine_instance.hpp index 9d0a969..43a1e85 100644 --- a/include/rive/animation/state_machine_instance.hpp +++ b/include/rive/animation/state_machine_instance.hpp
@@ -5,6 +5,7 @@ #include <stddef.h> #include <vector> #include <unordered_map> +#include "rive/animation/gamepad_listener_group.hpp" #include "rive/animation/keyboard_listener_group.hpp" #include "rive/animation/semantic_listener_group.hpp" #include "rive/animation/linear_animation_instance.hpp" @@ -20,6 +21,7 @@ #include "rive/input/focusable.hpp" #include "rive/input/focus_manager.hpp" #include "rive/semantic/semantic_manager.hpp" +#include "rive/input/gamepad_snapshot.hpp" namespace rive { @@ -48,6 +50,7 @@ class HitDrawable; class ListenerViewModel; class ScriptedListenerAction; +class ScriptedDrawable; typedef void (*DataBindChanged)(); #ifdef WITH_RIVE_TOOLS @@ -251,6 +254,21 @@ /// internal manager regardless of whether an external one is set. FocusManager* internalFocusManager() { return &m_focusManager; } + /// Parses embedder gamepad batch bytes (same format as JS + /// `GAMEPAD_BATCH_VERSION` in `registerGamepadInteractions`). Invokes + /// `focusManager()->gamepadDispatch` for each record. Returns false if the + /// buffer is invalid or truncated. + bool submitGamepadsFromBuffer(const uint8_t* data, size_t length); + + /// Forward `invocation` to every `ScriptedDrawable` in this state machine + /// whose script declares a gamepad handler (`wantsGamePad()`), skipping + /// `alreadyDispatched` (typically the focus-tree recipient) so a script + /// is never invoked twice for the same event. Used by gamepad dispatch + /// after the focus bubble so non-focused scripts can still react. + HitResult broadcastGamepadToScriptedDrawables( + const ListenerInvocation& invocation, + ScriptedDrawable* alreadyDispatched); + /// Set an external focus manager to use instead of the internal one. /// This is used when a nested artboard should share focus with its parent. /// If the focus tree was already built with a different manager, it will @@ -354,6 +372,16 @@ std::vector<std::unique_ptr<FocusListenerGroup>> m_focusListenerGroups; std::vector<std::unique_ptr<KeyboardListenerGroup>> m_keyboardListenerGroups; + std::vector<std::unique_ptr<GamepadListenerGroup>> m_gamepadListenerGroups; + /// Non-owning back-references to every `ScriptedDrawable` whose script + /// declares a gamepad handler. Populated once at init from the artboard + /// (which outlives this state machine) and walked by + /// `broadcastGamepadToScriptedDrawables` so events reach scripts that are + /// not on the focus chain. Mirrors how `m_hitComponents` lets every + /// pointer-aware drawable react regardless of focus. + std::vector<ScriptedDrawable*> m_gamepadScriptedDrawables; + /// Latest embedder gamepad state for `submitGamepadsFromBuffer` (WASM/JS). + std::unordered_map<int, GamepadSnapshot> m_embedderGamepads; // Semantic management std::unique_ptr<SemanticManager> m_semanticManager; @@ -404,6 +432,9 @@ bool canHit, float timeStamp = 0, int pointerId = 0) = 0; + virtual HitResult processGamepadInvocation( + const ListenerInvocation& invocation, + ScriptedDrawable* alreadyDispatched) = 0; virtual void prepareEvent(Vec2D position, ListenerType hitType, int pointerId) = 0;
diff --git a/include/rive/assets/script_asset.hpp b/include/rive/assets/script_asset.hpp index 5339480..cff7db4 100644 --- a/include/rive/assets/script_asset.hpp +++ b/include/rive/assets/script_asset.hpp
@@ -88,6 +88,9 @@ static const int m_drawsCanvasBit = 1 << 15; static const int m_wantsKeyboardInputBit = 1 << 16; static const int m_wantsTextInputBit = 1 << 17; + static const int m_wantsGamepadConnect = 1 << 18; + static const int m_wantsGamepadDisconnect = 1 << 19; + static const int m_wantsGamepadEvent = 1 << 20; int m_implementedMethods = 0; @@ -107,7 +110,8 @@ return (m_implementedMethods & (m_wantsPointerDownBit | m_wantsPointerMoveBit | m_wantsPointerUpBit | m_wantsPointerExitBit | - m_wantsPointerCancelBit)) != 0; + m_wantsPointerCancelBit | m_wantsGamepadConnect | + m_wantsGamepadDisconnect | m_wantsGamepadEvent)) != 0; } bool advances() { return (m_implementedMethods & m_advancesBit) != 0; } bool updates() { return (m_implementedMethods & m_updatesBit) != 0; } @@ -141,6 +145,18 @@ { return (m_implementedMethods & m_wantsPointerCancelBit) != 0; } + bool wantsGamePadConnect() + { + return (m_implementedMethods & m_wantsGamepadConnect) != 0; + } + bool wantsGamePadDisconnect() + { + return (m_implementedMethods & m_wantsGamepadDisconnect) != 0; + } + bool wantsGamePadEvent() + { + return (m_implementedMethods & m_wantsGamepadEvent) != 0; + } bool draws() { return (m_implementedMethods & m_drawsBit) != 0; } bool inits() { return (m_implementedMethods & m_initsBit) != 0; } bool dataConverts()
diff --git a/include/rive/focus_data.hpp b/include/rive/focus_data.hpp index c10c763..10b21f1 100644 --- a/include/rive/focus_data.hpp +++ b/include/rive/focus_data.hpp
@@ -1,8 +1,10 @@ #ifndef _RIVE_FOCUS_DATA_HPP_ #define _RIVE_FOCUS_DATA_HPP_ +#include "rive/animation/listener_invocation.hpp" #include "rive/component_dirt.hpp" #include "rive/generated/focus_data_base.hpp" #include "rive/input/focus_node.hpp" +#include "rive/input/gamepad_listener.hpp" #include "rive/input/keyboard_listener.hpp" #include "rive/input/focusable.hpp" #include "rive/math/aabb.hpp" @@ -39,6 +41,9 @@ /// Unregister a text input listener. void removeTextInputListener(KeyboardListener* listener); + void addGamepadListener(GamepadListener* listener); + void removeGamepadListener(GamepadListener* listener); + /// Programmatically focus this node. void focus(); @@ -65,6 +70,9 @@ bool isPressed, bool isRepeat) override; bool textInput(const std::string& text) override; + bool gamepadDispatch( + const ListenerInvocation& invocation, + ScriptedDrawable** outDispatchedScriptedDrawable = nullptr) override; void focused() override; void blurred() override; bool worldPosition(Vec2D& outPosition) override; @@ -94,6 +102,7 @@ std::vector<FocusListener*> m_focusListeners; std::vector<KeyboardListener*> m_keyboardListeners; std::vector<KeyboardListener*> m_textInputListeners; + std::vector<GamepadListener*> m_gamepadListeners; }; } // namespace rive
diff --git a/include/rive/generated/animation/listener_types/listener_input_type_gamepad_base.hpp b/include/rive/generated/animation/listener_types/listener_input_type_gamepad_base.hpp new file mode 100644 index 0000000..d955b77 --- /dev/null +++ b/include/rive/generated/animation/listener_types/listener_input_type_gamepad_base.hpp
@@ -0,0 +1,36 @@ +#ifndef _RIVE_LISTENER_INPUT_TYPE_GAMEPAD_BASE_HPP_ +#define _RIVE_LISTENER_INPUT_TYPE_GAMEPAD_BASE_HPP_ +#include "rive/animation/listener_types/listener_input_type.hpp" +namespace rive +{ +class ListenerInputTypeGamepadBase : public ListenerInputType +{ +protected: + typedef ListenerInputType Super; + +public: + static const uint16_t typeKey = 973; + + /// Helper to quickly determine if a core object extends another without + /// RTTI at runtime. + bool isTypeOf(uint16_t typeKey) const override + { + switch (typeKey) + { + case ListenerInputTypeGamepadBase::typeKey: + case ListenerInputTypeBase::typeKey: + return true; + default: + return false; + } + } + + uint16_t coreType() const override { return typeKey; } + + Core* clone() const override; + +protected: +}; +} // namespace rive + +#endif \ No newline at end of file
diff --git a/include/rive/generated/core_registry.hpp b/include/rive/generated/core_registry.hpp index 8f16d5f..a51ebaf 100644 --- a/include/rive/generated/core_registry.hpp +++ b/include/rive/generated/core_registry.hpp
@@ -46,6 +46,7 @@ #include "rive/animation/listener_trigger_change.hpp" #include "rive/animation/listener_types/listener_input_type.hpp" #include "rive/animation/listener_types/listener_input_type_event.hpp" +#include "rive/animation/listener_types/listener_input_type_gamepad.hpp" #include "rive/animation/listener_types/listener_input_type_keyboard.hpp" #include "rive/animation/listener_types/listener_input_type_semantic.hpp" #include "rive/animation/listener_types/listener_input_type_text.hpp" @@ -206,6 +207,7 @@ #include "rive/event.hpp" #include "rive/focus_data.hpp" #include "rive/foreground_layout_drawable.hpp" +#include "rive/inputs/gamepad_input.hpp" #include "rive/inputs/keyboard_input.hpp" #include "rive/inputs/semantic_input.hpp" #include "rive/inputs/user_input.hpp" @@ -605,6 +607,8 @@ return new ListenerInputType(); case ListenerInputTypeEventBase::typeKey: return new ListenerInputTypeEvent(); + case ListenerInputTypeGamepadBase::typeKey: + return new ListenerInputTypeGamepad(); case ListenerInputTypeKeyboardBase::typeKey: return new ListenerInputTypeKeyboard(); case ListenerInputTypeTextBase::typeKey: @@ -883,6 +887,8 @@ return new AudioEvent(); case UserInputBase::typeKey: return new UserInput(); + case GamepadInputBase::typeKey: + return new GamepadInput(); case KeyboardInputBase::typeKey: return new KeyboardInput(); case SemanticInputBase::typeKey: @@ -1666,6 +1672,18 @@ case AudioEventBase::assetIdPropertyKey: object->as<AudioEventBase>()->assetId(value); break; + case GamepadInputBase::kindPropertyKey: + object->as<GamepadInputBase>()->kind(value); + break; + case GamepadInputBase::mappingPropertyKey: + object->as<GamepadInputBase>()->mapping(value); + break; + case GamepadInputBase::inputIndexPropertyKey: + object->as<GamepadInputBase>()->inputIndex(value); + break; + case GamepadInputBase::buttonPhasePropertyKey: + object->as<GamepadInputBase>()->buttonPhase(value); + break; case KeyboardInputBase::keyTypePropertyKey: object->as<KeyboardInputBase>()->keyType(value); break; @@ -3554,6 +3572,14 @@ return object->as<ScriptAssetBase>()->generatorFunctionRef(); case AudioEventBase::assetIdPropertyKey: return object->as<AudioEventBase>()->assetId(); + case GamepadInputBase::kindPropertyKey: + return object->as<GamepadInputBase>()->kind(); + case GamepadInputBase::mappingPropertyKey: + return object->as<GamepadInputBase>()->mapping(); + case GamepadInputBase::inputIndexPropertyKey: + return object->as<GamepadInputBase>()->inputIndex(); + case GamepadInputBase::buttonPhasePropertyKey: + return object->as<GamepadInputBase>()->buttonPhase(); case KeyboardInputBase::keyTypePropertyKey: return object->as<KeyboardInputBase>()->keyType(); case KeyboardInputBase::keyPhasePropertyKey: @@ -4471,6 +4497,10 @@ case FileAssetBase::assetIdPropertyKey: case ScriptAssetBase::generatorFunctionRefPropertyKey: case AudioEventBase::assetIdPropertyKey: + case GamepadInputBase::kindPropertyKey: + case GamepadInputBase::mappingPropertyKey: + case GamepadInputBase::inputIndexPropertyKey: + case GamepadInputBase::buttonPhasePropertyKey: case KeyboardInputBase::keyTypePropertyKey: case KeyboardInputBase::keyPhasePropertyKey: case KeyboardInputBase::modifiersPropertyKey: @@ -5291,6 +5321,14 @@ return object->is<ScriptAssetBase>(); case AudioEventBase::assetIdPropertyKey: return object->is<AudioEventBase>(); + case GamepadInputBase::kindPropertyKey: + return object->is<GamepadInputBase>(); + case GamepadInputBase::mappingPropertyKey: + return object->is<GamepadInputBase>(); + case GamepadInputBase::inputIndexPropertyKey: + return object->is<GamepadInputBase>(); + case GamepadInputBase::buttonPhasePropertyKey: + return object->is<GamepadInputBase>(); case KeyboardInputBase::keyTypePropertyKey: return object->is<KeyboardInputBase>(); case KeyboardInputBase::keyPhasePropertyKey:
diff --git a/include/rive/generated/inputs/gamepad_input_base.hpp b/include/rive/generated/inputs/gamepad_input_base.hpp new file mode 100644 index 0000000..f1d21a7 --- /dev/null +++ b/include/rive/generated/inputs/gamepad_input_base.hpp
@@ -0,0 +1,125 @@ +#ifndef _RIVE_GAMEPAD_INPUT_BASE_HPP_ +#define _RIVE_GAMEPAD_INPUT_BASE_HPP_ +#include "rive/core/field_types/core_uint_type.hpp" +#include "rive/inputs/user_input.hpp" +namespace rive +{ +class GamepadInputBase : public UserInput +{ +protected: + typedef UserInput Super; + +public: + static const uint16_t typeKey = 974; + + /// Helper to quickly determine if a core object extends another without + /// RTTI at runtime. + bool isTypeOf(uint16_t typeKey) const override + { + switch (typeKey) + { + case GamepadInputBase::typeKey: + case UserInputBase::typeKey: + return true; + default: + return false; + } + } + + uint16_t coreType() const override { return typeKey; } + + static const uint16_t kindPropertyKey = 1021; + static const uint16_t mappingPropertyKey = 1018; + static const uint16_t inputIndexPropertyKey = 1019; + static const uint16_t buttonPhasePropertyKey = 1020; + +protected: + uint32_t m_Kind = 0; + uint32_t m_Mapping = 0; + uint32_t m_InputIndex = 0; + uint32_t m_ButtonPhase = 1; + +public: + inline uint32_t kind() const { return m_Kind; } + void kind(uint32_t value) + { + if (m_Kind == value) + { + return; + } + m_Kind = value; + kindChanged(); + } + + inline uint32_t mapping() const { return m_Mapping; } + void mapping(uint32_t value) + { + if (m_Mapping == value) + { + return; + } + m_Mapping = value; + mappingChanged(); + } + + inline uint32_t inputIndex() const { return m_InputIndex; } + void inputIndex(uint32_t value) + { + if (m_InputIndex == value) + { + return; + } + m_InputIndex = value; + inputIndexChanged(); + } + + inline uint32_t buttonPhase() const { return m_ButtonPhase; } + void buttonPhase(uint32_t value) + { + if (m_ButtonPhase == value) + { + return; + } + m_ButtonPhase = value; + buttonPhaseChanged(); + } + + Core* clone() const override; + void copy(const GamepadInputBase& object) + { + m_Kind = object.m_Kind; + m_Mapping = object.m_Mapping; + m_InputIndex = object.m_InputIndex; + m_ButtonPhase = object.m_ButtonPhase; + UserInput::copy(object); + } + + bool deserialize(uint16_t propertyKey, BinaryReader& reader) override + { + switch (propertyKey) + { + case kindPropertyKey: + m_Kind = CoreUintType::deserialize(reader); + return true; + case mappingPropertyKey: + m_Mapping = CoreUintType::deserialize(reader); + return true; + case inputIndexPropertyKey: + m_InputIndex = CoreUintType::deserialize(reader); + return true; + case buttonPhasePropertyKey: + m_ButtonPhase = CoreUintType::deserialize(reader); + return true; + } + return UserInput::deserialize(propertyKey, reader); + } + +protected: + virtual void kindChanged() {} + virtual void mappingChanged() {} + virtual void inputIndexChanged() {} + virtual void buttonPhaseChanged() {} +}; +} // namespace rive + +#endif \ No newline at end of file
diff --git a/include/rive/importers/listener_input_type_gamepad_importer.hpp b/include/rive/importers/listener_input_type_gamepad_importer.hpp new file mode 100644 index 0000000..57f97a2 --- /dev/null +++ b/include/rive/importers/listener_input_type_gamepad_importer.hpp
@@ -0,0 +1,26 @@ +#ifndef _RIVE_LISTENER_INPUT_TYPE_GAMEPAD_IMPORTER_HPP_ +#define _RIVE_LISTENER_INPUT_TYPE_GAMEPAD_IMPORTER_HPP_ + +#include "rive/importers/import_stack.hpp" + +namespace rive +{ +class ListenerInputTypeGamepad; + +class ListenerInputTypeGamepadImporter : public ImportStackObject +{ +private: + ListenerInputTypeGamepad* m_listenerInputTypeGamepad; + +public: + explicit ListenerInputTypeGamepadImporter( + ListenerInputTypeGamepad* listenerInputTypeGamepad); + ListenerInputTypeGamepad* listenerInputTypeGamepad() const + { + return m_listenerInputTypeGamepad; + } + StatusCode resolve() override; +}; +} // namespace rive + +#endif
diff --git a/include/rive/input/focus_manager.hpp b/include/rive/input/focus_manager.hpp index a9bec19..da57b2d 100644 --- a/include/rive/input/focus_manager.hpp +++ b/include/rive/input/focus_manager.hpp
@@ -13,6 +13,8 @@ { class Artboard; +class ListenerInvocation; +class ScriptedDrawable; /// Direction for directional focus navigation enum class Direction : uint8_t @@ -108,6 +110,14 @@ bool isRepeat); bool textInput(const std::string& text); + /// Bubble gamepad invocations from primary focus up through ancestors. + /// `outDispatchedScriptedDrawable` (when non-null) is filled with the + /// `ScriptedDrawable` that the focus tree forwarded the event to so + /// callers can avoid double-dispatching during a separate broadcast pass. + bool gamepadDispatch( + const ListenerInvocation& invocation, + ScriptedDrawable** outDispatchedScriptedDrawable = nullptr); + #ifdef WITH_RIVE_TOOLS // === Callbacks (editor/tools only) === using FocusChangedCallback = void (*)();
diff --git a/include/rive/input/focus_node.hpp b/include/rive/input/focus_node.hpp index 13f59cd..51c8885 100644 --- a/include/rive/input/focus_node.hpp +++ b/include/rive/input/focus_node.hpp
@@ -16,6 +16,7 @@ { class FocusManager; // Forward declaration +class ListenerInvocation; enum class EdgeBehavior : uint8_t { @@ -126,6 +127,16 @@ return m_focusable ? m_focusable->textInput(text) : false; } + bool gamepadDispatch( + const ListenerInvocation& invocation, + ScriptedDrawable** outDispatchedScriptedDrawable = nullptr) + { + return m_focusable + ? m_focusable->gamepadDispatch(invocation, + outDispatchedScriptedDrawable) + : false; + } + void focused() { if (m_focusable)
diff --git a/include/rive/input/focusable.hpp b/include/rive/input/focusable.hpp index b1ff48d..5641f27 100644 --- a/include/rive/input/focusable.hpp +++ b/include/rive/input/focusable.hpp
@@ -8,6 +8,9 @@ namespace rive { +class ListenerInvocation; +class ScriptedDrawable; + enum class KeyModifiers : uint8_t { none = 0, @@ -172,6 +175,15 @@ bool isPressed, bool isRepeat) = 0; virtual bool textInput(const std::string& text) = 0; + + /// Gamepad `ListenerInvocation` from the focus bubble. Default: ignore. + /// `outDispatchedScriptedDrawable` (when non-null) is filled with the + /// `ScriptedDrawable` that ended up receiving the event so callers can + /// avoid re-dispatching to it during a broadcast pass. + virtual bool gamepadDispatch( + const ListenerInvocation& invocation, + ScriptedDrawable** outDispatchedScriptedDrawable = nullptr); + virtual void focused() = 0; virtual void blurred() = 0;
diff --git a/include/rive/input/gamepad_batch.hpp b/include/rive/input/gamepad_batch.hpp new file mode 100644 index 0000000..a17cdfb --- /dev/null +++ b/include/rive/input/gamepad_batch.hpp
@@ -0,0 +1,26 @@ +#ifndef _RIVE_GAMEPAD_BATCH_HPP_ +#define _RIVE_GAMEPAD_BATCH_HPP_ + +#include <cstddef> +#include <cstdint> + +namespace rive +{ + +/// Wire format version for `StateMachineInstance::submitGamepadsFromBuffer` / +/// JS `GAMEPAD_BATCH_VERSION` (version `uint32` then record stream, LE). +constexpr uint32_t kGamepadBatchWireVersion = 2; +constexpr uint8_t kGamepadBatchMaxButtons = 32; +constexpr uint8_t kGamepadBatchMaxAxes = 16; + +/// Record `uint8` type after the version field. +enum class GamepadRecordType : uint8_t +{ + connected = 0, + update = 1, + disconnected = 2, +}; + +} // namespace rive + +#endif
diff --git a/include/rive/input/gamepad_listener.hpp b/include/rive/input/gamepad_listener.hpp new file mode 100644 index 0000000..41f4ea8 --- /dev/null +++ b/include/rive/input/gamepad_listener.hpp
@@ -0,0 +1,28 @@ +#ifndef _RIVE_GAMEPAD_LISTENER_HPP_ +#define _RIVE_GAMEPAD_LISTENER_HPP_ + +namespace rive +{ + +class ListenerInvocation; +class ScriptedDrawable; + +/// Interface for objects notified of gamepad snapshots on a `FocusData`. +class GamepadListener +{ +public: + virtual ~GamepadListener() = default; + + /// Called when the associated `FocusData` receives a gamepad event. + /// Return true to stop bubbling to ancestor focus nodes (optional). + /// `outDispatchedScriptedDrawable` (when non-null) is filled with the + /// `ScriptedDrawable` that ended up receiving the event so callers can + /// avoid re-dispatching to it during a broadcast pass. + virtual bool gamepadDispatch( + const ListenerInvocation& invocation, + ScriptedDrawable** outDispatchedScriptedDrawable = nullptr) = 0; +}; + +} // namespace rive + +#endif
diff --git a/include/rive/input/gamepad_snapshot.hpp b/include/rive/input/gamepad_snapshot.hpp new file mode 100644 index 0000000..5a65d19 --- /dev/null +++ b/include/rive/input/gamepad_snapshot.hpp
@@ -0,0 +1,63 @@ +#ifndef _RIVE_GAMEPAD_SNAPSHOT_HPP_ +#define _RIVE_GAMEPAD_SNAPSHOT_HPP_ + +#include <cstddef> +#include <cstdint> +#include <vector> + +namespace rive +{ + +/// A single field change in a gamepad "update" wire message or event. +enum class GamepadInputChangeKind : uint8_t +{ + button = 0, + axis = 1, +}; + +struct GamepadInputChange +{ + GamepadInputChangeKind kind = GamepadInputChangeKind::button; + /// W3C button or axis index (0-based). + uint8_t index = 0; + /// `GamepadButton.value` (0-1) or axis analog value. + float value = 0.f; +}; + +/// How closely the embedder could map hardware to the W3C Standard Gamepad +/// layout. +enum class GamepadMappingKind : uint8_t +{ + /// Buttons and axes follow https://w3c.github.io/gamepad/#remapping + standard = 0, + /// Non-standard device or unmapped — semantic filters may be unreliable. + unknown = 1, +}; + +/// Neutral gamepad snapshot in `ListenerInvocation` and embedder state. +/// +/// - `deviceId`: embedder-defined stable id for the logical device session +/// (hot-plug may allocate a new id; document embedder policy alongside the +/// integration). +/// - `buttonMask`: bit \e i set when W3C standard gamepad button \e i is +/// pressed +/// (see https://w3c.github.io/gamepad/#remapping ). +/// - `buttonValues`: parallel to W3C `buttons[]` order, each entry is +/// `GamepadButton.value` (0–1), including analog triggers and pressure. +/// - `axes`: ordered analog values; length is embedder-defined (W3C standard +/// layout uses at least six: left stick, right stick, then left/right +/// triggers). Typical ranges: sticks [-1,1], triggers [0,1]. +/// - `mapping`: whether the embedder normalized to the standard layout; when +/// `unknown`, semantic helpers that map names to indices may not apply. +struct GamepadSnapshot +{ + int deviceId = 0; + uint64_t buttonMask = 0; + std::vector<float> buttonValues; + std::vector<float> axes; + GamepadMappingKind mapping = GamepadMappingKind::standard; +}; + +} // namespace rive + +#endif
diff --git a/include/rive/input/standard_gamepad.hpp b/include/rive/input/standard_gamepad.hpp new file mode 100644 index 0000000..f12db08 --- /dev/null +++ b/include/rive/input/standard_gamepad.hpp
@@ -0,0 +1,69 @@ +#ifndef _RIVE_STANDARD_GAMEPAD_HPP_ +#define _RIVE_STANDARD_GAMEPAD_HPP_ + +#include <cstddef> +#include <cstdint> +#include <vector> + +namespace rive +{ + +/// Logical face / control positions for the W3C Standard Gamepad layout. +/// Indices match https://w3c.github.io/gamepad/#remapping button indices. +enum class StandardGamepadButton : uint8_t +{ + south = 0x00, + east = 0x01, + west = 0x02, + north = 0x03, + leftShoulder = 0x04, + rightShoulder = 0x05, + leftTrigger = 0x06, + rightTrigger = 0x07, + back = 0x08, + forward = 0x09, + leftStick = 0x0a, + rightStick = 0x0b, + dpadUp = 0x0c, + dpadDown = 0x0d, + dpadLeft = 0x0e, + dpadRight = 0x0f, + start = 0x10, +}; + +/// Standard axis slots for the W3C layout (indices into `GamepadSnapshot::axes` +/// when that vector is standard-mapped; missing indices read as 0). Analog +/// button pressure uses `GamepadSnapshot::buttonValues` at the same indices as +/// `StandardGamepadButton`. +enum class StandardGamepadAxis : uint8_t +{ + leftX = 0, + leftY = 1, + rightX = 2, + rightY = 3, + leftTrigger = 4, + rightTrigger = 5, +}; + +inline float standardGamepadAxisValue(const std::vector<float>& axes, + StandardGamepadAxis axis) +{ + const size_t i = static_cast<size_t>(axis); + return i < axes.size() ? axes[i] : 0.f; +} + +inline size_t standardGamepadButtonIndex(StandardGamepadButton b) +{ + return static_cast<size_t>(b); +} + +inline bool standardGamepadButtonPressed(uint64_t buttonMask, + StandardGamepadButton button) +{ + const uint64_t bit = uint64_t(1) << standardGamepadButtonIndex(button); + return (buttonMask & bit) != 0; +} + +} // namespace rive + +#endif
diff --git a/include/rive/inputs/gamepad_button_phase.hpp b/include/rive/inputs/gamepad_button_phase.hpp new file mode 100644 index 0000000..a312775 --- /dev/null +++ b/include/rive/inputs/gamepad_button_phase.hpp
@@ -0,0 +1,21 @@ +#ifndef _RIVE_GAMEPAD_BUTTON_PHASE_HPP_ +#define _RIVE_GAMEPAD_BUTTON_PHASE_HPP_ + +#include <cstdint> + +namespace rive +{ +/// Bitmask for \c GamepadInputBase::buttonPhase() — which button transitions a +/// gamepad listener input matches. Only meaningful when the input's `kind` is +/// `GamepadInputKind::button`. +struct GamepadButtonPhaseMask +{ + /// Button transitioned to pressed (value >= 0.5). + static constexpr uint32_t down = 1u << 0; + /// Button transitioned to released (value < 0.5). + static constexpr uint32_t up = 1u << 1; + static constexpr uint32_t all = down | up; +}; +} // namespace rive + +#endif
diff --git a/include/rive/inputs/gamepad_input.hpp b/include/rive/inputs/gamepad_input.hpp new file mode 100644 index 0000000..e1e8b7f --- /dev/null +++ b/include/rive/inputs/gamepad_input.hpp
@@ -0,0 +1,15 @@ +#ifndef _RIVE_GAMEPAD_INPUT_HPP_ +#define _RIVE_GAMEPAD_INPUT_HPP_ +#include "rive/generated/inputs/gamepad_input_base.hpp" +#include "rive/inputs/gamepad_button_phase.hpp" +#include "rive/inputs/gamepad_input_kind.hpp" +namespace rive +{ +class GamepadInput : public GamepadInputBase +{ +public: + StatusCode import(ImportStack& importStack) override; +}; +} // namespace rive + +#endif
diff --git a/include/rive/inputs/gamepad_input_kind.hpp b/include/rive/inputs/gamepad_input_kind.hpp new file mode 100644 index 0000000..819f477 --- /dev/null +++ b/include/rive/inputs/gamepad_input_kind.hpp
@@ -0,0 +1,32 @@ +#ifndef _RIVE_GAMEPAD_INPUT_KIND_HPP_ +#define _RIVE_GAMEPAD_INPUT_KIND_HPP_ + +#include <cstdint> + +namespace rive +{ +/// Values for \c GamepadInputBase::kind() — which gamepad event kind a single +/// `GamepadInput` filters. `button` / `axis` mirror `GamepadInputChangeKind` +/// (see \c gamepad_snapshot.hpp) so the value can be compared directly against +/// `GamepadEventInvocation::change.kind`. +enum class GamepadInputKind : uint32_t +{ + button = 0, + axis = 1, + connected = 2, + disconnected = 3, +}; + +/// Values for \c GamepadInputBase::mapping() — how `inputIndex` is interpreted +/// for `button` / `axis` kinds. +enum class GamepadInputMapping : uint32_t +{ + /// `inputIndex` is a W3C standard slot (matches the corresponding + /// `StandardGamepadButton` / `StandardGamepadAxis` enum value). + standard = 0, + /// `inputIndex` is the raw W3C index into the buttons/axes arrays. + index = 1, +}; +} // namespace rive + +#endif
diff --git a/include/rive/listener_type.hpp b/include/rive/listener_type.hpp index 38393e1..545702b 100644 --- a/include/rive/listener_type.hpp +++ b/include/rive/listener_type.hpp
@@ -21,6 +21,7 @@ blur = 14, keyboard = 15, semanticAction = 16, + gamepad = 17, }; } #endif \ No newline at end of file
diff --git a/include/rive/lua/rive_lua_libs.hpp b/include/rive/lua/rive_lua_libs.hpp index 224d2a6..d134944 100644 --- a/include/rive/lua/rive_lua_libs.hpp +++ b/include/rive/lua/rive_lua_libs.hpp
@@ -272,14 +272,21 @@ isReportedEvent, isViewModelChange, isNone, - isGamepad, + isGamepadConnected, + isGamepadEvent, + isGamepadDisconnected, asPointerEvent, asKeyboardEvent, asTextInput, asFocus, asReportedEvent, asViewModelChange, - asGamepad, + asGamepadConnected, + asGamepadEvent, + asGamepadDisconnected, + gamepadEvent, + gamepadConnected, + gamepadDisconnected, asNone, key, alt, @@ -290,7 +297,6 @@ delaySeconds, deviceId, buttonMask, - axis0, remove, removeAt, removeAllOf, @@ -340,6 +346,44 @@ transformVec4, writeToBuffer, invertAffine, + + // Gamepad + axes, + gamepadMapping, + mapping, + isStandardMapping, + buttons, + buttonPressed, + buttonValue, + axis, + west, + south, + north, + east, + leftShoulder, + rightShoulder, + gamepadBack, + gamepadForward, + leftStickButton, + rightStickButton, + dpadUp, + dpadDown, + dpadLeft, + dpadRight, + leftStick, + rightStick, + start, + leftTrigger, + rightTrigger, + leftTriggerPressed, + rightTriggerPressed, + changeKind, + changeIndex, + changeValue, + hasStandardButtonIntent, + hasStandardAxisIntent, + intentButton, + intentAxis, }; struct ScriptedMat2D @@ -1822,20 +1866,43 @@ static constexpr bool hasMetatable = true; }; -class ScriptedGamepadInvocation +class ScriptedGamepadConnected { public: - ScriptedGamepadInvocation(int deviceId, uint64_t buttonMask, float axis0) : - m_deviceId(deviceId), m_buttonMask(buttonMask), m_axis0(axis0) + explicit ScriptedGamepadConnected(const GamepadSnapshot& snapshot) : + m_snapshot(snapshot) {} - static constexpr uint8_t luaTag = LUA_T_COUNT + 60; - static constexpr const char* luaName = "GamepadInvocation"; + static constexpr uint8_t luaTag = LUA_T_COUNT + 48; + static constexpr const char* luaName = "GamepadConnected"; + static constexpr bool hasMetatable = true; + + GamepadSnapshot m_snapshot; +}; + +class ScriptedGamepadEvent +{ +public: + explicit ScriptedGamepadEvent(const GamepadEventInvocation& v) : m_data(v) + {} + + static constexpr uint8_t luaTag = LUA_T_COUNT + 63; + static constexpr const char* luaName = "GamepadEvent"; + static constexpr bool hasMetatable = true; + + GamepadEventInvocation m_data; +}; + +class ScriptedGamepadDisconnected +{ +public: + explicit ScriptedGamepadDisconnected(int deviceId) : m_deviceId(deviceId) {} + + static constexpr uint8_t luaTag = LUA_T_COUNT + 64; + static constexpr const char* luaName = "GamepadDisconnected"; static constexpr bool hasMetatable = true; int m_deviceId; - uint64_t m_buttonMask; - float m_axis0; }; class ScriptedNoneInvocation
diff --git a/include/rive/lua/scripting_vm.hpp b/include/rive/lua/scripting_vm.hpp index c4e0f5c..1a4310b 100644 --- a/include/rive/lua/scripting_vm.hpp +++ b/include/rive/lua/scripting_vm.hpp
@@ -5,6 +5,7 @@ #include "rive/refcnt.hpp" #include "rive/span.hpp" #include <memory> +#include <unordered_set> struct lua_State; @@ -12,6 +13,7 @@ { class ModuleDetails; class ScriptingContext; +class ScriptedObject; class ScriptingVM : public RefCnt<ScriptingVM> { @@ -21,6 +23,20 @@ ~ScriptingVM(); + // Closes the lua_State synchronously and runs all userdata finalizers. + // Idempotent. Called from ~ScriptingVM but exposed so call sites that + // need teardown to be observable (e.g. between editor file swaps) can + // force it. + void closeLuaState(); + + // ScriptedObject holds a non-owning raw ScriptingVM*. These methods let + // the VM track which ScriptedObjects point at it so ~ScriptingVM (and + // closeLuaState) can null those pointers before cascading lua_close + // finalizers tear down the ScriptedObjects via their owning userdatas. + // Otherwise those finalizers would dereference an already-freed VM. + void registerScriptedObject(ScriptedObject* obj); + void unregisterScriptedObject(ScriptedObject* obj); + ScriptingContext* context() { return m_ownedContext.get(); } lua_State* state() const { return m_state; } @@ -71,6 +87,7 @@ private: lua_State* m_state; std::unique_ptr<ScriptingContext> m_ownedContext; + std::unordered_set<ScriptedObject*> m_scriptedObjects; }; } // namespace rive
diff --git a/include/rive/nested_artboard.hpp b/include/rive/nested_artboard.hpp index 7566673..75b8396 100644 --- a/include/rive/nested_artboard.hpp +++ b/include/rive/nested_artboard.hpp
@@ -9,6 +9,7 @@ #include "rive/viewmodel/viewmodel_instance_value.hpp" #include "rive/hit_info.hpp" #include "rive/input/focusable.hpp" +#include "rive/animation/listener_invocation.hpp" #include "rive/span.hpp" #include "rive/advancing_component.hpp" #include "rive/resetting_component.hpp" @@ -129,6 +130,11 @@ // Focusable interface - delegates to nested state machines bool keyInput(Key, KeyModifiers, bool, bool) override { return false; }; bool textInput(const std::string&) override { return false; }; + bool gamepadDispatch(const ListenerInvocation&, + ScriptedDrawable** = nullptr) override + { + return false; + } void focused() override {} void blurred() override {} Artboard* focusableArtboard() const override { return artboard(); }
diff --git a/include/rive/scripted/scripted_drawable.hpp b/include/rive/scripted/scripted_drawable.hpp index 9493f7c..312f3c0 100644 --- a/include/rive/scripted/scripted_drawable.hpp +++ b/include/rive/scripted/scripted_drawable.hpp
@@ -1,6 +1,7 @@ #ifndef _RIVE_SCRIPTED_DRAWABLE_HPP_ #define _RIVE_SCRIPTED_DRAWABLE_HPP_ #include "rive/generated/scripted/scripted_drawable_base.hpp" +#include "rive/animation/listener_invocation.hpp" #include "rive/animation/state_machine_instance.hpp" #include "rive/advancing_component.hpp" #include "rive/assets/script_asset.hpp" @@ -56,6 +57,9 @@ bool worldToLocal(Vec2D world, Vec2D* local); void markNeedsUpdate() override; bool willDraw() override; +#ifdef WITH_RIVE_SCRIPTING + bool gamepadDispatch(const ListenerInvocation& invocation); +#endif Component* component() override { return this; } bool keyInput(Key key, KeyModifiers modifiers, @@ -93,6 +97,9 @@ bool canHit, float timeStamp, int pointerId) override; + HitResult processGamepadInvocation( + const ListenerInvocation& invocation, + ScriptedDrawable* alreadyDispatched) override; }; } // namespace rive
diff --git a/include/rive/scripted/scripted_object.hpp b/include/rive/scripted/scripted_object.hpp index b7c31bb..db4769a 100644 --- a/include/rive/scripted/scripted_object.hpp +++ b/include/rive/scripted/scripted_object.hpp
@@ -32,11 +32,14 @@ ScriptedContext* m_contextPtr = nullptr; virtual void disposeScriptInputs(); #ifdef WITH_RIVE_SCRIPTING -#ifdef WITH_RIVE_TOOLS - rcp<ScriptingVM> m_vm = nullptr; // Ref-counted for editor -#else - ScriptingVM* m_vm = nullptr; // Non-owning for runtime -#endif + // Non-owning. ScriptingVM tracks every ScriptedObject that points at it + // (via registerScriptedObject in ensureScriptInitialized) and nulls these + // out from ~ScriptingVM. Holding it as rcp would create a cycle: + // ScriptingVM → lua_State → ScriptedArtboard userdata → + // ScriptReffedArtboard → inner ArtboardInstance → ScriptedObject → + // rcp<ScriptingVM>. + ScriptingVM* m_vm = nullptr; + friend class ScriptingVM; #endif bool inUpdatePhase() const { return m_inUpdatePhase; } void setInUpdatePhase(bool value) { m_inUpdatePhase = value; }
diff --git a/include/rive/text/text_input.hpp b/include/rive/text/text_input.hpp index 6bca272..73b9d32 100644 --- a/include/rive/text/text_input.hpp +++ b/include/rive/text/text_input.hpp
@@ -5,6 +5,7 @@ #include "rive/advancing_component.hpp" #include "rive/text/raw_text_input.hpp" #include "rive/text/text_interface.hpp" +#include "rive/animation/listener_invocation.hpp" #include "rive/input/focusable.hpp" #include <cmath> @@ -49,6 +50,9 @@ bool isPressed, bool isRepeat) override; bool textInput(const std::string& text) override; + bool gamepadDispatch( + const ListenerInvocation& invocation, + ScriptedDrawable** outDispatchedScriptedDrawable = nullptr) override; void focused() override; void blurred() override; bool worldPosition(Vec2D& outPosition) override;
diff --git a/src/animation/gamepad_listener_group.cpp b/src/animation/gamepad_listener_group.cpp new file mode 100644 index 0000000..2a74469 --- /dev/null +++ b/src/animation/gamepad_listener_group.cpp
@@ -0,0 +1,59 @@ +#include "rive/animation/gamepad_listener_group.hpp" +#include "rive/animation/listener_invocation.hpp" +#include "rive/animation/listener_types/listener_input_type_gamepad.hpp" +#include "rive/animation/state_machine_instance.hpp" +#include "rive/animation/state_machine_listener.hpp" +#include "rive/scripted/scripted_drawable.hpp" +#include "rive/focus_data.hpp" + +using namespace rive; + +GamepadListenerGroup::GamepadListenerGroup( + FocusData* focusData, + const StateMachineListener* listener, + StateMachineInstance* stateMachineInstance) : + m_focusData(focusData), + m_listener(listener), + m_stateMachineInstance(stateMachineInstance) +{ + m_focusData->addGamepadListener(this); +} + +GamepadListenerGroup::~GamepadListenerGroup() +{ + m_focusData->removeGamepadListener(this); +} + +bool GamepadListenerGroup::gamepadDispatch( + const ListenerInvocation& invocation, + ScriptedDrawable** outDispatchedScriptedDrawable) +{ +#ifdef WITH_RIVE_SCRIPTING + if (m_focusData && m_focusData->parent()) + { + + auto parent = m_focusData->parent(); + if (parent->is<ScriptedDrawable>()) + { + auto* scriptedDrawable = parent->as<ScriptedDrawable>(); + bool handled = scriptedDrawable->gamepadDispatch(invocation); + // Report which scripted drawable consumed the focus-tree dispatch + // so a subsequent broadcast pass can skip it. + if (outDispatchedScriptedDrawable != nullptr) + { + *outDispatchedScriptedDrawable = scriptedDrawable; + } + return handled; + } + } +#endif + if (!m_listener || + !ListenerInputTypeGamepad::gamepadListenerConstraintsMet(m_listener, + invocation)) + { + return false; + } + m_listener->performChanges(m_stateMachineInstance, invocation); + m_stateMachineInstance->markNeedsAdvance(); + return false; +}
diff --git a/src/animation/listener_invocation.cpp b/src/animation/listener_invocation.cpp index c9012f5..129d221 100644 --- a/src/animation/listener_invocation.cpp +++ b/src/animation/listener_invocation.cpp
@@ -71,15 +71,25 @@ return ListenerInvocation(ListenerInvocationStorage(NoneInvocation{})); } -ListenerInvocation ListenerInvocation::gamepad(int deviceId, - uint64_t buttonMask, - float axis0) +ListenerInvocation ListenerInvocation::gamepadConnected( + const GamepadSnapshot& snapshot) { - GamepadInvocation g; - g.deviceId = deviceId; - g.buttonMask = buttonMask; - g.axis0 = axis0; - return ListenerInvocation(ListenerInvocationStorage(std::move(g))); + GamepadConnectedInvocation c; + c.snapshot = snapshot; + return ListenerInvocation(ListenerInvocationStorage(std::move(c))); +} + +ListenerInvocation ListenerInvocation::gamepadEvent( + GamepadEventInvocation value) +{ + return ListenerInvocation(ListenerInvocationStorage(std::move(value))); +} + +ListenerInvocation ListenerInvocation::gamepadDisconnected(int deviceId) +{ + GamepadDisconnectedInvocation d; + d.deviceId = deviceId; + return ListenerInvocation(ListenerInvocationStorage(std::move(d))); } ListenerInvocation ListenerInvocation::semantic(SemanticListenerGroup* group,
diff --git a/src/animation/listener_types/listener_input_type_gamepad.cpp b/src/animation/listener_types/listener_input_type_gamepad.cpp new file mode 100644 index 0000000..6049de9 --- /dev/null +++ b/src/animation/listener_types/listener_input_type_gamepad.cpp
@@ -0,0 +1,160 @@ +#include "rive/animation/listener_types/listener_input_type_gamepad.hpp" +#include "rive/animation/listener_invocation.hpp" +#include "rive/animation/state_machine_listener.hpp" +#include "rive/input/gamepad_snapshot.hpp" +#include "rive/input/standard_gamepad.hpp" +#include "rive/inputs/gamepad_button_phase.hpp" +#include "rive/inputs/gamepad_input.hpp" +#include "rive/inputs/gamepad_input_kind.hpp" + +using namespace rive; + +const GamepadInput* ListenerInputTypeGamepad::gamepadInput(size_t index) const +{ + if (index < m_gamepadInputs.size()) + { + return m_gamepadInputs[index]; + } + return nullptr; +} + +void ListenerInputTypeGamepad::addGamepadInput(GamepadInput* input) +{ + if (input == nullptr) + { + return; + } + for (GamepadInput* existing : m_gamepadInputs) + { + if (existing == input) + { + return; + } + } + m_gamepadInputs.push_back(input); +} + +bool ListenerInputTypeGamepad::gamepadButtonPhaseMatches(uint32_t phase, + bool isPressed) +{ + const uint32_t mask = phase & GamepadButtonPhaseMask::all; + if (mask == 0) + { + return false; + } + if (isPressed) + { + return (mask & GamepadButtonPhaseMask::down) != 0; + } + return (mask & GamepadButtonPhaseMask::up) != 0; +} + +bool ListenerInputTypeGamepad::gamepadInputMatches( + const GamepadInput& input, + const ListenerInvocation& invocation) +{ + const auto kind = static_cast<GamepadInputKind>(input.kind()); + switch (kind) + { + case GamepadInputKind::connected: + return invocation.asGamepadConnected() != nullptr; + case GamepadInputKind::disconnected: + return invocation.asGamepadDisconnected() != nullptr; + case GamepadInputKind::button: + case GamepadInputKind::axis: + { + const GamepadEventInvocation* ev = invocation.asGamepadEvent(); + if (ev == nullptr) + { + return false; + } + const bool wantButton = kind == GamepadInputKind::button; + const auto expected = wantButton ? GamepadInputChangeKind::button + : GamepadInputChangeKind::axis; + if (ev->change.kind != expected) + { + return false; + } + + const auto mapping = + static_cast<GamepadInputMapping>(input.mapping()); + if (mapping == GamepadInputMapping::standard) + { + if (wantButton) + { + if (!ev->hasStandardButtonIntent || + static_cast<uint32_t>(ev->standardButton) != + input.inputIndex()) + { + return false; + } + } + else + { + if (!ev->hasStandardAxisIntent || + static_cast<uint32_t>(ev->standardAxis) != + input.inputIndex()) + { + return false; + } + } + } + else + { + if (static_cast<uint32_t>(ev->change.index) != + input.inputIndex()) + { + return false; + } + } + + if (wantButton) + { + const bool isPressed = ev->change.value >= 0.5f; + return gamepadButtonPhaseMatches(input.buttonPhase(), + isPressed); + } + return true; + } + } + return false; +} + +bool ListenerInputTypeGamepad::gamepadListenerConstraintsMet( + const StateMachineListener* listener, + const ListenerInvocation& invocation) +{ + if (listener == nullptr) + { + return false; + } + for (size_t i = 0; i < listener->listenerInputTypeCount(); ++i) + { + const ListenerInputType* lit = listener->listenerInputType(i); + if (lit == nullptr || !lit->is<ListenerInputTypeGamepad>()) + { + continue; + } + const ListenerInputTypeGamepad* litg = + lit->as<ListenerInputTypeGamepad>(); + if (litg->gamepadInputCount() == 0) + { + return true; + } + bool anyMatches = false; + for (size_t j = 0; j < litg->gamepadInputCount(); ++j) + { + const GamepadInput* gi = litg->gamepadInput(j); + if (gi != nullptr && gamepadInputMatches(*gi, invocation)) + { + anyMatches = true; + break; + } + } + if (anyMatches) + { + return true; + } + } + return false; +}
diff --git a/src/animation/state_machine_instance.cpp b/src/animation/state_machine_instance.cpp index 0f0c9e9..988e7f2 100644 --- a/src/animation/state_machine_instance.cpp +++ b/src/animation/state_machine_instance.cpp
@@ -743,6 +743,13 @@ } } + HitResult processGamepadInvocation( + const ListenerInvocation& invocation, + ScriptedDrawable* alreadyDispatched) override + { + return HitResult::none; + } + HitResult processEvent(Vec2D position, ListenerType hitType, bool canHit, @@ -909,6 +916,25 @@ } return false; } + HitResult processGamepadInvocation( + const ListenerInvocation& invocation, + ScriptedDrawable* alreadyDispatched) override + { + auto hitResult = HitResult::none; + auto nestedArtboard = m_component->as<NestedArtboard>(); + for (auto nestedAnimation : nestedArtboard->nestedAnimations()) + { + if (nestedAnimation->is<NestedStateMachine>()) + { + auto nestedStateMachine = + nestedAnimation->as<NestedStateMachine>(); + nestedStateMachine->stateMachineInstance() + ->broadcastGamepadToScriptedDrawables(invocation, + alreadyDispatched); + } + } + return hitResult; + } HitResult processEvent(Vec2D position, ListenerType hitType, bool canHit, @@ -980,6 +1006,7 @@ case ListenerType::blur: case ListenerType::keyboard: case ListenerType::semanticAction: + case ListenerType::gamepad: break; } } @@ -1007,6 +1034,7 @@ case ListenerType::blur: case ListenerType::keyboard: case ListenerType::semanticAction: + case ListenerType::gamepad: break; } } @@ -1126,6 +1154,7 @@ case ListenerType::blur: case ListenerType::keyboard: case ListenerType::semanticAction: + case ListenerType::gamepad: break; } } @@ -1152,6 +1181,7 @@ case ListenerType::blur: case ListenerType::keyboard: case ListenerType::semanticAction: + case ListenerType::gamepad: break; } } @@ -1171,6 +1201,49 @@ } return hitResult; } + HitResult processGamepadInvocation( + const ListenerInvocation& invocation, + ScriptedDrawable* alreadyDispatched) override + { + auto componentList = m_component->as<ArtboardComponentList>(); + HitResult hitResult = HitResult::none; + bool runningCanHit = true; + if (componentList->isCollapsed()) + { + return hitResult; + } + const auto& order = componentList->orderedListIndices(); + for (auto it = order.rbegin(); it != order.rend(); ++it) + { + const int i = *it; + auto stateMachine = componentList->stateMachineInstance(i); + if (stateMachine != nullptr) + { + HitResult itemHitResult = HitResult::none; + if (runningCanHit) + { + itemHitResult = + stateMachine->broadcastGamepadToScriptedDrawables( + invocation, + alreadyDispatched); + } + + if ((hitResult == HitResult::none && + (itemHitResult == HitResult::hit || + itemHitResult == HitResult::hitOpaque)) || + (hitResult == HitResult::hit && + itemHitResult == HitResult::hitOpaque)) + { + hitResult = itemHitResult; + } + if (hitResult == HitResult::hitOpaque) + { + runningCanHit = false; + } + } + } + return hitResult; + } void prepareEvent(Vec2D position, ListenerType hitType, int pointerId) override @@ -1842,6 +1915,28 @@ } m_listenerGroups.push_back(std::move(listenerGroup)); } + if (listener->hasListener(ListenerType::gamepad)) + { + auto target = m_artboardInstance->resolve(listener->targetId()); + auto node = target->as<Node>(); + FocusData* focusData = nullptr; + for (auto child : node->children()) + { + if (child->is<FocusData>()) + { + focusData = child->as<FocusData>(); + break; + } + } + if (focusData != nullptr) + { + auto gamepadGroup = + std::make_unique<GamepadListenerGroup>(focusData, + listener, + this); + m_gamepadListenerGroups.push_back(std::move(gamepadGroup)); + } + } } std::vector<ListenerGroupProvider*> componentProvidedListenerGroups; @@ -1958,12 +2053,18 @@ scriptedPair.second->dataContext(m_artboardInstance->dataContext()); } initScriptedObjects(); - // Register Scripted objects as keyboard and text targets when expected + // Register Scripted objects as keyboard and text targets when expected, + // and collect every scripted drawable that wants gamepad events so we can + // broadcast to it later regardless of focus. for (auto object : instance->objects<ContainerComponent>()) { auto scriptedObject = ScriptedObject::from(object); - if (scriptedObject && (scriptedObject->wantsKeyboardInput() || - scriptedObject->wantsTextInput())) + if (!scriptedObject) + { + continue; + } + if (scriptedObject->wantsKeyboardInput() || + scriptedObject->wantsTextInput()) { for (auto& child : object->as<ContainerComponent>()->children()) { @@ -1981,6 +2082,14 @@ } } } + if ((scriptedObject->wantsGamePadConnect() || + scriptedObject->wantsGamePadDisconnect() || + scriptedObject->wantsGamePadEvent()) && + object->is<ScriptedDrawable>()) + { + m_gamepadScriptedDrawables.push_back( + object->as<ScriptedDrawable>()); + } } sortHitComponents(); @@ -2019,6 +2128,7 @@ { m_artboardInstance->cleanupSemanticTree(); } + m_embedderGamepads.clear(); unbind(); for (auto inst : m_inputInstances)
diff --git a/src/assets/script_asset.cpp b/src/assets/script_asset.cpp index 8b0021f..07733de 100644 --- a/src/assets/script_asset.cpp +++ b/src/assets/script_asset.cpp
@@ -148,6 +148,25 @@ m_implementedMethods |= m_wantsPointerExitBit; } rive_lua_pop(state, 1); + if (static_cast<lua_Type>( + lua_getfield(state, -1, "gamepadConnected")) == LUA_TFUNCTION) + { + m_implementedMethods |= m_wantsGamepadConnect; + } + rive_lua_pop(state, 1); + if (static_cast<lua_Type>(lua_getfield(state, -1, "gamepadEvent")) == + LUA_TFUNCTION) + { + m_implementedMethods |= m_wantsGamepadEvent; + } + rive_lua_pop(state, 1); + if (static_cast<lua_Type>( + lua_getfield(state, -1, "gamepadDisconnected")) == + LUA_TFUNCTION) + { + m_implementedMethods |= m_wantsGamepadDisconnect; + } + rive_lua_pop(state, 1); if (static_cast<lua_Type>(lua_getfield(state, -1, "init")) == LUA_TFUNCTION) {
diff --git a/src/file.cpp b/src/file.cpp index a00ecde..35f6f3c 100644 --- a/src/file.cpp +++ b/src/file.cpp
@@ -34,6 +34,7 @@ #include "rive/importers/state_transition_importer.hpp" #include "rive/importers/state_machine_layer_component_importer.hpp" #include "rive/importers/transition_viewmodel_condition_importer.hpp" +#include "rive/importers/listener_input_type_gamepad_importer.hpp" #include "rive/importers/listener_input_type_keyboard_importer.hpp" #include "rive/importers/listener_input_type_semantic_importer.hpp" #include "rive/importers/viewmodel_importer.hpp" @@ -479,6 +480,12 @@ object->as<ListenerInputTypeKeyboard>()); stackType = ListenerInputTypeKeyboardBase::typeKey; break; + case ListenerInputTypeGamepadBase::typeKey: + stackObject = + std::make_unique<ListenerInputTypeGamepadImporter>( + object->as<ListenerInputTypeGamepad>()); + stackType = ListenerInputTypeGamepadBase::typeKey; + break; case ListenerInputTypeSemanticBase::typeKey: stackObject = std::make_unique<ListenerInputTypeSemanticImporter>( @@ -757,6 +764,11 @@ } } #endif + // ScriptedObjects only hold a raw ScriptingVM* (see + // ScriptingVM::registerScriptedObject), so dropping our rcp here is the + // only thing keeping the VM alive from File's side. If Dart still holds + // its own rcp<ScriptingVM> (editor flow), the VM and lua_State stay + // alive until Dart releases too. ~ScriptingVM handles lua_close. m_scriptingVM = nullptr; } #endif
diff --git a/src/focus_data.cpp b/src/focus_data.cpp index 6a79977..631e619 100644 --- a/src/focus_data.cpp +++ b/src/focus_data.cpp
@@ -116,6 +116,22 @@ } } +void FocusData::addGamepadListener(GamepadListener* listener) +{ + m_gamepadListeners.push_back(listener); +} + +void FocusData::removeGamepadListener(GamepadListener* listener) +{ + auto it = std::find(m_gamepadListeners.begin(), + m_gamepadListeners.end(), + listener); + if (it != m_gamepadListeners.end()) + { + m_gamepadListeners.erase(it); + } +} + void FocusData::focus() { // Note: In C++ runtime, focus() needs a FocusManager to set focus. @@ -153,6 +169,21 @@ return false; } +bool FocusData::gamepadDispatch( + const ListenerInvocation& invocation, + ScriptedDrawable** outDispatchedScriptedDrawable) +{ + for (auto* listener : m_gamepadListeners) + { + if (listener->gamepadDispatch(invocation, + outDispatchedScriptedDrawable)) + { + return true; + } + } + return false; +} + void FocusData::scrollIntoView() { // Find closest LayoutComponent ancestor
diff --git a/src/generated/animation/listener_types/listener_input_type_gamepad_base.cpp b/src/generated/animation/listener_types/listener_input_type_gamepad_base.cpp new file mode 100644 index 0000000..4ed5c1f --- /dev/null +++ b/src/generated/animation/listener_types/listener_input_type_gamepad_base.cpp
@@ -0,0 +1,11 @@ +#include "rive/generated/animation/listener_types/listener_input_type_gamepad_base.hpp" +#include "rive/animation/listener_types/listener_input_type_gamepad.hpp" + +using namespace rive; + +Core* ListenerInputTypeGamepadBase::clone() const +{ + auto cloned = new ListenerInputTypeGamepad(); + cloned->copy(*this); + return cloned; +}
diff --git a/src/generated/inputs/gamepad_input_base.cpp b/src/generated/inputs/gamepad_input_base.cpp new file mode 100644 index 0000000..6794fd3 --- /dev/null +++ b/src/generated/inputs/gamepad_input_base.cpp
@@ -0,0 +1,11 @@ +#include "rive/generated/inputs/gamepad_input_base.hpp" +#include "rive/inputs/gamepad_input.hpp" + +using namespace rive; + +Core* GamepadInputBase::clone() const +{ + auto cloned = new GamepadInput(); + cloned->copy(*this); + return cloned; +}
diff --git a/src/importers/listener_input_type_gamepad_importer.cpp b/src/importers/listener_input_type_gamepad_importer.cpp new file mode 100644 index 0000000..67e00b8 --- /dev/null +++ b/src/importers/listener_input_type_gamepad_importer.cpp
@@ -0,0 +1,13 @@ +#include "rive/importers/listener_input_type_gamepad_importer.hpp" + +using namespace rive; + +ListenerInputTypeGamepadImporter::ListenerInputTypeGamepadImporter( + ListenerInputTypeGamepad* listenerInputTypeGamepad) : + m_listenerInputTypeGamepad(listenerInputTypeGamepad) +{} + +StatusCode ListenerInputTypeGamepadImporter::resolve() +{ + return StatusCode::Ok; +}
diff --git a/src/input/focus_manager.cpp b/src/input/focus_manager.cpp index bef2613..f31c241 100644 --- a/src/input/focus_manager.cpp +++ b/src/input/focus_manager.cpp
@@ -5,6 +5,7 @@ #include "rive/input/focus_manager.hpp" #include "rive/artboard.hpp" #include "rive/artboard_host.hpp" +#include "rive/animation/listener_invocation.hpp" #include "rive/focus_data.hpp" #include "rive/math/aabb.hpp" #include <algorithm> @@ -634,6 +635,23 @@ return false; } +bool FocusManager::gamepadDispatch( + const ListenerInvocation& invocation, + ScriptedDrawable** outDispatchedScriptedDrawable) +{ + dropFocusIfFocusTargetHidden(); + FocusNode* node = m_primaryFocus.get(); + while (node != nullptr) + { + if (node->gamepadDispatch(invocation, outDispatchedScriptedDrawable)) + { + return true; + } + node = node->parent(); + } + return false; +} + void FocusManager::notifyFocusChange(FocusNode* oldFocus, FocusNode* newFocus) { // Find the common ancestor to avoid unnecessary blur/focus notifications
diff --git a/src/input/focusable.cpp b/src/input/focusable.cpp index 43ce68e..377ede2 100644 --- a/src/input/focusable.cpp +++ b/src/input/focusable.cpp
@@ -1,9 +1,15 @@ +#include "rive/animation/listener_invocation.hpp" #include "rive/input/focusable.hpp" #include "rive/nested_artboard.hpp" #include "rive/text/text_input.hpp" using namespace rive; +bool Focusable::gamepadDispatch(const ListenerInvocation&, ScriptedDrawable**) +{ + return false; +} + Focusable* Focusable::from(Core* object) { if (object == nullptr)
diff --git a/src/input/gamepad_batch.cpp b/src/input/gamepad_batch.cpp new file mode 100644 index 0000000..1dffff6 --- /dev/null +++ b/src/input/gamepad_batch.cpp
@@ -0,0 +1,363 @@ +#include "rive/animation/listener_invocation.hpp" +#include "rive/animation/state_machine_instance.hpp" +#include "rive/core/binary_reader.hpp" +#include "rive/input/focus_manager.hpp" +#include "rive/input/gamepad_batch.hpp" +#include "rive/input/gamepad_snapshot.hpp" +#include "rive/input/standard_gamepad.hpp" +#include "rive/scripted/scripted_drawable.hpp" +#include "rive/span.hpp" + +namespace rive +{ + +static void recomputeButtonMaskFromValues(GamepadSnapshot& s) +{ + s.buttonMask = 0; + for (size_t i = 0; i < s.buttonValues.size(); i++) + { + if (s.buttonValues[i] >= 0.5f) + { + s.buttonMask |= (uint64_t(1) << i); + } + } +} + +static void fillStandardIntent(const GamepadSnapshot& snap, + GamepadEventInvocation& ev) +{ + ev.hasStandardButtonIntent = false; + ev.hasStandardAxisIntent = false; + if (snap.mapping != GamepadMappingKind::standard) + { + return; + } + if (ev.change.kind == GamepadInputChangeKind::button) + { + if (ev.change.index <= + static_cast<uint8_t>(StandardGamepadButton::start)) + { + ev.hasStandardButtonIntent = true; + ev.standardButton = + static_cast<StandardGamepadButton>(ev.change.index); + } + } + else + { + if (ev.change.index <= + static_cast<uint8_t>(StandardGamepadAxis::rightTrigger)) + { + ev.hasStandardAxisIntent = true; + ev.standardAxis = static_cast<StandardGamepadAxis>(ev.change.index); + } + } +} + +static bool readConnectedPayload(BinaryReader& reader, + GamepadSnapshot& outSnapshot) +{ + outSnapshot = GamepadSnapshot{}; + outSnapshot.deviceId = static_cast<int32_t>(reader.readUint32()); + const uint8_t mappingByte = reader.readByte(); + const uint8_t nButtons = reader.readByte(); + const uint8_t nAxes = reader.readByte(); + reader.readByte(); // 1-byte padding to align the float arrays. + if (reader.hasError() || nButtons > kGamepadBatchMaxButtons || + nAxes > kGamepadBatchMaxAxes) + { + return false; + } + outSnapshot.mapping = mappingByte == 0 ? GamepadMappingKind::standard + : GamepadMappingKind::unknown; + outSnapshot.buttonValues.resize(nButtons); + outSnapshot.axes.resize(nAxes); + for (uint8_t b = 0; b < nButtons; b++) + { + outSnapshot.buttonValues[b] = reader.readFloat32(); + } + for (uint8_t a = 0; a < nAxes; a++) + { + outSnapshot.axes[a] = reader.readFloat32(); + } + if (reader.hasError()) + { + return false; + } + // buttonMask is not on the wire — derive it from the per-button values. + recomputeButtonMaskFromValues(outSnapshot); + return true; +} + +static bool applyUpdateChange(GamepadSnapshot& snap, + const GamepadInputChange& ch) +{ + if (ch.kind == GamepadInputChangeKind::button) + { + if (ch.index >= kGamepadBatchMaxButtons) + { + return false; + } + if (snap.buttonValues.size() <= ch.index) + { + snap.buttonValues.resize(ch.index + 1, 0.f); + } + snap.buttonValues[ch.index] = ch.value; + recomputeButtonMaskFromValues(snap); + } + else + { + if (ch.index >= kGamepadBatchMaxAxes) + { + return false; + } + if (snap.axes.size() <= ch.index) + { + snap.axes.resize(ch.index + 1, 0.f); + } + snap.axes[ch.index] = ch.value; + } + return true; +} + +static GamepadEventInvocation makeEventInvocation( + const GamepadSnapshot& afterApply, + const GamepadInputChange& ch) +{ + GamepadEventInvocation ev; + ev.fullState = afterApply; + ev.change = ch; + fillStandardIntent(afterApply, ev); + return ev; +} + +// Decode a little-endian binary batch of gamepad events produced by the +// embedder (e.g. the JS runtime — see registerGamepadInteractions.ts) and +// dispatch them through the focus manager. +// +// Wire format (all multi-byte values little-endian, fixed-width — no LEB128): +// uint32 version -- must equal kGamepadBatchWireVersion +// then a stream of records, each starting with a 1-byte GamepadRecordType: +// +// connected (0): +// int32 deviceId +// uint8 mapping (0 = standard, else unknown) +// uint8 nButtons (<= kGamepadBatchMaxButtons) +// uint8 nAxes (<= kGamepadBatchMaxAxes) +// uint8 padding (alignment filler) +// float32 buttonValues[nButtons] +// float32 axes[nAxes] +// +// update (1): +// int32 deviceId +// uint8 nChanges +// repeated nChanges times: +// uint8 kind (0 = button, 1 = axis) +// uint8 index +// float32 value +// +// disconnected (2): +// int32 deviceId +// +// Returns false (and stops dispatching) on any malformed record: short read, +// wrong version, unknown device on update, out-of-range button/axis index, +// or unknown record type. A truncated batch leaves any records dispatched so +// far in place. +bool StateMachineInstance::submitGamepadsFromBuffer(const uint8_t* data, + size_t n) +{ + if (data == nullptr) + { + return false; + } + BinaryReader reader(Span<const uint8_t>(data, n)); + const uint32_t version = reader.readUint32(); + if (reader.hasError() || version != kGamepadBatchWireVersion) + { + return false; + } + FocusManager* fm = focusManager(); + if (fm == nullptr) + { + return false; + } + // reachedEnd() returns true once the cursor hits end-of-buffer OR the + // reader has flagged an overflow, so any partial-record read inside the + // loop will both `return false` and naturally terminate iteration. + while (!reader.reachedEnd()) + { + const uint8_t typeByte = reader.readByte(); + if (reader.hasError()) + { + return false; + } + const auto rec = static_cast<GamepadRecordType>(typeByte); + switch (rec) + { + case GamepadRecordType::connected: + { + GamepadSnapshot snap; + if (!readConnectedPayload(reader, snap)) + { + return false; + } + m_embedderGamepads[snap.deviceId] = snap; + { + auto invocation = + ListenerInvocation::gamepadConnected(snap); + ScriptedDrawable* dispatched = nullptr; + (void)fm->gamepadDispatch(invocation, &dispatched); + broadcastGamepadToScriptedDrawables(invocation, dispatched); + } + break; + } + case GamepadRecordType::update: + { + const int32_t deviceId = + static_cast<int32_t>(reader.readUint32()); + const uint8_t nChanges = reader.readByte(); + if (reader.hasError()) + { + return false; + } + // Updates must target a gamepad we've previously seen + // connected; otherwise we have no snapshot to mutate. + auto it = m_embedderGamepads.find(deviceId); + if (it == m_embedderGamepads.end()) + { + return false; + } + std::vector<GamepadInputChange> changes; + changes.reserve(nChanges); + for (uint8_t i = 0; i < nChanges; i++) + { + const uint8_t chKindB = reader.readByte(); + const uint8_t chIndex = reader.readByte(); + const float fval = reader.readFloat32(); + if (reader.hasError()) + { + return false; + } + GamepadInputChange ch; + ch.kind = chKindB == 0 ? GamepadInputChangeKind::button + : GamepadInputChangeKind::axis; + ch.index = chIndex; + ch.value = fval; + changes.push_back(ch); + } + // Apply all changes to the stored snapshot first so that every + // dispatched event sees the same fully-updated `fullState`... + GamepadSnapshot& snap = it->second; + for (const auto& ch : changes) + { + if (!applyUpdateChange(snap, ch)) + { + return false; + } + } + // ...then dispatch one event per change carrying that final + // state plus the specific change that occurred. + const GamepadSnapshot finalSnap = snap; + for (const auto& ch : changes) + { + GamepadEventInvocation evi = + makeEventInvocation(finalSnap, ch); + auto invocation = + ListenerInvocation::gamepadEvent(std::move(evi)); + ScriptedDrawable* dispatched = nullptr; + (void)fm->gamepadDispatch(invocation, &dispatched); + broadcastGamepadToScriptedDrawables(invocation, dispatched); + } + break; + } + case GamepadRecordType::disconnected: + { + const int32_t deviceId = + static_cast<int32_t>(reader.readUint32()); + if (reader.hasError()) + { + return false; + } + m_embedderGamepads.erase(deviceId); + { + auto invocation = + ListenerInvocation::gamepadDisconnected(deviceId); + ScriptedDrawable* dispatched = nullptr; + (void)fm->gamepadDispatch(invocation, &dispatched); + broadcastGamepadToScriptedDrawables(invocation, dispatched); + } + break; + } + default: + // Unknown record type — wire format mismatch, bail out. + return false; + } + } + return true; +} + +HitResult StateMachineInstance::broadcastGamepadToScriptedDrawables( + const ListenerInvocation& invocation, + ScriptedDrawable* alreadyDispatched) +{ + bool hitSomething = false; + bool hitOpaque = false; + // Walk m_hitComponents purely for the nested-propagation overrides + // (HitNestedArtboard / HitArtboardComponentList recurse into their + // child SMIs). HitScriptedDrawable's gamepad path is intentionally a + // no-op — direct dispatch happens via m_gamepadScriptedDrawables below + // so scripts without pointer handlers are still reached. + for (const auto& hitShape : m_hitComponents) + { + HitResult hitResult = + hitShape->processGamepadInvocation(invocation, alreadyDispatched); + if (hitResult != HitResult::none) + { + hitSomething = true; + if (hitResult == HitResult::hitOpaque) + { + hitOpaque = true; + } + } + } + +#ifdef WITH_RIVE_SCRIPTING + for (ScriptedDrawable* drawable : m_gamepadScriptedDrawables) + { + if (drawable == nullptr || drawable == alreadyDispatched) + { + continue; + } + switch (invocation.kind()) + { + case ListenerInvocationKind::gamepadConnected: + if (!drawable->wantsGamePadConnect()) + { + continue; + } + break; + case ListenerInvocationKind::gamepadEvent: + if (!drawable->wantsGamePadEvent()) + { + continue; + } + break; + case ListenerInvocationKind::gamepadDisconnected: + if (!drawable->wantsGamePadDisconnect()) + { + continue; + } + break; + default: + continue; + } + if (drawable->gamepadDispatch(invocation)) + { + hitSomething = true; + } + } +#endif + + return hitSomething ? hitOpaque ? HitResult::hitOpaque : HitResult::hit + : HitResult::none; +} +} // namespace rive
diff --git a/src/inputs/gamepad_input.cpp b/src/inputs/gamepad_input.cpp new file mode 100644 index 0000000..29d42f3 --- /dev/null +++ b/src/inputs/gamepad_input.cpp
@@ -0,0 +1,28 @@ +#include "rive/inputs/gamepad_input.hpp" +#include "rive/animation/listener_types/listener_input_type_gamepad.hpp" +#include "rive/generated/animation/listener_types/listener_input_type_gamepad_base.hpp" +#include "rive/generated/artboard_base.hpp" +#include "rive/importers/artboard_importer.hpp" +#include "rive/importers/listener_input_type_gamepad_importer.hpp" + +using namespace rive; + +StatusCode GamepadInput::import(ImportStack& importStack) +{ + auto* litImporter = importStack.latest<ListenerInputTypeGamepadImporter>( + ListenerInputTypeGamepadBase::typeKey); + if (litImporter == nullptr) + { + return StatusCode::MissingObject; + } + litImporter->listenerInputTypeGamepad()->addGamepadInput(this); + + auto artboardImporter = + importStack.latest<ArtboardImporter>(ArtboardBase::typeKey); + if (artboardImporter == nullptr) + { + return StatusCode::MissingObject; + } + artboardImporter->addComponent(this); + return Super::import(importStack); +}
diff --git a/src/lua/lua_artboards.cpp b/src/lua/lua_artboards.cpp index e014acf..63b83d7 100644 --- a/src/lua/lua_artboards.cpp +++ b/src/lua/lua_artboards.cpp
@@ -2,7 +2,9 @@ #include "rive/lua/rive_lua_libs.hpp" #include "rive/file.hpp" #include "rive/artboard.hpp" +#include "rive/animation/listener_invocation.hpp" #include "rive/animation/state_machine_instance.hpp" +#include "rive/input/focus_manager.hpp" #include "rive/viewmodel/viewmodel_property_number.hpp" #include "rive/viewmodel/viewmodel_property_trigger.hpp" #include "rive/node.hpp" @@ -134,6 +136,50 @@ return 1; } +static int apply_gamepad_event(lua_State* L, int atom) +{ + auto scriptedArtboard = lua_torive<ScriptedArtboard>(L, 1); + auto result = 0; + auto stateMachine = scriptedArtboard->stateMachine(); + if (stateMachine) + { + auto dispatch = [&](const ListenerInvocation& invocation) { + ScriptedDrawable* dispatched = nullptr; + (void)stateMachine->focusManager()->gamepadDispatch(invocation, + &dispatched); + result = (int)stateMachine->broadcastGamepadToScriptedDrawables( + invocation, + dispatched); + }; + switch (atom) + { + case (int)LuaAtoms::gamepadConnected: + { + auto* connected = lua_torive<ScriptedGamepadConnected>(L, 2); + dispatch(ListenerInvocation::gamepadConnected( + connected->m_snapshot)); + break; + } + case (int)LuaAtoms::gamepadEvent: + { + auto* event = lua_torive<ScriptedGamepadEvent>(L, 2); + dispatch(ListenerInvocation::gamepadEvent(event->m_data)); + break; + } + case (int)LuaAtoms::gamepadDisconnected: + { + auto* disconnected = + lua_torive<ScriptedGamepadDisconnected>(L, 2); + dispatch(ListenerInvocation::gamepadDisconnected( + disconnected->m_deviceId)); + break; + } + } + } + lua_pushinteger(L, result); + return 1; +} + static int artboard_advance(lua_State* L) { auto scriptedArtboard = lua_torive<ScriptedArtboard>(L, 1); @@ -233,6 +279,12 @@ { return apply_pointer_event(L, atom); } + case (int)LuaAtoms::gamepadEvent: + case (int)LuaAtoms::gamepadConnected: + case (int)LuaAtoms::gamepadDisconnected: + { + return apply_gamepad_event(L, atom); + } } }
diff --git a/src/lua/lua_listener_invocation.cpp b/src/lua/lua_listener_invocation.cpp index babdcb0..e2d265a 100644 --- a/src/lua/lua_listener_invocation.cpp +++ b/src/lua/lua_listener_invocation.cpp
@@ -1,10 +1,122 @@ #ifdef WITH_RIVE_SCRIPTING #include "rive/lua/rive_lua_libs.hpp" +#include "rive/input/standard_gamepad.hpp" #include "lualib.h" namespace rive { +namespace +{ + +bool gamepadIsStandardMapping(const GamepadSnapshot& s) +{ + return s.mapping == GamepadMappingKind::standard; +} + +void pushStandardButton(lua_State* L, + const GamepadSnapshot& s, + StandardGamepadButton b) +{ + if (!gamepadIsStandardMapping(s)) + { + lua_pushboolean(L, 0); + return; + } + lua_pushboolean(L, standardGamepadButtonPressed(s.buttonMask, b) ? 1 : 0); +} + +void pushStick(lua_State* L, + const GamepadSnapshot& s, + StandardGamepadAxis ax, + StandardGamepadAxis ay) +{ + if (!gamepadIsStandardMapping(s)) + { + lua_pushvector2(L, 0.f, 0.f); + return; + } + lua_pushvector2(L, + standardGamepadAxisValue(s.axes, ax), + standardGamepadAxisValue(s.axes, ay)); +} + +void pushTriggerAxis(lua_State* L, + const GamepadSnapshot& s, + StandardGamepadAxis a) +{ + if (!gamepadIsStandardMapping(s)) + { + lua_pushnumber(L, 0.); + return; + } + lua_pushnumber(L, standardGamepadAxisValue(s.axes, a)); +} + +const char* standardButtonLabel(StandardGamepadButton b) +{ + switch (b) + { + case StandardGamepadButton::south: + return "south"; + case StandardGamepadButton::east: + return "east"; + case StandardGamepadButton::west: + return "west"; + case StandardGamepadButton::north: + return "north"; + case StandardGamepadButton::leftShoulder: + return "leftShoulder"; + case StandardGamepadButton::rightShoulder: + return "rightShoulder"; + case StandardGamepadButton::leftTrigger: + return "leftTrigger"; + case StandardGamepadButton::rightTrigger: + return "rightTrigger"; + case StandardGamepadButton::back: + return "back"; + case StandardGamepadButton::forward: + return "forward"; + case StandardGamepadButton::leftStick: + return "leftStick"; + case StandardGamepadButton::rightStick: + return "rightStick"; + case StandardGamepadButton::dpadUp: + return "dpadUp"; + case StandardGamepadButton::dpadDown: + return "dpadDown"; + case StandardGamepadButton::dpadLeft: + return "dpadLeft"; + case StandardGamepadButton::dpadRight: + return "dpadRight"; + case StandardGamepadButton::start: + return "start"; + } + return "unknown"; +} + +const char* standardAxisLabel(StandardGamepadAxis a) +{ + switch (a) + { + case StandardGamepadAxis::leftX: + return "leftX"; + case StandardGamepadAxis::leftY: + return "leftY"; + case StandardGamepadAxis::rightX: + return "rightX"; + case StandardGamepadAxis::rightY: + return "rightY"; + case StandardGamepadAxis::leftTrigger: + return "leftTriggerAxis"; + case StandardGamepadAxis::rightTrigger: + return "rightTriggerAxis"; + } + return "unknown"; +} + +} // namespace + void rive_lua_push_pointer_arg_for_perform(lua_State* L, const ListenerInvocation& inv) { @@ -70,8 +182,14 @@ ListenerInvocationKind::viewModelChange); case (int)LuaAtoms::isNone: return pushBool(inv.kind() == ListenerInvocationKind::none); - case (int)LuaAtoms::isGamepad: - return pushBool(inv.kind() == ListenerInvocationKind::gamepad); + case (int)LuaAtoms::isGamepadConnected: + return pushBool(inv.kind() == + ListenerInvocationKind::gamepadConnected); + case (int)LuaAtoms::isGamepadEvent: + return pushBool(inv.kind() == ListenerInvocationKind::gamepadEvent); + case (int)LuaAtoms::isGamepadDisconnected: + return pushBool(inv.kind() == + ListenerInvocationKind::gamepadDisconnected); case (int)LuaAtoms::asPointerEvent: if (const PointerInvocation* p = inv.asPointer()) @@ -138,13 +256,29 @@ lua_pushnil(L); return 1; - case (int)LuaAtoms::asGamepad: - if (const GamepadInvocation* g = inv.asGamepad()) + case (int)LuaAtoms::asGamepadConnected: + if (const GamepadConnectedInvocation* g = inv.asGamepadConnected()) { - lua_newrive<ScriptedGamepadInvocation>(L, - g->deviceId, - g->buttonMask, - g->axis0); + lua_newrive<ScriptedGamepadConnected>(L, g->snapshot); + return 1; + } + lua_pushnil(L); + return 1; + + case (int)LuaAtoms::asGamepadEvent: + if (const GamepadEventInvocation* e = inv.asGamepadEvent()) + { + lua_newrive<ScriptedGamepadEvent>(L, *e); + return 1; + } + lua_pushnil(L); + return 1; + + case (int)LuaAtoms::asGamepadDisconnected: + if (const GamepadDisconnectedInvocation* d = + inv.asGamepadDisconnected()) + { + lua_newrive<ScriptedGamepadDisconnected>(L, d->deviceId); return 1; } lua_pushnil(L); @@ -221,27 +355,6 @@ ((ScriptedReportedEventInvocation*)udata)->m_delaySeconds); } -static void gamepad_invocation_direct_deviceId(void* udata, void* result) -{ - lua_userdatadirectfield_setnumber( - result, - (double)((ScriptedGamepadInvocation*)udata)->m_deviceId); -} - -static void gamepad_invocation_direct_buttonMask(void* udata, void* result) -{ - lua_userdatadirectfield_setnumber( - result, - (double)((ScriptedGamepadInvocation*)udata)->m_buttonMask); -} - -static void gamepad_invocation_direct_axis0(void* udata, void* result) -{ - lua_userdatadirectfield_setnumber( - result, - ((ScriptedGamepadInvocation*)udata)->m_axis0); -} - static int keyboard_invocation_index(lua_State* L) { int atom; @@ -374,6 +487,69 @@ return 0; } +static int gamepad_snapshot_namecall(lua_State* L, const GamepadSnapshot& snap) +{ + int atom; + const char* str = lua_namecallatom(L, &atom); + if (str == nullptr) + { + luaL_error(L, "invalid call"); + return 0; + } + const lua_Integer idx = luaL_checkinteger(L, 2); + switch (atom) + { + case (int)LuaAtoms::buttonPressed: + if (idx < 1 || idx > 64) + { + lua_pushboolean(L, 0); + return 1; + } + lua_pushboolean(L, + (snap.buttonMask & + (uint64_t(1) << static_cast<unsigned>(idx - 1))) != + 0 + ? 1 + : 0); + return 1; + case (int)LuaAtoms::buttonValue: + if (idx < 1 || static_cast<size_t>(idx) > snap.buttonValues.size()) + { + lua_pushnumber(L, 0.); + return 1; + } + lua_pushnumber(L, snap.buttonValues[static_cast<size_t>(idx) - 1]); + return 1; + case (int)LuaAtoms::axis: + if (idx < 1 || static_cast<size_t>(idx) > snap.axes.size()) + { + lua_pushnumber(L, 0.); + return 1; + } + lua_pushnumber(L, snap.axes[static_cast<size_t>(idx) - 1]); + return 1; + } + luaL_error(L, + "%s is not a valid method of gamepad data", + luaL_checkstring(L, 1)); + return 0; +} + +static int gamepad_connected_namecall(lua_State* L) +{ + auto* g = lua_torive<ScriptedGamepadConnected>(L, 1); + return gamepad_snapshot_namecall(L, g->m_snapshot); +} + +static int gamepad_event_namecall(lua_State* L) +{ + auto* g = lua_torive<ScriptedGamepadEvent>(L, 1); + return gamepad_snapshot_namecall(L, g->m_data.fullState); +} + +static int gamepad_snapshot_index(lua_State* L, + int atom, + const GamepadSnapshot& snap); static int gamepad_invocation_index(lua_State* L) { int atom; @@ -383,23 +559,219 @@ luaL_typeerrorL(L, 2, lua_typename(L, LUA_TSTRING)); return 0; } - auto* g = lua_torive<ScriptedGamepadInvocation>(L, 1); + auto* g = lua_torive<ScriptedGamepadConnected>(L, 1); + return gamepad_snapshot_index(L, atom, g->m_snapshot); +} + +static int gamepad_snapshot_index(lua_State* L, + int atom, + const GamepadSnapshot& snap) +{ + switch (atom) + { + case (int)LuaAtoms::deviceId: + lua_pushinteger(L, snap.deviceId); + return 1; + case (int)LuaAtoms::buttonMask: + lua_pushnumber(L, static_cast<double>(snap.buttonMask)); + return 1; + case (int)LuaAtoms::buttons: + { + const auto& bv = snap.buttonValues; + lua_createtable(L, static_cast<int>(bv.size()), 0); + for (size_t i = 0; i < bv.size(); ++i) + { + lua_pushnumber(L, bv[i]); + lua_rawseti(L, -2, static_cast<int>(i + 1)); + } + return 1; + } + case (int)LuaAtoms::axes: + { + const auto& ax = snap.axes; + lua_createtable(L, static_cast<int>(ax.size()), 0); + for (size_t i = 0; i < ax.size(); ++i) + { + lua_pushnumber(L, ax[i]); + lua_rawseti(L, -2, static_cast<int>(i + 1)); + } + return 1; + } + case (int)LuaAtoms::gamepadMapping: + lua_pushinteger(L, static_cast<int>(snap.mapping)); + return 1; + case (int)LuaAtoms::mapping: + if (snap.mapping == GamepadMappingKind::standard) + { + lua_pushstring(L, "standard"); + } + else + { + lua_pushstring(L, "unknown"); + } + return 1; + case (int)LuaAtoms::isStandardMapping: + lua_pushboolean(L, gamepadIsStandardMapping(snap) ? 1 : 0); + return 1; + case (int)LuaAtoms::west: + pushStandardButton(L, snap, StandardGamepadButton::west); + return 1; + case (int)LuaAtoms::south: + pushStandardButton(L, snap, StandardGamepadButton::south); + return 1; + case (int)LuaAtoms::north: + pushStandardButton(L, snap, StandardGamepadButton::north); + return 1; + case (int)LuaAtoms::east: + pushStandardButton(L, snap, StandardGamepadButton::east); + return 1; + case (int)LuaAtoms::leftShoulder: + pushStandardButton(L, snap, StandardGamepadButton::leftShoulder); + return 1; + case (int)LuaAtoms::rightShoulder: + pushStandardButton(L, snap, StandardGamepadButton::rightShoulder); + return 1; + case (int)LuaAtoms::gamepadBack: + pushStandardButton(L, snap, StandardGamepadButton::back); + return 1; + case (int)LuaAtoms::gamepadForward: + pushStandardButton(L, snap, StandardGamepadButton::forward); + return 1; + case (int)LuaAtoms::leftStickButton: + pushStandardButton(L, snap, StandardGamepadButton::leftStick); + return 1; + case (int)LuaAtoms::rightStickButton: + pushStandardButton(L, snap, StandardGamepadButton::rightStick); + return 1; + case (int)LuaAtoms::dpadUp: + pushStandardButton(L, snap, StandardGamepadButton::dpadUp); + return 1; + case (int)LuaAtoms::dpadDown: + pushStandardButton(L, snap, StandardGamepadButton::dpadDown); + return 1; + case (int)LuaAtoms::dpadLeft: + pushStandardButton(L, snap, StandardGamepadButton::dpadLeft); + return 1; + case (int)LuaAtoms::dpadRight: + pushStandardButton(L, snap, StandardGamepadButton::dpadRight); + return 1; + case (int)LuaAtoms::start: + pushStandardButton(L, snap, StandardGamepadButton::start); + return 1; + case (int)LuaAtoms::leftTriggerPressed: + pushStandardButton(L, snap, StandardGamepadButton::leftTrigger); + return 1; + case (int)LuaAtoms::rightTriggerPressed: + pushStandardButton(L, snap, StandardGamepadButton::rightTrigger); + return 1; + case (int)LuaAtoms::leftStick: + pushStick(L, + snap, + StandardGamepadAxis::leftX, + StandardGamepadAxis::leftY); + return 1; + case (int)LuaAtoms::rightStick: + pushStick(L, + snap, + StandardGamepadAxis::rightX, + StandardGamepadAxis::rightY); + return 1; + case (int)LuaAtoms::leftTrigger: + pushTriggerAxis(L, snap, StandardGamepadAxis::leftTrigger); + return 1; + case (int)LuaAtoms::rightTrigger: + pushTriggerAxis(L, snap, StandardGamepadAxis::rightTrigger); + return 1; + } + luaL_error(L, + "%s is not a valid field of gamepad state", + luaL_checkstring(L, 1)); + return 0; +} + +static int gamepad_event_index(lua_State* L) +{ + int atom; + const char* key = lua_tostringatom(L, 2, &atom); + if (!key) + { + luaL_typeerrorL(L, 2, lua_typename(L, LUA_TSTRING)); + return 0; + } + auto* g = lua_torive<ScriptedGamepadEvent>(L, 1); + const GamepadEventInvocation& d = g->m_data; + const GamepadInputChange& c = d.change; + const GamepadSnapshot& snap = d.fullState; + switch (atom) + { + case (int)LuaAtoms::changeKind: + if (c.kind == GamepadInputChangeKind::button) + { + lua_pushstring(L, "button"); + } + else + { + lua_pushstring(L, "axis"); + } + return 1; + case (int)LuaAtoms::changeIndex: + lua_pushinteger(L, + static_cast<lua_Integer>(c.index) + + 1); // 1-based, W3C + return 1; + case (int)LuaAtoms::changeValue: + lua_pushnumber(L, c.value); + return 1; + case (int)LuaAtoms::hasStandardButtonIntent: + lua_pushboolean(L, d.hasStandardButtonIntent ? 1 : 0); + return 1; + case (int)LuaAtoms::hasStandardAxisIntent: + lua_pushboolean(L, d.hasStandardAxisIntent ? 1 : 0); + return 1; + case (int)LuaAtoms::intentButton: + if (d.hasStandardButtonIntent) + { + lua_pushstring(L, standardButtonLabel(d.standardButton)); + } + else + { + lua_pushnil(L); + } + return 1; + case (int)LuaAtoms::intentAxis: + if (d.hasStandardAxisIntent) + { + lua_pushstring(L, standardAxisLabel(d.standardAxis)); + } + else + { + lua_pushnil(L); + } + return 1; + } + return gamepad_snapshot_index(L, atom, snap); +} + +static int gamepad_disconnected_index(lua_State* L) +{ + int atom; + const char* key = lua_tostringatom(L, 2, &atom); + if (!key) + { + luaL_typeerrorL(L, 2, lua_typename(L, LUA_TSTRING)); + return 0; + } + auto* g = lua_torive<ScriptedGamepadDisconnected>(L, 1); switch (atom) { case (int)LuaAtoms::deviceId: lua_pushinteger(L, g->m_deviceId); return 1; - case (int)LuaAtoms::buttonMask: - lua_pushnumber(L, static_cast<double>(g->m_buttonMask)); - return 1; - case (int)LuaAtoms::axis0: - lua_pushnumber(L, g->m_axis0); - return 1; } luaL_error(L, "%s is not a valid field of %s", luaL_checkstring(L, 1), - ScriptedGamepadInvocation::luaName); + ScriptedGamepadDisconnected::luaName); return 0; } @@ -474,28 +846,27 @@ lua_setreadonly(L, -1, true); lua_pop(L, 1); - lua_register_rive<ScriptedGamepadInvocation>(L); + lua_register_rive<ScriptedGamepadConnected>(L); lua_pushcfunction(L, gamepad_invocation_index, nullptr); lua_setfield(L, -2, "__index"); + lua_pushcfunction(L, gamepad_connected_namecall, nullptr); + lua_setfield(L, -2, "__namecall"); lua_setreadonly(L, -1, true); lua_pop(L, 1); - { - uint8_t tag = ScriptedGamepadInvocation::luaTag; - lua_registeruserdatadirectfieldget(L, - tag, - "deviceId", - gamepad_invocation_direct_deviceId); - lua_registeruserdatadirectfieldget( - L, - tag, - "buttonMask", - gamepad_invocation_direct_buttonMask); - lua_registeruserdatadirectfieldget(L, - tag, - "axis0", - gamepad_invocation_direct_axis0); - } + lua_register_rive<ScriptedGamepadEvent>(L); + lua_pushcfunction(L, gamepad_event_index, nullptr); + lua_setfield(L, -2, "__index"); + lua_pushcfunction(L, gamepad_event_namecall, nullptr); + lua_setfield(L, -2, "__namecall"); + lua_setreadonly(L, -1, true); + lua_pop(L, 1); + + lua_register_rive<ScriptedGamepadDisconnected>(L); + lua_pushcfunction(L, gamepad_disconnected_index, nullptr); + lua_setfield(L, -2, "__index"); + lua_setreadonly(L, -1, true); + lua_pop(L, 1); lua_register_rive<ScriptedNoneInvocation>(L); lua_setreadonly(L, -1, true);
diff --git a/src/lua/rive_lua_libs.cpp b/src/lua/rive_lua_libs.cpp index 3469f4b..64aa082 100644 --- a/src/lua/rive_lua_libs.cpp +++ b/src/lua/rive_lua_libs.cpp
@@ -172,14 +172,21 @@ {"isReportedEvent", (int16_t)LuaAtoms::isReportedEvent}, {"isViewModelChange", (int16_t)LuaAtoms::isViewModelChange}, {"isNone", (int16_t)LuaAtoms::isNone}, - {"isGamepad", (int16_t)LuaAtoms::isGamepad}, + {"isGamepadConnected", (int16_t)LuaAtoms::isGamepadConnected}, + {"isGamepadEvent", (int16_t)LuaAtoms::isGamepadEvent}, + {"isGamepadDisconnected", (int16_t)LuaAtoms::isGamepadDisconnected}, {"asPointerEvent", (int16_t)LuaAtoms::asPointerEvent}, {"asKeyboardEvent", (int16_t)LuaAtoms::asKeyboardEvent}, {"asTextInput", (int16_t)LuaAtoms::asTextInput}, {"asFocus", (int16_t)LuaAtoms::asFocus}, {"asReportedEvent", (int16_t)LuaAtoms::asReportedEvent}, {"asViewModelChange", (int16_t)LuaAtoms::asViewModelChange}, - {"asGamepad", (int16_t)LuaAtoms::asGamepad}, + {"asGamepadConnected", (int16_t)LuaAtoms::asGamepadConnected}, + {"asGamepadEvent", (int16_t)LuaAtoms::asGamepadEvent}, + {"asGamepadDisconnected", (int16_t)LuaAtoms::asGamepadDisconnected}, + {"gamepadEvent", (int16_t)LuaAtoms::gamepadEvent}, + {"gamepadConnected", (int16_t)LuaAtoms::gamepadConnected}, + {"gamepadDisconnected", (int16_t)LuaAtoms::gamepadDisconnected}, {"asNone", (int16_t)LuaAtoms::asNone}, {"key", (int16_t)LuaAtoms::key}, {"shift", (int16_t)LuaAtoms::shift}, @@ -191,10 +198,45 @@ {"delaySeconds", (int16_t)LuaAtoms::delaySeconds}, {"deviceId", (int16_t)LuaAtoms::deviceId}, {"buttonMask", (int16_t)LuaAtoms::buttonMask}, - {"axis0", (int16_t)LuaAtoms::axis0}, {"remove", (int16_t)LuaAtoms::remove}, {"removeAt", (int16_t)LuaAtoms::removeAt}, {"removeAllOf", (int16_t)LuaAtoms::removeAllOf}, + {"axes", (int16_t)LuaAtoms::axes}, + {"gamepadMapping", (int16_t)LuaAtoms::gamepadMapping}, + {"mapping", (int16_t)LuaAtoms::mapping}, + {"isStandardMapping", (int16_t)LuaAtoms::isStandardMapping}, + {"buttons", (int16_t)LuaAtoms::buttons}, + {"buttonPressed", (int16_t)LuaAtoms::buttonPressed}, + {"buttonValue", (int16_t)LuaAtoms::buttonValue}, + {"axis", (int16_t)LuaAtoms::axis}, + {"west", (int16_t)LuaAtoms::west}, + {"south", (int16_t)LuaAtoms::south}, + {"north", (int16_t)LuaAtoms::north}, + {"east", (int16_t)LuaAtoms::east}, + {"leftShoulder", (int16_t)LuaAtoms::leftShoulder}, + {"rightShoulder", (int16_t)LuaAtoms::rightShoulder}, + {"back", (int16_t)LuaAtoms::gamepadBack}, + {"forward", (int16_t)LuaAtoms::gamepadForward}, + {"leftStickButton", (int16_t)LuaAtoms::leftStickButton}, + {"rightStickButton", (int16_t)LuaAtoms::rightStickButton}, + {"dpadUp", (int16_t)LuaAtoms::dpadUp}, + {"dpadDown", (int16_t)LuaAtoms::dpadDown}, + {"dpadLeft", (int16_t)LuaAtoms::dpadLeft}, + {"dpadRight", (int16_t)LuaAtoms::dpadRight}, + {"start", (int16_t)LuaAtoms::start}, + {"leftStick", (int16_t)LuaAtoms::leftStick}, + {"rightStick", (int16_t)LuaAtoms::rightStick}, + {"leftTrigger", (int16_t)LuaAtoms::leftTrigger}, + {"rightTrigger", (int16_t)LuaAtoms::rightTrigger}, + {"leftTriggerPressed", (int16_t)LuaAtoms::leftTriggerPressed}, + {"rightTriggerPressed", (int16_t)LuaAtoms::rightTriggerPressed}, + {"changeKind", (int16_t)LuaAtoms::changeKind}, + {"changeIndex", (int16_t)LuaAtoms::changeIndex}, + {"changeValue", (int16_t)LuaAtoms::changeValue}, + {"hasStandardButtonIntent", (int16_t)LuaAtoms::hasStandardButtonIntent}, + {"hasStandardAxisIntent", (int16_t)LuaAtoms::hasStandardAxisIntent}, + {"intentButton", (int16_t)LuaAtoms::intentButton}, + {"intentAxis", (int16_t)LuaAtoms::intentAxis}, {"audio", (int16_t)LuaAtoms::audio}, {"play", (int16_t)LuaAtoms::play}, {"playAtTime", (int16_t)LuaAtoms::playAtTime}, @@ -481,13 +523,50 @@ init(m_state, m_ownedContext.get()); } -ScriptingVM::~ScriptingVM() +ScriptingVM::~ScriptingVM() { closeLuaState(); } + +void ScriptingVM::closeLuaState() { + if (m_state == nullptr) + { + return; + } // Cancel async tasks before closing Lua state to prevent callbacks // from accessing dead state. if (m_ownedContext) m_ownedContext->shutdownAsyncForState(m_state); - lua_close(m_state); + + // Null every registered ScriptedObject's back-pointer before the lua + // teardown cascade. Once m_vm is gone, ScriptedObject::state() returns + // nullptr, so scriptDispose() (called from cascading destruction inside + // lua_close) skips its lua_unref / disposeScriptedContext calls. Those + // calls would otherwise dereference Lua userdatas (ScriptedContext, ref + // tables) that lua_close has already freed in earlier sweep iterations. + for (ScriptedObject* obj : m_scriptedObjects) + { + obj->m_vm = nullptr; + } + m_scriptedObjects.clear(); + + lua_State* state = m_state; + m_state = nullptr; + lua_close(state); +} + +void ScriptingVM::registerScriptedObject(ScriptedObject* obj) +{ + if (obj != nullptr) + { + m_scriptedObjects.insert(obj); + } +} + +void ScriptingVM::unregisterScriptedObject(ScriptedObject* obj) +{ + if (obj != nullptr) + { + m_scriptedObjects.erase(obj); + } } void ScriptingVM::replaceContext(std::unique_ptr<ScriptingContext> newContext)
diff --git a/src/scripted/scripted_drawable.cpp b/src/scripted/scripted_drawable.cpp index 99ce32b..01923a4 100644 --- a/src/scripted/scripted_drawable.cpp +++ b/src/scripted/scripted_drawable.cpp
@@ -1,5 +1,6 @@ #ifdef WITH_RIVE_SCRIPTING #include "rive/lua/rive_lua_libs.hpp" +#include "rive/animation/listener_invocation.hpp" #endif #include "rive/component_dirt.hpp" #include "rive/assets/script_asset.hpp" @@ -74,6 +75,63 @@ return std::vector<HitComponent*>{hitComponent}; } +bool ScriptedDrawable::gamepadDispatch(const ListenerInvocation& inv) +{ + if (m_vm == nullptr || !state()) + { + return false; + } + lua_State* L = state(); + const char* method = nullptr; + switch (inv.kind()) + { + case ListenerInvocationKind::gamepadConnected: + method = "gamepadConnected"; + break; + case ListenerInvocationKind::gamepadEvent: + method = "gamepadEvent"; + break; + case ListenerInvocationKind::gamepadDisconnected: + method = "gamepadDisconnected"; + break; + default: + return false; + } + rive_lua_pushRef(L, m_self); + lua_getfield(L, -1, method); + if (static_cast<lua_Type>(lua_type(L, -1)) != LUA_TFUNCTION) + { + rive_lua_pop(L, 2); + return false; + } + lua_pushvalue(L, -2); + if (const GamepadConnectedInvocation* c = inv.asGamepadConnected()) + { + lua_newrive<ScriptedGamepadConnected>(L, c->snapshot); + } + else if (const GamepadEventInvocation* e = inv.asGamepadEvent()) + { + lua_newrive<ScriptedGamepadEvent>(L, *e); + } + else if (const GamepadDisconnectedInvocation* d = + inv.asGamepadDisconnected()) + { + lua_newrive<ScriptedGamepadDisconnected>(L, d->deviceId); + } + else + { + rive_lua_pop(L, 3); + return false; + } + if (static_cast<lua_Status>(rive_lua_pcall_with_context(L, this, 2, 0)) != + LUA_OK) + { + rive_lua_pop(L, 1); + } + rive_lua_pop(L, 1); + return true; +} + HitResult HitScriptedDrawable::processEvent(Vec2D position, ListenerType hitType, bool canHit, @@ -119,6 +177,19 @@ return hitResult; } +HitResult HitScriptedDrawable::processGamepadInvocation( + const ListenerInvocation&, + ScriptedDrawable*) +{ + // Gamepad dispatch to ScriptedDrawables runs through + // StateMachineInstance::broadcastGamepadToScriptedDrawables's walk over + // m_gamepadScriptedDrawables — that list includes gamepad-only scripts + // (which never enter m_hitComponents because hitComponents() is gated on + // listensToPointerEvents()). Returning none here avoids double-dispatch + // for drawables that handle both pointer and gamepad. + return HitResult::none; +} + bool ScriptedDrawable::keyInput(Key key, KeyModifiers modifiers, bool isPressed, @@ -235,6 +306,14 @@ return HitResult::none; } +HitResult HitScriptedDrawable::processGamepadInvocation( + const ListenerInvocation& invocation, + ScriptedDrawable* alreadyDispatched) +{ + // TODO: implement + return HitResult::none; +} + bool ScriptedDrawable::willDraw() { return Super::willDraw() && draws(); } #endif
diff --git a/src/scripted/scripted_object.cpp b/src/scripted/scripted_object.cpp index 40cf2ad..e2c6362 100644 --- a/src/scripted/scripted_object.cpp +++ b/src/scripted/scripted_object.cpp
@@ -257,6 +257,10 @@ disposeScriptedContext(); // Stack: [self, status] rive_lua_pop(L, 2); + if (m_vm != nullptr) + { + m_vm->unregisterScriptedObject(this); + } m_vm = nullptr; m_self = 0; return false; @@ -266,6 +270,10 @@ lua_unref(L, m_self); disposeScriptedContext(); rive_lua_pop(L, 2); + if (m_vm != nullptr) + { + m_vm->unregisterScriptedObject(this); + } m_vm = nullptr; m_self = 0; return false; @@ -285,11 +293,7 @@ { return false; } -#if defined(WITH_RIVE_TOOLS) - if (m_self != 0 && m_vm.get() == vm) -#else if (m_self != 0 && m_vm == vm) -#endif { rive_lua_pop(L, 1); return true; @@ -305,6 +309,7 @@ disposeTrackedProperties(); disposeScriptedContext(); + m_vm->unregisterScriptedObject(this); } m_userLuaInitDone = false; @@ -358,11 +363,11 @@ return false; } m_self = lua_ref(L, -1); -#ifdef WITH_RIVE_TOOLS - m_vm = ref_rcp(vm); -#else m_vm = vm; -#endif + if (vm != nullptr) + { + vm->registerScriptedObject(this); + } rive_lua_pop(L, 1); return true; } @@ -464,7 +469,11 @@ lua_unref(L, m_self); disposeScriptedContext(); } - m_vm = nullptr; + if (m_vm != nullptr) + { + m_vm->unregisterScriptedObject(this); + m_vm = nullptr; + } m_self = 0; m_userLuaInitDone = false; }
diff --git a/src/text/text_input.cpp b/src/text/text_input.cpp index 4e4132f..97603b7 100644 --- a/src/text/text_input.cpp +++ b/src/text/text_input.cpp
@@ -459,6 +459,11 @@ return true; } +bool TextInput::gamepadDispatch(const ListenerInvocation&, ScriptedDrawable**) +{ + return false; +} + void TextInput::focused() { // TODO: Implement focus visual feedback
diff --git a/tests/unit_tests/assets/gamepad_test.riv b/tests/unit_tests/assets/gamepad_test.riv new file mode 100644 index 0000000..9b7d90b --- /dev/null +++ b/tests/unit_tests/assets/gamepad_test.riv Binary files differ
diff --git a/tests/unit_tests/runtime/focus_test.cpp b/tests/unit_tests/runtime/focus_test.cpp index c68c051..dda82b5 100644 --- a/tests/unit_tests/runtime/focus_test.cpp +++ b/tests/unit_tests/runtime/focus_test.cpp
@@ -11,6 +11,8 @@ #include "rive_file_reader.hpp" #include "rive/viewmodel/viewmodel_instance_boolean.hpp" #include "rive/viewmodel/viewmodel_instance_number.hpp" +#include "rive/animation/listener_invocation.hpp" +#include "rive/input/gamepad_snapshot.hpp" namespace rive { @@ -21,6 +23,7 @@ public: int keyInputCount = 0; int textInputCount = 0; + int gamepadDispatchCount = 0; int focusedCount = 0; int blurredCount = 0; std::string lastText; @@ -44,6 +47,13 @@ return returnValue; } + bool gamepadDispatch(const ListenerInvocation&, + ScriptedDrawable** = nullptr) override + { + gamepadDispatchCount++; + return returnValue; + } + void focused() override { focusedCount++; } void blurred() override { blurredCount++; } @@ -293,6 +303,11 @@ // No focus, input not handled CHECK(manager.keyInput(Key::a, KeyModifiers::none, true, false) == false); CHECK(manager.textInput("hello") == false); + GamepadSnapshot snap{}; + snap.deviceId = 1; + snap.buttonMask = 1; + CHECK(manager.gamepadDispatch(ListenerInvocation::gamepadConnected(snap)) == + false); manager.setFocus(node); @@ -304,6 +319,10 @@ CHECK(manager.textInput("world") == true); CHECK(focusable.textInputCount == 1); CHECK(focusable.lastText == "world"); + + CHECK(manager.gamepadDispatch(ListenerInvocation::gamepadConnected(snap)) == + true); + CHECK(focusable.gamepadDispatchCount == 1); } TEST_CASE("FocusManager traversal basic", "[FocusManager]")
diff --git a/tests/unit_tests/runtime/gamepad_test.cpp b/tests/unit_tests/runtime/gamepad_test.cpp new file mode 100644 index 0000000..5dd9ae2 --- /dev/null +++ b/tests/unit_tests/runtime/gamepad_test.cpp
@@ -0,0 +1,425 @@ +#include "rive/animation/state_machine_instance.hpp" +#include "rive/artboard.hpp" +#include "rive/file.hpp" +#include "rive/input/gamepad_batch.hpp" +#include "rive/input/gamepad_snapshot.hpp" +#include "rive_file_reader.hpp" +#include "rive_testing.hpp" +#include "utils/serializing_factory.hpp" +#include "rive/viewmodel/viewmodel_instance_string.hpp" +#include <cstdint> +#include <cstring> +#include <vector> + +using namespace rive; + +namespace +{ +// Builds a little-endian gamepad batch matching the wire format documented in +// `gamepad_batch.cpp`. Multi-byte fields are fixed-width LE; counts must stay +// within `kGamepadBatchMax{Buttons,Axes}`. +struct WireBuilder +{ + std::vector<uint8_t> buf; + + void u8(uint8_t v) { buf.push_back(v); } + void u32(uint32_t v) + { + buf.push_back(static_cast<uint8_t>(v)); + buf.push_back(static_cast<uint8_t>(v >> 8)); + buf.push_back(static_cast<uint8_t>(v >> 16)); + buf.push_back(static_cast<uint8_t>(v >> 24)); + } + void i32(int32_t v) { u32(static_cast<uint32_t>(v)); } + void f32(float v) + { + uint32_t bits; + std::memcpy(&bits, &v, sizeof(bits)); + u32(bits); + } + + void header() { u32(kGamepadBatchWireVersion); } + + void connected(int32_t deviceId, + uint8_t nButtons = 17, + uint8_t nAxes = 4, + uint8_t mapping = 0) + { + u8(static_cast<uint8_t>(GamepadRecordType::connected)); + i32(deviceId); + u8(mapping); + u8(nButtons); + u8(nAxes); + u8(0); // padding to align the float arrays + for (uint8_t b = 0; b < nButtons; b++) + { + f32(0.f); + } + for (uint8_t a = 0; a < nAxes; a++) + { + f32(0.f); + } + } + + void updateOne(int32_t deviceId, + GamepadInputChangeKind kind, + uint8_t index, + float value) + { + u8(static_cast<uint8_t>(GamepadRecordType::update)); + i32(deviceId); + u8(1); // nChanges + u8(static_cast<uint8_t>(kind)); + u8(index); + f32(value); + } + + void disconnected(int32_t deviceId) + { + u8(static_cast<uint8_t>(GamepadRecordType::disconnected)); + i32(deviceId); + } +}; + +// Open the shared gamepad fixture and advance once so the focus manager and +// scripted drawable list are initialized before any events are dispatched. +std::unique_ptr<StateMachineInstance> openReadyStateMachine( + rcp<File>& fileOut, + std::unique_ptr<ArtboardInstance>& artboardOut, + SerializingFactory& silver) +{ + fileOut = ReadRiveFile("assets/gamepad_test.riv", &silver); + artboardOut = fileOut->artboardDefault(); + REQUIRE(artboardOut != nullptr); + + auto sm = artboardOut->stateMachineAt(0); + REQUIRE(sm != nullptr); + + auto vmi = fileOut->createDefaultViewModelInstance(artboardOut.get()); + sm->bindViewModelInstance(vmi); + sm->advanceAndApply(0); + return sm; +} +} // namespace + +TEST_CASE("gamepad batch accepts a single connected record", "[gamepad]") +{ + SerializingFactory silver; + rcp<File> file; + std::unique_ptr<ArtboardInstance> artboard; + auto stateMachine = openReadyStateMachine(file, artboard, silver); + + constexpr int32_t kDeviceId = 0; + constexpr uint8_t kNButtons = 17; + constexpr uint8_t kNAxes = 4; + static_assert(kNButtons <= kGamepadBatchMaxButtons, "button cap"); + static_assert(kNAxes <= kGamepadBatchMaxAxes, "axis cap"); + + WireBuilder wb; + wb.header(); + wb.connected(kDeviceId, kNButtons, kNAxes); + + // Version (4) + record type (1) + deviceId (4) + 4 header bytes + // + 17 button floats + 4 axis floats. + REQUIRE(wb.buf.size() == + 4u + 1u + 4u + 4u + size_t(kNButtons) * 4u + size_t(kNAxes) * 4u); + + CHECK(stateMachine->submitGamepadsFromBuffer(wb.buf.data(), wb.buf.size())); +} + +TEST_CASE("gamepad batch tracks multiple device ids independently", "[gamepad]") +{ + SerializingFactory silver; + rcp<File> file; + std::unique_ptr<ArtboardInstance> artboard; + auto stateMachine = openReadyStateMachine(file, artboard, silver); + + // Connect three devices with distinct ids (including a high id to make + // sure the int32 path round-trips). + WireBuilder connect; + connect.header(); + connect.connected(/*deviceId*/ 1); + connect.connected(/*deviceId*/ 7); + connect.connected(/*deviceId*/ 42); + CHECK(stateMachine->submitGamepadsFromBuffer(connect.buf.data(), + connect.buf.size())); + + // Send a separate batch per device, mixing button + axis updates. + WireBuilder updates; + updates.header(); + updates.updateOne(1, GamepadInputChangeKind::button, /*index*/ 0, 1.f); + updates.updateOne(7, GamepadInputChangeKind::axis, /*index*/ 2, -0.5f); + updates.updateOne(42, GamepadInputChangeKind::button, /*index*/ 4, 1.f); + updates.updateOne(42, GamepadInputChangeKind::axis, /*index*/ 0, 0.75f); + CHECK(stateMachine->submitGamepadsFromBuffer(updates.buf.data(), + updates.buf.size())); +} + +TEST_CASE("gamepad batch rejects an update for an unknown device id", + "[gamepad]") +{ + SerializingFactory silver; + rcp<File> file; + std::unique_ptr<ArtboardInstance> artboard; + auto stateMachine = openReadyStateMachine(file, artboard, silver); + + WireBuilder wb; + wb.header(); + wb.connected(/*deviceId*/ 3); + // Update targets a deviceId we never connected — must bail out. + wb.updateOne(/*deviceId*/ 99, + GamepadInputChangeKind::button, + /*index*/ 0, + 1.f); + + CHECK_FALSE( + stateMachine->submitGamepadsFromBuffer(wb.buf.data(), wb.buf.size())); +} + +TEST_CASE("gamepad batch handles disconnect of one of several devices", + "[gamepad]") +{ + SerializingFactory silver; + rcp<File> file; + std::unique_ptr<ArtboardInstance> artboard; + auto stateMachine = openReadyStateMachine(file, artboard, silver); + + WireBuilder wb; + wb.header(); + wb.connected(/*deviceId*/ 10); + wb.connected(/*deviceId*/ 20); + wb.connected(/*deviceId*/ 30); + // Drive an update on each, disconnect the middle one, then drive the + // surviving devices again to confirm they are still tracked. + wb.updateOne(10, GamepadInputChangeKind::button, 0, 1.f); + wb.updateOne(20, GamepadInputChangeKind::axis, 1, 0.25f); + wb.updateOne(30, GamepadInputChangeKind::button, 2, 1.f); + wb.disconnected(/*deviceId*/ 20); + wb.updateOne(10, GamepadInputChangeKind::axis, 0, -1.f); + wb.updateOne(30, GamepadInputChangeKind::button, 3, 0.f); + + CHECK(stateMachine->submitGamepadsFromBuffer(wb.buf.data(), wb.buf.size())); + + // Anything addressed to the now-disconnected device must be rejected. + WireBuilder afterDisconnect; + afterDisconnect.header(); + afterDisconnect.updateOne(/*deviceId*/ 20, + GamepadInputChangeKind::button, + 0, + 1.f); + CHECK_FALSE( + stateMachine->submitGamepadsFromBuffer(afterDisconnect.buf.data(), + afterDisconnect.buf.size())); +} + +TEST_CASE("gamepad batch allows reconnecting the same device id", "[gamepad]") +{ + SerializingFactory silver; + rcp<File> file; + std::unique_ptr<ArtboardInstance> artboard; + auto stateMachine = openReadyStateMachine(file, artboard, silver); + + constexpr int32_t kDeviceId = 5; + + WireBuilder first; + first.header(); + first.connected(kDeviceId); + first.updateOne(kDeviceId, GamepadInputChangeKind::button, 0, 1.f); + first.disconnected(kDeviceId); + CHECK(stateMachine->submitGamepadsFromBuffer(first.buf.data(), + first.buf.size())); + + // After disconnect the device must be unknown again — any update before a + // fresh connect is rejected. + WireBuilder strayUpdate; + strayUpdate.header(); + strayUpdate.updateOne(kDeviceId, GamepadInputChangeKind::button, 0, 1.f); + CHECK_FALSE(stateMachine->submitGamepadsFromBuffer(strayUpdate.buf.data(), + strayUpdate.buf.size())); + + // Reconnect with the same id and confirm updates flow again. + WireBuilder reconnect; + reconnect.header(); + reconnect.connected(kDeviceId); + reconnect.updateOne(kDeviceId, GamepadInputChangeKind::axis, 0, 0.5f); + CHECK(stateMachine->submitGamepadsFromBuffer(reconnect.buf.data(), + reconnect.buf.size())); +} + +TEST_CASE("gamepad batch tolerates disconnect of an unknown device id", + "[gamepad]") +{ + SerializingFactory silver; + rcp<File> file; + std::unique_ptr<ArtboardInstance> artboard; + auto stateMachine = openReadyStateMachine(file, artboard, silver); + + // Disconnect for a device we never connected is a no-op `erase` per the + // wire-format contract — the batch must still parse successfully. + WireBuilder wb; + wb.header(); + wb.disconnected(/*deviceId*/ 1234); + + CHECK(stateMachine->submitGamepadsFromBuffer(wb.buf.data(), wb.buf.size())); +} + +TEST_CASE("File loads and processes multiple types of gamepad inputs", + "[gamepad]") +{ + SerializingFactory silver; + rcp<File> file; + std::unique_ptr<ArtboardInstance> artboard; + auto stateMachine = openReadyStateMachine(file, artboard, silver); + + REQUIRE(artboard != nullptr); + + silver.frameSize(artboard->width(), artboard->height()); + + stateMachine->advanceAndApply(0.1f); + auto renderer = silver.makeRenderer(); + artboard->draw(renderer.get()); + silver.addFrame(); + + constexpr int32_t kDeviceId1 = 3; + constexpr int32_t kDeviceId2 = 5; + constexpr int32_t kDeviceId3 = 1; + + // connect device 1 + { + WireBuilder wb; + wb.header(); + wb.connected(kDeviceId1); + CHECK(stateMachine->submitGamepadsFromBuffer(wb.buf.data(), + wb.buf.size())); + stateMachine->advanceAndApply(0.016f); + artboard->draw(renderer.get()); + } + + // press button at index 0 on device 1 + { + + silver.addFrame(); + WireBuilder wb; + wb.header(); + wb.updateOne(kDeviceId1, GamepadInputChangeKind::button, 0, 1.f); + CHECK(stateMachine->submitGamepadsFromBuffer(wb.buf.data(), + wb.buf.size())); + stateMachine->advanceAndApply(0.016f); + artboard->draw(renderer.get()); + } + // connect device 2 and 3 + { + silver.addFrame(); + WireBuilder wb; + wb.header(); + wb.connected(kDeviceId2); + wb.connected(kDeviceId3, + 17, + 4, + 1); // Device 3 is not a standard mapping + CHECK(stateMachine->submitGamepadsFromBuffer(wb.buf.data(), + wb.buf.size())); + stateMachine->advanceAndApply(0.016f); + artboard->draw(renderer.get()); + } + // submit button press on device 2 and 3 + { + silver.addFrame(); + WireBuilder wb; + wb.header(); + wb.updateOne(kDeviceId2, GamepadInputChangeKind::button, 2, 1.f); + wb.updateOne(kDeviceId3, GamepadInputChangeKind::button, 2, 1.f); + CHECK(stateMachine->submitGamepadsFromBuffer(wb.buf.data(), + wb.buf.size())); + stateMachine->advanceAndApply(0.016f); + artboard->draw(renderer.get()); + } + // submit axis change on device 1 and 2 + { + + for (auto i = 1; i < 10; i++) + { + silver.addFrame(); + WireBuilder wb; + wb.header(); + wb.updateOne(kDeviceId1, GamepadInputChangeKind::axis, 0, i * 0.1f); + wb.updateOne(kDeviceId2, + GamepadInputChangeKind::axis, + 1, + i * -0.1f); + CHECK(stateMachine->submitGamepadsFromBuffer(wb.buf.data(), + wb.buf.size())); + stateMachine->advanceAndApply(0.016f); + artboard->draw(renderer.get()); + } + } + // disconnect device 3 + { + silver.addFrame(); + WireBuilder wb; + wb.header(); + wb.disconnected(kDeviceId3); + CHECK(stateMachine->submitGamepadsFromBuffer(wb.buf.data(), + wb.buf.size())); + stateMachine->advanceAndApply(0.016f); + artboard->draw(renderer.get()); + } + // release button 0 of device 1 + { + stateMachine->focusManager()->focusNext(); + silver.addFrame(); + WireBuilder wb; + wb.header(); + wb.updateOne(kDeviceId1, GamepadInputChangeKind::button, 0, 0.f); + CHECK(stateMachine->submitGamepadsFromBuffer(wb.buf.data(), + wb.buf.size())); + stateMachine->advanceAndApply(0.016f); + artboard->draw(renderer.get()); + } + // press button 0 of device 1 + { + silver.addFrame(); + WireBuilder wb; + wb.header(); + wb.updateOne(kDeviceId1, GamepadInputChangeKind::button, 0, 1.f); + CHECK(stateMachine->submitGamepadsFromBuffer(wb.buf.data(), + wb.buf.size())); + stateMachine->advanceAndApply(0.016f); + artboard->draw(renderer.get()); + } + // Release button 0 + { + silver.addFrame(); + WireBuilder wb; + wb.header(); + wb.updateOne(kDeviceId1, GamepadInputChangeKind::button, 0, 0.f); + CHECK(stateMachine->submitGamepadsFromBuffer(wb.buf.data(), + wb.buf.size())); + stateMachine->advanceAndApply(0.016f); + artboard->draw(renderer.get()); + } + { + silver.addFrame(); + WireBuilder wb; + wb.header(); + wb.updateOne(kDeviceId1, GamepadInputChangeKind::button, 1, 1.f); + CHECK(stateMachine->submitGamepadsFromBuffer(wb.buf.data(), + wb.buf.size())); + stateMachine->advanceAndApply(0.016f); + artboard->draw(renderer.get()); + } + // Move left joystick x and y axis + { + silver.addFrame(); + WireBuilder wb; + wb.header(); + wb.updateOne(kDeviceId1, GamepadInputChangeKind::axis, 0, 0.5f); + wb.updateOne(kDeviceId1, GamepadInputChangeKind::axis, 1, 0.5f); + CHECK(stateMachine->submitGamepadsFromBuffer(wb.buf.data(), + wb.buf.size())); + stateMachine->advanceAndApply(0.016f); + artboard->draw(renderer.get()); + } + + CHECK(silver.matches("gamepad_test")); +} \ No newline at end of file
diff --git a/tests/unit_tests/runtime/scripting/scripting_gamepad_event_test.cpp b/tests/unit_tests/runtime/scripting/scripting_gamepad_event_test.cpp new file mode 100644 index 0000000..17ed768 --- /dev/null +++ b/tests/unit_tests/runtime/scripting/scripting_gamepad_event_test.cpp
@@ -0,0 +1,93 @@ +#include "catch.hpp" +#include "scripting_test_utilities.hpp" +#include "rive/input/gamepad_snapshot.hpp" +#include "rive/input/standard_gamepad.hpp" +#include "rive/lua/rive_lua_libs.hpp" + +using namespace rive; + +TEST_CASE("GamepadEvent reads snapshot fields and standard names", + "[scripting]") +{ + ScriptingTest vm("function deviceIdOf(g)\n" + " return g.deviceId\n" + "end\n" + "function mappingOf(g)\n" + " return g.mapping\n" + "end\n" + "function southPressed(g)\n" + " return g.south\n" + "end\n" + "function btnPressed(g, i)\n" + " return g:buttonPressed(i)\n" + "end\n" + "function axisValue(g, i)\n" + " return g:axis(i)\n" + "end\n"); + + lua_State* L = vm.state(); + + GamepadSnapshot snap{}; + snap.deviceId = 42; + snap.mapping = GamepadMappingKind::standard; + snap.buttonMask = uint64_t(1) + << static_cast<unsigned>(StandardGamepadButton::south); + snap.buttonValues = {0.5f, 1.f}; + snap.axes = {0.25f, -0.5f, 0.f, 0.f, 0.75f, 0.25f}; + + lua_newrive<ScriptedGamepadConnected>(L, snap); + + lua_getglobal(L, "deviceIdOf"); + lua_pushvalue(L, -2); + CHECK(lua_pcall(L, 1, 1, 0) == LUA_OK); + CHECK(lua_tointeger(L, -1) == 42); + lua_pop(L, 1); + + lua_getglobal(L, "mappingOf"); + lua_pushvalue(L, -2); + CHECK(lua_pcall(L, 1, 1, 0) == LUA_OK); + CHECK(std::string(lua_tostring(L, -1)) == "standard"); + lua_pop(L, 1); + + lua_getglobal(L, "southPressed"); + lua_pushvalue(L, -2); + CHECK(lua_pcall(L, 1, 1, 0) == LUA_OK); + CHECK(lua_toboolean(L, -1)); + lua_pop(L, 1); + + lua_getglobal(L, "btnPressed"); + lua_pushvalue(L, -2); + lua_pushinteger(L, 1); + CHECK(lua_pcall(L, 2, 1, 0) == LUA_OK); + CHECK(lua_toboolean(L, -1)); + lua_pop(L, 1); + + lua_getglobal(L, "axisValue"); + lua_pushvalue(L, -2); + lua_pushinteger(L, 1); + CHECK(lua_pcall(L, 2, 1, 0) == LUA_OK); + CHECK(lua_tonumber(L, -1) == Approx(0.25f)); + lua_pop(L, 2); +} + +TEST_CASE("GamepadEvent unknown mapping clears semantic buttons", "[scripting]") +{ + ScriptingTest vm("function southPressed(g)\n" + " return g.south\n" + "end\n"); + + lua_State* L = vm.state(); + + GamepadSnapshot snap{}; + snap.mapping = GamepadMappingKind::unknown; + snap.buttonMask = uint64_t(1) + << static_cast<unsigned>(StandardGamepadButton::south); + + lua_newrive<ScriptedGamepadConnected>(L, snap); + + lua_getglobal(L, "southPressed"); + lua_pushvalue(L, -2); + CHECK(lua_pcall(L, 1, 1, 0) == LUA_OK); + CHECK(!lua_toboolean(L, -1)); + lua_pop(L, 2); +}
diff --git a/tests/unit_tests/silvers/gamepad_test.sriv b/tests/unit_tests/silvers/gamepad_test.sriv new file mode 100644 index 0000000..5505d9c --- /dev/null +++ b/tests/unit_tests/silvers/gamepad_test.sriv Binary files differ