input

Backend-neutral devices, remappable actions and the ECS input plugin

Garnet Input

require "garnet-input" provides backend-neutral devices, remappable actions and an ECS plugin that makes input an engine service. Host adapters (garnet-engine/desktop, the iOS app plugin, or your own) feed raw input; games read actions.

Input plugin

world = Garnet::World.new
world.add_plugin(Garnet::Input::Plugin.new) # App plugins add it for you

world.schedule.add(:fixed_update, name: "player.move") do |w, seconds|
  velocity = w.resource(Garnet::Input::Actions).vec2(:move) * 120 # Garnet::Math::Vec2
  # ...
end

Input::Plugin installs three resources:

  • Input::Devices: raw keyboard, mouse (logical coordinates), touches, text, focus, motion and gamepads, with held?, pressed? and released? for the current frame.
  • Input::Actions: the global action map, fed from the keyboard and every connected pad (see global_devices below).
  • Input::ActionMap: its bindings. Mutate it (or call plugin.capture_binding(:confirm)) to rebind; the plugin reapplies it.

It emits KeyEvent, MouseButtonEvent, MouseMoveEvent, ScrollEvent, TextEvent, TouchEvent, FocusEvent, GamepadEvent, GamepadButtonEvent and BindingCaptured into the world. Its systems are input.devices and input.players (start of Input) and input.actions, which ticks every action map at the start of each FixedUpdate tick. Read actions from fixed systems; a press that arrives in a frame without a fixed tick waits for the next one. Pass tick_mode: :frame to tick once per frame for games that read actions in Update.

Default actions

ActionMap.default binds keyboard and any standard gamepad:

Action Keyboard Gamepad
:move vector (:move_x, :move_y) WASD, arrows left stick
:look vector (:look_x, :look_y) none right stick
:confirm Enter, Space A
:cancel Escape, Backspace B
:pause Escape, P Start
:menu_up, :menu_down, :menu_left, :menu_right arrows, WASD D-pad

Vectors use screen orientation: positive Y points down. :look has no keys: every letter cluster (IJKL, QE) collides with keys games bind to actions, and keyboard players look with the mouse, whose delta is unbounded and depends on cursor capture and sensitivity, so read Devices#mouse.delta for mouse look and add look keys to your own map if you want them. Controls with device Input::ANY_DEVICE (the default for Key#control and Input.button) match any device routed to the action map; the global map also receives keys on KEYBOARD_DEVICE and pad controls on their native ids, so bindings written for ActionGamepad keep working.

Rebinding and persistence

map = world.resource(Garnet::Input::ActionMap)
map.load(settings_path)                       # overlays saved controls
map.rebind(:confirm, 0, Garnet::Input::Key::F.control)
world.plugin(Garnet::Input::Plugin).capture_binding(:pause) # next press
map.save(settings_path)
map.reset                                     # back to defaults

Saved JSON is versioned and keyed by action name. Loading ignores actions the map doesn't declare, so settings survive game updates.

Shared keys, consuming and on-screen buttons

consume?(:cancel) takes a press once. It also takes that physical press from every other action bound to the same key or button, in the global map and in every player's ActionState (they share Plugin#ledger): when Escape is both :cancel and :pause, a menu that closes on consume?(:cancel) does not reopen on pressed?(:pause) in the same tick. The next press of the key is unaffected.

Consume a press once it has been handled. A Start press that resumes play from a pause menu is still pressed? for the gameplay systems that run later in the same tick, so a game that only reads pressed?(:pause) there pauses again at once; consume?(:pause) in the menu prevents it.

actions.press(:pulse) (or plugin.press) presses an action for the next tick from code, as if a bound key were tapped: pressed?, consume? and held? see it. On-screen buttons use it to drive gameplay actions:

button[UI::Interactive].state.on_click_press(:pulse) # garnet-ui/plugin

Local multiplayer

Spawn one entity per seat:

world.spawn(Garnet::Input::Player.new(0))                # keyboard + first pad
world.spawn(Garnet::Input::Player.new(1), Garnet::Input::Controls.new(map))

world.query(Garnet::Input::ActionState) do |_, state|
  move = state.vector(:move)
end

The plugin adds an ActionState to every Player and feeds it from that seat's gamepad and, for keyboard seats (seat 0 by default), the keyboard. Newly connected pads go to the lowest seat without one unless auto_assign_gamepads is false; manage seats yourself with devices.gamepads.assign.

The global Actions hears every connected pad by default, so any controller can drive menus. In a game where players join by pressing a button, pass Plugin.new(global_devices: :keyboard_and_seated) so a pad that has not joined (has no seat) cannot confirm or pause; it still reports GamepadButtonEvents for a join screen. :seated also drops the keyboard unless some Player reads it.

UI first claim

Devices#intercept { |event| claimed } sees raw events before gameplay, and Devices#intercept_gamepads { |id, pad| pad.claim(...) } routes pads. The UI plugin registers both. A claimed press never reaches gameplay; a release always follows a press that did, so keys never stick.

Scripted input and replays

tape = Garnet::Input::Tape.build do |script|
  script.press(:right).wait(30).release(:right)
  script.button(:a, true, device: 0).wait.button(:a, false, device: 0)
  script.stick(0, move_x: 1).wait(10)      # raw stick, before the dead zone
  script.analog(0, move_x: 0.5).wait(10)   # what gameplay reads: 0.5
  script.click(120, 48)                    # left press here, release next frame
  script.pointer(200, 90).scroll(0, -1).wait
  script.text("4815").tap(:enter)          # typed text, then a key
  script.touch(1, :begin, 40, 300).wait.touch(1, :end, 90, 300).wait
end
plugin.replay(tape)  # drives Devices, UI claims and actions like live play
plugin.record        # later: plugin.recording.to_json

A recording captures keys with modifiers, pointer moves, mouse buttons and scrolling at their positions, typed text, touches, focus changes and pads. Tapes are saved as version 2 JSON, which stores only frames with input and, for pads, only the axes that changed; version 1 tapes still load. GamepadSample.reading(move_x, move_y) builds the raw sample whose sticks read those values after the 0.2 radial dead zone, for tools that pilot a game through Devices#gamepad.

A replay supplies one tick per frame through the same path as live input and ignores the host until it ends. Advance exactly one fixed step per frame (the capture harness and HeadlessDriver do) for deterministic results.

Replayed input goes through the same intercept claims as live input, in a window or headless. Claims depend on the UI's current state, so record and replay with the same UI plugins at the same Scene::Screen size: a headless world without a Scene::Screen resource never lays the UI out, so it claims nothing and a tape recorded there can diverge in a window.

Actions without the plugin

require "garnet-input" provides remappable digital actions and analog axes independent of the window, UI, and physics. Host adapters feed Actions#button and #analog using their normalized device and control IDs. Call #tick once per fixed simulation step. A complete tap between ticks can still set pressed?, while held? follows the state of all bindings. consume? takes a newly pressed or buffered action once. The buffer duration counts fixed ticks.

bind_axis combines digital and analog bindings with a per-axis dead zone. axes caps a vector's length for diagonal movement; vec2(x_axis, y_axis) and vec2(:move) return the same values as a Garnet::Math::Vec2 (Plugin#vec2 too), so velocity = input.vec2(:move) * speed needs no tuple unpacking. Mouse#position, #delta, #wheel and Touch#position, #start are Vec2 views of the existing fields. Call release_device(id) after disconnect and reset on host focus loss. The existing World schedule can call tick before other fixed systems.

Call record_tick in place of tick when capturing a replay. Store the resulting snapshots in an Input::Tape, which supports versioned JSON. Replay them with Actions#replay on an instance with the same bindings and initial state. The existing fixed-step world schedule remains the simulation clock.

DigitalRoute(T) gives UI first claim on a digital press and sends its release to gameplay if gameplay received the press. Call cancel on focus loss to recover keys that need synthesized releases. The GLFW UI adapter uses this route for its gameplay key callback.

For mapped controllers, use Gamepads(Gamepad).new and poll the host once per frame. Gamepads#assign(device_id, seat) binds a connected device to a single local player. Read move, look, pressed?(GamepadButton::A), and right_trigger? from its Gamepad. Use drain_connections to consume connect and disconnect events. A disconnected device releases its seat and can be reassigned by the game.

For a custom host or tests, feed GamepadSample snapshots into Gamepads#poll or Gamepad#sample directly. Pass the host's focus state so button presses and held triggers cannot leak across focus changes. Use ReleaseGate for the same release-before-rearm behavior on mouse or key actions.

To feed a fixed-tick action map, construct one ActionGamepad per device and poll the registry at host sample cadence. For example, with a UI router:

pads = Garnet::Input::Gamepads(Garnet::Input::ActionGamepad).new do
  Garnet::Input::ActionGamepad.new(actions) do |device, pad|
    router.route_gamepad(pad) if device == menu_device
  end
end
host.poll_gamepads(pads)

Omit the route block for gameplay alone. Bind button controls by GamepadButton#value and host device ID. Axis IDs 0–3 are move X/Y and look X/Y after radial dead-zone processing, with up positive. Axes 4–5 are left and right trigger levels from zero to one. Each trigger rearms once it returns within five percent of rest after attach or focus loss. A UI route can use pad.claim(button) { handled } before gameplay receives transitions. Call pads.blur when focus is lost, including while polling is paused. The application selects the menu device, seat assignments, and bindings.

Callback hosts can update a single device via pads.sample(id, sample) or pads.disconnect(id). Event-driven hosts pass the presses they saw to Devices#poll_gamepads(samples, generations, presses) as {device, button} in event order: that frame's GamepadButtonEvents follow it, and a tap released before the snapshot still reads as a one-frame press (garnet-platform-glfw/sdl_gamepads does this for SDL3). The iOS adapter in garnet-engine/ios_gamepads accepts the five native controller callback arguments after the registry. It maps the ten reported buttons and left stick. Other axes stay neutral.

Touch gestures and tilt

TouchGestures turns raw touches into taps and a horizontal swipe-and-hold. Feed every touch with touch(id, TouchPhase, x, y, seconds) and call sample(seconds) once per frame. A touch that travels threshold horizontally (and more horizontally than vertically) becomes the swipe; swipe is then its signed depth, horizontal travel over length, clamped to -1..1, until the finger lifts or the touch is cancelled. swiping?, swipe_began? and swipe_ended? follow the hold. A quick flick that starts and ends between frames is still reported for at least one sample and min_hold seconds. Short touches that stay within tap_slop appear in taps. Route touches your own widgets claim (buttons, sliders) elsewhere and call cancel on focus loss.

gestures = Garnet::Input::TouchGestures.new(threshold: 16_f32, length: 120_f32, device: 7)
actions.bind_axis(:swing, analog: [Garnet::Input::Analog.new(gestures.swipe_axis)])
actions.bind(:select, [gestures.tap_control])
# host touch callback: gestures.touch(id, phase, x, y, now)
gestures.sample(now)
gestures.feed(actions) # swipe_axis, swipe_left / swipe_right held, tap_control pressed per tap
actions.tick

Tilt converts device gravity (device coordinates, as CoreMotion reports it) into a steering-wheel axis for a handheld screen: rolling the device clockwise in its screen plane steers right. Pass the interface ScreenOrientation so landscape left and right agree. calibrate stores the current roll as centre; value returns the roll from centre over range radians with a rescaled deadzone, clamped to -1..1 and unsmoothed, fading to 0 as the screen lies flat. feed(actions, control, ...) writes it to an analog control. The iOS host supplies gravity through Garnet::IOS.motion.

Repository

input

Owner
Statistic
  • 0
  • 0
  • 0
  • 4
  • 2
  • 1 day ago
  • November 30, 2026
License

MIT License

Links
Synced at

Wed, 02 Dec 2026 02:08:54 GMT

Languages