input

package
v0.0.0-...-94fff03 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 5, 2026 License: MIT Imports: 16 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package input turns keyboard, mouse, gamepad and touch input into named actions. Game code reads actions ("jump", "move"), never keys; which control drives an action is data.

The pieces:

  • Actions: the action table, declared in Go (Button, Axis, Vec2).
  • Bindings: a bindings file (BindingsFile, JSON) compiled against the actions: mapping contexts with bindings, composites, modifiers, processors, interactions and touch regions. ParseBindings reports every problem at once with GOD-style paths.
  • Router: polls a Source once per tick and evaluates every Player: its devices, its stack of active mappings, its Profile overrides. The result is one State per player.
  • Profile: per-player settings and rebinding overrides, saved as JSON.

The package imports only the standard library, so it runs headless: tests and replays drive it with ManualSource and ReplaySource. input/ebiteninput reads Ebiten; input/inputsys connects the Router to an ecs World and loads bindings files through the asset system. The guide is doc/guide/engine/input.md.

Index

Constants

View Source
const (
	MaxRawButtons = 64
	MaxRawAxes    = 8
)

Limits of the raw gamepad fallback (padraw:).

View Source
const (
	// MaxPads is the number of gamepads a Frame carries.
	MaxPads = 8
	// MaxTouches is the number of simultaneous touches a Frame carries.
	MaxTouches = 10
)

Frame size limits.

View Source
const KeyCount = int(numKeys) - 1

KeyCount is the number of keys; valid keys are 1..KeyCount.

View Source
const MaxPlayers = 8

MaxPlayers is the largest number of player slots a Router has.

View Source
const TouchAny = 0xFFFF

TouchAny is the Code of touch:any, which is down while any touch is.

Variables

View Source
var (
	KeyEscapeControl = Control{Type: CtrlKey, Code: uint16(KeyEscape)}
	PadStartControl  = Control{Type: CtrlPadButton, Code: uint16(PadStart)}
)

Common controls, for Listen cancel lists and tests.

Functions

func BindingsSchema

func BindingsSchema() []byte

BindingsSchema returns schema/bindings.schema.json: the JSON shape of a bindings file in the GOD TypeSchema dialect. Tools such as `wpix schema` convert it for editors. The slice is a copy.

Types

type Action

type Action uint16

Action identifies one declared action. IDs are dense and start at 1; the zero Action means "none" and reads as zero everywhere.

type ActionOption

type ActionOption func(*actionInfo)

ActionOption changes how an action is declared.

func AllowMods

func AllowMods() ActionOption

AllowMods lets rebinding capture modifier+key combinations (Ctrl+S) for the action. Without it a captured key is bound without modifiers.

func Delta

func Delta() ActionOption

Delta marks a Vec2 action whose value is a per-tick delta (mouse look, touch drag). Its length may exceed 1, and the profile's sensitivity setting scales it.

type Actions

type Actions struct {
	// contains filtered or unexported fields
}

Actions is the game's action table. Declare every action at startup (package-level vars are the usual place), then Actions.Freeze it before building a Router or parsing bindings. The zero value is ready to use.

Declaring panics with "input: " for an empty or duplicate name and after Freeze. Actions is not safe for concurrent declaration; once frozen it is read-only and safe to share (asset workers read it while decoding).

func (*Actions) AllowsMods

func (a *Actions) AllowsMods(id Action) bool

AllowsMods reports whether the action was declared with AllowMods.

func (*Actions) Axis

func (a *Actions) Axis(name, doc string, opts ...ActionOption) Action

Axis declares an Axis action.

func (*Actions) Button

func (a *Actions) Button(name, doc string, opts ...ActionOption) Action

Button declares a Button action and returns its ID. doc is shown in rebinding menus and generated docs.

func (*Actions) Doc

func (a *Actions) Doc(id Action) string

Doc returns the action's doc string.

func (*Actions) Freeze

func (a *Actions) Freeze()

Freeze ends declaration. It is idempotent.

func (*Actions) Frozen

func (a *Actions) Frozen() bool

Frozen reports whether Freeze was called.

func (*Actions) IsDelta

func (a *Actions) IsDelta(id Action) bool

IsDelta reports whether the action was declared with Delta.

func (*Actions) Kind

func (a *Actions) Kind(id Action) Kind

Kind returns the action's kind.

func (*Actions) Len

func (a *Actions) Len() int

Len returns the number of declared actions. Valid IDs are 1..Len.

func (*Actions) Lookup

func (a *Actions) Lookup(name string) (Action, bool)

Lookup returns the action declared under name.

func (*Actions) Name

func (a *Actions) Name(id Action) string

Name returns the action's name. Panics with "input: unknown action" for an ID that was not declared.

func (*Actions) Vec2

func (a *Actions) Vec2(name, doc string, opts ...ActionOption) Action

Vec2 declares a Vec2 action.

type AssignPolicy

type AssignPolicy uint8

AssignPolicy decides which player a device drives.

const (
	// AssignSingle gives every device to player 0. Single-player games.
	AssignSingle AssignPolicy = iota
	// AssignJoin leaves devices unassigned until they press the join
	// action, which claims the lowest free player slot. Unassigned devices
	// drive the lobby player ([Router.Lobby]), so menus work before anyone
	// joined.
	AssignJoin
)

Assign policies.

type BindingSpec

type BindingSpec struct {
	// Control is a single control ("key:Space", "pad:leftstick").
	Control string `json:"control,omitempty"`
	// Composite builds the value from several controls: "axis" (Neg, Pos),
	// "dpad" (Up, Down, Left, Right) or "chord" (Controls).
	Composite string `json:"composite,omitempty"`
	Neg       string `json:"neg,omitempty"`
	Pos       string `json:"pos,omitempty"`
	Up        string `json:"up,omitempty"`
	Down      string `json:"down,omitempty"`
	Left      string `json:"left,omitempty"`
	Right     string `json:"right,omitempty"`
	// Controls are the controls of a chord, 2 to 4.
	Controls []string `json:"controls,omitempty"`
	// WhichWins decides axis and dpad composites when both directions of an
	// axis are down: "" or "none" gives 0, "last" the one pressed last.
	WhichWins string `json:"whichWins,omitempty"`
	// Mods are modifier groups ("mod:ctrl") that must be down.
	Mods []string `json:"mods,omitempty"`
	// Processors run in order on the binding's value.
	Processors []ProcessorSpec `json:"processors,omitempty"`
	// Interaction decides when a Button action fires; Axis and Vec2 actions
	// accept press and repeat. Absent means press.
	Interaction *InteractionSpec `json:"interaction,omitempty"`
	// Threshold is the value at which an analog control presses a Button
	// action. Zero means 0.5.
	Threshold float32 `json:"threshold,omitempty"`
	// Locked keeps the binding out of rebinding and conflict resolution.
	Locked bool `json:"locked,omitempty"`
}

BindingSpec is one binding. Exactly one of Control and Composite is set.

type Bindings

type Bindings struct {
	// contains filtered or unexported fields
}

Bindings are compiled bindings: the default bindings of a game (from ParseBindings) or a player's effective bindings (defaults plus profile overrides). They are immutable once built and safe to share between players and goroutines.

func CompileBindings

func CompileBindings(f BindingsFile, acts *Actions) (*Bindings, error)

CompileBindings validates and compiles a decoded bindings file, like ParseBindings.

func NewBindings

func NewBindings(acts *Actions) *Bindings

NewBindings returns empty bindings for acts: every action reads zero. It is the placeholder while the bindings file loads. Panics with "input: " if acts is nil or not frozen.

func ParseBindings

func ParseBindings(data []byte, acts *Actions) (*Bindings, error)

ParseBindings decodes, validates and compiles a bindings file against acts. It reports every problem at once (errors.Join), each prefixed with its path in the file:

$.mappings.gameplay.bindings.jump[1].control: unknown control "pad:soth"

Panics with "input: " if acts is nil or not frozen.

func (*Bindings) Actions

func (b *Bindings) Actions() *Actions

Actions returns the action table the bindings were compiled against.

func (*Bindings) ControlString

func (b *Bindings) ControlString(c Control) string

ControlString returns the file form of c, with touch region names.

func (*Bindings) File

func (b *Bindings) File() BindingsFile

File returns the decoded file the bindings were compiled from. Treat it as read-only.

func (*Bindings) HasMapping

func (b *Bindings) HasMapping(name string) bool

HasMapping reports whether the bindings define the mapping name.

func (*Bindings) MappingNames

func (b *Bindings) MappingNames() []string

MappingNames returns the mapping names, sorted.

type BindingsFile

type BindingsFile struct {
	// Version is the format version, currently 1.
	Version int `json:"version"`
	// Groups names sets of mappings that can be active at the same time.
	// Rebinding checks conflicts inside a mapping and its groups.
	Groups map[string][]string `json:"groups,omitempty"`
	// Mappings are the mapping contexts by name.
	Mappings map[string]MappingSpec `json:"mappings"`
}

BindingsFile is the JSON form of a bindings file (input/bindings.json): the default bindings a game ships. Decode it with ParseBindings, which validates it against an Actions table and compiles it. The JSON shape follows encoding/json rules and is described in the GOD TypeSchema subset by schema/bindings.schema.json.

type Capture

type Capture struct {
	Player int
	Target Slot
	// Control is the captured control, Mods the modifier groups held with
	// it (bit per Mod; only for actions declared with AllowMods).
	Control Control
	Mods    uint8
	// Canceled is set when a cancel control ended the listen.
	Canceled bool
}

Capture is the result of a listen, delivered in Events.Captured.

type Conflict

type Conflict struct {
	Slot
	Locked bool
}

Conflict is a binding that uses the same control (with the same modifiers) as a rebind target, in the target's mapping or a mapping of one of its groups.

type Control

type Control struct {
	Type ControlType
	Part Part
	// Code is the Key, Mod, MouseButton, PadButton, Stick, raw index or
	// touch region index (TouchAny for touch:any), depending on Type.
	Code uint16
}

Control is one physical input of one device class: a key, a mouse button, a stick half, a touch region. It is 4 bytes, comparable and pointer-free. Files spell it as a string, see ParseControl and Control.String.

func KeyControl

func KeyControl(k Key) Control

KeyControl returns the control of key k.

func MouseButtonControl

func MouseButtonControl(b MouseButton) Control

MouseButtonControl returns the control of mouse button b.

func PadButtonControl

func PadButtonControl(b PadButton) Control

PadButtonControl returns the control of gamepad button b.

func ParseControl

func ParseControl(s string, region func(name string) (uint16, bool)) (Control, error)

ParseControl parses the file form of a control. region resolves a touch region name to its index; nil rejects every touch control except touch:any.

func (Control) Class

func (c Control) Class() DeviceClass

Class returns the device class the control belongs to.

func (Control) IsZero

func (c Control) IsZero() bool

IsZero reports whether c is the zero Control ("no control").

func (Control) String

func (c Control) String() string

String returns the file form of c ("key:Space", "pad:leftstickY-"). Touch regions print as "touch:#<index>" because the name lives in the bindings; use Bindings.ControlString for the authored form.

type ControlType

type ControlType uint8

ControlType says which family a Control belongs to.

const (
	CtrlKey          ControlType = iota + 1 // key:<Key>
	CtrlMod                                 // mod:shift|ctrl|alt|meta (either side)
	CtrlMouseButton                         // mouse:left|right|middle|back|forward
	CtrlMouseWheel                          // mouse:wheel (Vec2, per tick)
	CtrlMouseDelta                          // mouse:delta (Vec2, logical px per tick)
	CtrlPadButton                           // pad:<button>, standard layout
	CtrlPadStick                            // pad:leftstick|rightstick
	CtrlPadRawButton                        // padraw:b<n>
	CtrlPadRawAxis                          // padraw:a<n>
	CtrlTouch                               // touch:<region> or touch:any
)

Control types.

type DeviceChanges

type DeviceChanges struct {
	Connected    []DeviceInfo
	Disconnected []DeviceID
}

DeviceChanges are the pads a Source saw connect and disconnect since its last Poll. The router resets it before each Poll.

type DeviceClass

type DeviceClass uint8

DeviceClass is a kind of device.

const (
	Keyboard DeviceClass = iota + 1
	Mouse
	Gamepad
	Touch
)

Device classes.

func (DeviceClass) String

func (c DeviceClass) String() string

String returns "keyboard", "mouse", "gamepad" or "touch".

type DeviceID

type DeviceID uint16

DeviceID identifies a device for the life of a Router. Keyboard, mouse and touch screen have fixed IDs; a Source assigns pad IDs (at least FirstPadDevice) and may reuse one only after its pad disconnected.

const (
	KeyboardDevice DeviceID = 1
	MouseDevice    DeviceID = 2
	TouchDevice    DeviceID = 3
	FirstPadDevice DeviceID = 16
)

Fixed device IDs.

type DeviceInfo

type DeviceInfo struct {
	ID    DeviceID
	Class DeviceClass
	// Name is the device's name ("Xbox Wireless Controller").
	Name string
	// GUID is the SDL GUID of a gamepad; with Name it matches a reconnected
	// pad to its player.
	GUID   string
	Family Family
}

DeviceInfo describes a connected device.

type Events

type Events struct {
	// DevicesConnected and DevicesDisconnected list pad hot-plugs.
	DevicesConnected    []DeviceInfo
	DevicesDisconnected []DeviceInfo
	// PlayersJoined and PlayersLeft list player indices (Join policy and
	// Player.Leave).
	PlayersJoined []int
	PlayersLeft   []int
	// DevicesLost lists devices that disconnected while assigned to a
	// player; the player keeps its slot. DevicesRestored lists lost pads
	// that came back (same GUID and name) and were reattached.
	DevicesLost     []PlayerDevice
	DevicesRestored []PlayerDevice
	// ActiveDeviceChanged lists players whose last-used device changed:
	// time to switch prompt glyphs.
	ActiveDeviceChanged []int
	// Captured holds the results of rebinding listens (see Player.Listen).
	Captured []Capture
}

Events are what happened during one Router.Update. The slices are reset (length 0, capacity kept) at the start of every Update, so the pointer from Router.Events is stable and the contents are valid until the next Update.

type Family

type Family uint8

Family is a device family; prompts pick glyphs and names by it.

const (
	FamilyGeneric Family = iota
	FamilyXbox
	FamilyPlayStation
	FamilyNintendo
	FamilyKeyboard // keyboard and mouse
	FamilyTouch
)

Families.

func FamilyOf

func FamilyOf(name string) Family

FamilyOf guesses a gamepad's family from its name.

func (Family) String

func (f Family) String() string

String returns the family's short name ("xbox", "kbm"), as used in glyph keys.

type Frame

type Frame struct {
	// Unfocused is set while the window has no keyboard focus; the router
	// then treats every control as up. The zero Frame is focused.
	Unfocused bool
	// Width and Height are the logical screen size, for touch regions.
	Width, Height uint16
	// Keys holds the keys that are down.
	Keys  KeySet
	Mouse MouseFrame
	// Pads[:NPads] are the connected gamepads.
	Pads  [MaxPads]PadFrame
	NPads uint8
	// Touches[:NTouches] are the active touches.
	Touches  [MaxTouches]TouchFrame
	NTouches uint8
}

Frame is one tick of raw device state. It is plain data with fixed-size arrays and no pointers: a Source fills it, tests build it by hand, a Recorder stores it. Positions are in logical (Layout) pixels.

type InteractionSpec

type InteractionSpec struct {
	// Press is down while the control is (the default).
	Press bool `json:"press,omitempty"`
	// Release fires for one tick when the control goes up.
	Release bool `json:"release,omitempty"`
	// Hold is down once the control has been down this long.
	Hold string `json:"hold,omitempty"`
	// Tap fires for one tick on release if the control was down less than
	// this long.
	Tap string `json:"tap,omitempty"`
	// DoubleTap fires on a second press within this window.
	DoubleTap string `json:"doubleTap,omitempty"`
	// Repeat fires on the press and then periodically while held.
	Repeat *RepeatSpec `json:"repeat,omitempty"`
}

InteractionSpec is one interaction. Exactly one field is set. Durations are Go duration strings ("350ms").

type Key

type Key uint8

Key is a physical keyboard key, named by its position on a US layout ("W" stays the key below "2" on AZERTY). The names are the same as Ebiten's key names without the "Key" prefix; [KeyName] and ParseKey convert. The zero Key is "none".

const (
	KeyA Key = iota + 1
	KeyB
	KeyC
	KeyD
	KeyE
	KeyF
	KeyG
	KeyH
	KeyI
	KeyJ
	KeyK
	KeyL
	KeyM
	KeyN
	KeyO
	KeyP
	KeyQ
	KeyR
	KeyS
	KeyT
	KeyU
	KeyV
	KeyW
	KeyX
	KeyY
	KeyZ
	KeyAltLeft
	KeyAltRight
	KeyArrowDown
	KeyArrowLeft
	KeyArrowRight
	KeyArrowUp
	KeyBackquote
	KeyBackslash
	KeyBackspace
	KeyBracketLeft
	KeyBracketRight
	KeyCapsLock
	KeyComma
	KeyContextMenu
	KeyControlLeft
	KeyControlRight
	KeyDelete
	KeyDigit0
	KeyDigit1
	KeyDigit2
	KeyDigit3
	KeyDigit4
	KeyDigit5
	KeyDigit6
	KeyDigit7
	KeyDigit8
	KeyDigit9
	KeyEnd
	KeyEnter
	KeyEqual
	KeyEscape
	KeyF1
	KeyF2
	KeyF3
	KeyF4
	KeyF5
	KeyF6
	KeyF7
	KeyF8
	KeyF9
	KeyF10
	KeyF11
	KeyF12
	KeyF13
	KeyF14
	KeyF15
	KeyF16
	KeyF17
	KeyF18
	KeyF19
	KeyF20
	KeyF21
	KeyF22
	KeyF23
	KeyF24
	KeyHome
	KeyInsert
	KeyIntlBackslash
	KeyMetaLeft
	KeyMetaRight
	KeyMinus
	KeyNumLock
	KeyNumpad0
	KeyNumpad1
	KeyNumpad2
	KeyNumpad3
	KeyNumpad4
	KeyNumpad5
	KeyNumpad6
	KeyNumpad7
	KeyNumpad8
	KeyNumpad9
	KeyNumpadAdd
	KeyNumpadDecimal
	KeyNumpadDivide
	KeyNumpadEnter
	KeyNumpadEqual
	KeyNumpadMultiply
	KeyNumpadSubtract
	KeyPageDown
	KeyPageUp
	KeyPause
	KeyPeriod
	KeyPrintScreen
	KeyQuote
	KeyScrollLock
	KeySemicolon
	KeyShiftLeft
	KeyShiftRight
	KeySlash
	KeySpace
	KeyTab
)

Keys. The order is part of the recording format (see Recorder); append new keys at the end.

func ParseKey

func ParseKey(name string) (Key, bool)

ParseKey returns the key named name (case-sensitive, as Key.String writes it).

func (Key) String

func (k Key) String() string

String returns the key's name ("Space", "ArrowUp"), or "" for an invalid key.

type KeySet

type KeySet [2]uint64

KeySet is the set of keys that are down: one bit per key, no pointers, so a Frame stays a plain value that can be copied and recorded.

func (*KeySet) Clear

func (s *KeySet) Clear(k Key)

Clear removes k from the set.

func (*KeySet) Empty

func (s *KeySet) Empty() bool

Empty reports whether no key is down.

func (*KeySet) Has

func (s *KeySet) Has(k Key) bool

Has reports whether k is in the set.

func (*KeySet) Reset

func (s *KeySet) Reset()

Reset empties the set.

func (*KeySet) Set

func (s *KeySet) Set(k Key)

Set adds k to the set. The zero Key is ignored.

type Kind

type Kind uint8

Kind says what value an action carries.

const (
	// Button is digital: down or up, with edges and held ticks. Analog
	// controls press it when they cross the binding's threshold.
	Button Kind = iota + 1
	// Axis is one float: [-1, 1] from an axis composite or a stick half,
	// [0, 1] from a trigger.
	Axis
	// Vec2 is two floats: a stick, a dpad composite, the mouse delta.
	Vec2
)

Action kinds.

func (Kind) String

func (k Kind) String() string

String returns "Button", "Axis" or "Vec2".

type ListenOptions

type ListenOptions struct {
	// Target is the slot being rebound. Its Class decides which devices
	// may be captured: kbm takes keys and mouse buttons, gamepad takes pad
	// buttons, sticks and triggers. Touch slots cannot be captured.
	Target Slot
	// Cancel are controls that end listening without a result. nil means
	// Escape and the Start button.
	Cancel []Control
}

ListenOptions configure Player.Listen.

type ManualSource

type ManualSource struct {
	Frame   Frame
	Changes DeviceChanges
	// Names maps keys to layout labels for KeyName; nil uses Key.String.
	Names map[Key]string
	// Vibrations records every Vibrate call.
	Vibrations []Vibration
}

ManualSource is a Source whose next frame the caller sets: tests, bots, network clients. Set Frame and Changes before each Router.Update. Changes are delivered once and then cleared; Frame stays until changed.

func (*ManualSource) KeyName

func (m *ManualSource) KeyName(k Key) string

KeyName implements Source.

func (*ManualSource) Poll

func (m *ManualSource) Poll(f *Frame, ch *DeviceChanges)

Poll implements Source.

func (*ManualSource) Vibrate

func (m *ManualSource) Vibrate(id DeviceID, strong, weak float32, d time.Duration)

Vibrate implements Source.

type MappingSpec

type MappingSpec struct {
	// Priority orders active mappings: higher is evaluated first.
	Priority int `json:"priority,omitempty"`
	// Block stops evaluation of every mapping below this one.
	Block bool `json:"block,omitempty"`
	// StrictMods makes bindings without mods ignore their control while
	// any modifier the binding does not list is down.
	StrictMods bool `json:"strictMods,omitempty"`
	// Bindings lists the bindings of each action by action name.
	Bindings map[string][]BindingSpec `json:"bindings"`
	// Touch declares the touch regions that touch:<name> controls of this
	// mapping refer to.
	Touch map[string]TouchRegionSpec `json:"touch,omitempty"`
}

MappingSpec is one mapping context in a BindingsFile.

type Mod

type Mod uint8

Mod is a modifier group: either the left or the right key.

const (
	ModShift Mod = iota
	ModCtrl
	ModAlt
	ModMeta
)

Modifier groups, also used as bits in a binding's modifier mask.

type MouseButton

type MouseButton uint8

MouseButton is a mouse button. The values match Ebiten's MouseButton0..4.

const (
	MouseLeft MouseButton = iota
	MouseMiddle
	MouseRight
	MouseBack
	MouseForward
)

Mouse buttons.

type MouseFrame

type MouseFrame struct {
	// X and Y are the cursor position in logical pixels.
	X, Y float32
	// WheelX and WheelY are this tick's wheel movement.
	WheelX, WheelY float32
	// Buttons has bit b set while MouseButton b is down.
	Buttons uint8
}

MouseFrame is the mouse part of a Frame.

func (*MouseFrame) Down

func (m *MouseFrame) Down(b MouseButton) bool

Down reports whether button b is down.

func (*MouseFrame) SetDown

func (m *MouseFrame) SetDown(b MouseButton, down bool)

SetDown sets or clears button b.

type Options

type Options struct {
	// Actions is the frozen action table. Required.
	Actions *Actions
	// Bindings are the default bindings. nil means [NewBindings]: nothing
	// is bound until [Router.SetBindings].
	Bindings *Bindings
	// Players is the number of player slots, 1..MaxPlayers. 0 means 1.
	Players int
	// Assign is the device assignment policy.
	Assign AssignPolicy
	// JoinAction is the Button action that claims a slot (AssignJoin).
	JoinAction Action
	// TPS is the tick rate interaction durations are converted with. 0
	// means 60.
	TPS int
	// OnError receives profile problems that are skipped (an override for
	// an action that no longer exists). nil logs them.
	OnError func(error)
}

Options configure a Router.

type Override

type Override struct {
	Mapping string `json:"mapping"`
	Action  string `json:"action"`
	// Class is "kbm", "gamepad" or "touch".
	Class string `json:"class"`
	Slot  int    `json:"slot"`
	// Part names a composite part ("up", "neg"); Control or Unbind then
	// apply to that part only.
	Part string `json:"part,omitempty"`
	// Binding replaces the whole binding (or adds it, past the last slot).
	Binding *BindingSpec `json:"binding,omitempty"`
	// Control replaces the control of Part.
	Control string `json:"control,omitempty"`
	// Unbind removes the binding or part on purpose.
	Unbind bool `json:"unbind,omitempty"`
}

Override changes one slot: the Slot-th binding of class Class of an action in a mapping. Exactly one of Binding, Control and Unbind is set.

type PadButton

type PadButton uint8

PadButton is a gamepad button in the standard layout, named by position: South is A on Xbox, Cross on PlayStation and B on Nintendo pads. The order matches Ebiten's StandardGamepadButton.

const (
	PadSouth  PadButton = iota // right cluster, bottom
	PadEast                    // right cluster, right
	PadWest                    // right cluster, left
	PadNorth                   // right cluster, top
	PadLB                      // front top left (bumper)
	PadRB                      // front top right
	PadLT                      // front bottom left (trigger, analog 0..1)
	PadRT                      // front bottom right (trigger, analog 0..1)
	PadSelect                  // center left (Back, View, Share, Minus)
	PadStart                   // center right (Start, Menu, Options, Plus)
	PadLS                      // left stick press
	PadRS                      // right stick press
	PadUp                      // dpad
	PadDown
	PadLeft
	PadRight
	PadHome // center (Guide, PS, Home)
	PadButtonCount
)

Gamepad buttons.

type PadFrame

type PadFrame struct {
	// Device identifies the pad; it must match a connected DeviceInfo.
	Device DeviceID
	// Standard is set when the pad has a standard-layout mapping, so
	// Buttons, Triggers and Axes are meaningful. Otherwise only the raw
	// fields are.
	Standard bool
	// Buttons has bit b set while PadButton b is down.
	Buttons uint32
	// Triggers are LT and RT, 0..1.
	Triggers [2]float32
	// Axes are left X, left Y, right X, right Y, -1..1, Y down positive.
	Axes [4]float32
	// RawButtons and RawAxes are the unmapped values, for padraw: controls.
	RawButtons uint64
	RawAxes    [MaxRawAxes]float32
}

PadFrame is one gamepad in a Frame.

func (*PadFrame) Down

func (p *PadFrame) Down(b PadButton) bool

Down reports whether button b is down.

func (*PadFrame) SetDown

func (p *PadFrame) SetDown(b PadButton, down bool)

SetDown sets or clears button b.

type Part

type Part uint8

Part selects one component of a two-dimensional or signed control.

const (
	PartWhole Part = iota
	PartX          // -1..1
	PartY          // -1..1, down positive
	PartXPos       // 0..1, right half
	PartXNeg       // 0..1, left half
	PartYPos       // 0..1, lower half
	PartYNeg       // 0..1, upper half
)

Parts. PartWhole is the control's natural value.

type Player

type Player struct {
	// contains filtered or unexported fields
}

Player is one player slot: assigned devices, a stack of active mappings, a profile and the resulting State. Get one with Router.Player or Router.Lobby.

func (*Player) ActiveDevice

func (p *Player) ActiveDevice() DeviceInfo

ActiveDevice returns the device that last produced input for this player: prompts follow its Family. Before any input it is the first assigned device.

func (*Player) Assign

func (p *Player) Assign(id DeviceID)

Assign gives device id to p, taking it from whoever has it, and marks p joined. Unknown devices are ignored.

func (*Player) Bind

func (p *Player) Bind(t Slot, c Control, mods uint8, policy ResolvePolicy) error

Bind binds control c (with modifiers mods) to slot t, records the change as profile overrides and rebuilds the player's bindings. Conflicts (see Player.Conflicts) are resolved by policy. It returns an error, and changes nothing, when the mapping or slot class doesn't fit, the target is locked, a Replace or Swap would touch a locked binding, or the target is a composite and t.Part is empty.

func (*Player) Bindings

func (p *Player) Bindings() *Bindings

Bindings returns the player's effective bindings: the defaults with the profile's overrides applied.

func (*Player) CancelListen

func (p *Player) CancelListen()

CancelListen stops listening without a result.

func (*Player) Conflicts

func (p *Player) Conflicts(t Slot, c Control, mods uint8) []Conflict

Conflicts returns the bindings that already use c with modifiers mods in the target's mapping and the mappings that share a group with it. The target slot itself is not reported.

func (*Player) ConsumePress

func (p *Player) ConsumePress(a Action)

ConsumePress uses up the press of the Button action a: State.PressedWithin reports false until a goes down again, and State.JustPressed reports false for the rest of this tick, so a second reader does not act on the same press. Down and HeldTicks are unchanged, and so is Router.Any. Panics like the State queries for an unknown action or one that is not a Button.

func (*Player) Devices

func (p *Player) Devices() []DeviceID

Devices returns the devices assigned to p. Valid until the next change.

func (*Player) Index

func (p *Player) Index() int

Index returns the slot index, or -1 for the lobby.

func (*Player) IsActive

func (p *Player) IsActive(name string) bool

IsActive reports whether the mapping name is on the stack.

func (*Player) Joined

func (p *Player) Joined() bool

Joined reports whether the slot is taken. With AssignSingle player 0 is always joined.

func (*Player) Leave

func (p *Player) Leave()

Leave returns all of p's devices to the lobby, forgets its lost devices and frees the slot (PlayersLeft event). The lobby cannot leave.

func (*Player) Listen

func (p *Player) Listen(opts ListenOptions)

Listen starts capturing the next control for opts.Target. While listening, every action of the player reads zero, and presses buffered before (see State.PressedWithin) are forgotten. It first waits until every capturable control is up (so the click on "Rebind" is not captured), then takes the first control that goes down. The result arrives in Events.Captured of a later tick.

Panics with "input: " if the player is already listening, the target action is not declared, or the target class is touch.

func (*Player) Listening

func (p *Player) Listening() bool

Listening reports whether the player is listening.

func (*Player) Mappings

func (p *Player) Mappings() []string

Mappings returns the active mapping names in push order. Valid until the next change.

func (*Player) Pop

func (p *Player) Pop(name string)

Pop removes the mapping name from the stack, wherever it is. It is a no-op if the mapping is not active.

func (*Player) Profile

func (p *Player) Profile() *Profile

Profile returns the player's profile. Settings may be changed in place and apply at the next Update; after changing Overrides directly, call SetProfile.

func (*Player) Push

func (p *Player) Push(name string)

Push activates the mapping name on top of the stack (moving it to the top if it is active already). Mappings the bindings do not define are kept on the stack and stay inactive until bindings that define them are set. The change takes effect at the next Update, so every system in a tick sees the same state.

func (*Player) Reset

func (p *Player) Reset(mapping string, a Action)

Reset drops the player's overrides of action a in mapping, so the defaults apply again.

func (*Player) ResetAll

func (p *Player) ResetAll()

ResetAll drops every override of the player. Settings are kept.

func (*Player) Rumble

func (p *Player) Rumble(strong, weak float32, d time.Duration)

Rumble asks the player's gamepads to vibrate with motor strengths 0..1. Requests within one tick merge to the strongest; the next Update sends them, scaled by the profile's Vibration setting.

func (*Player) SetMappings

func (p *Player) SetMappings(names ...string)

SetMappings replaces the stack.

func (*Player) SetProfile

func (p *Player) SetProfile(prof *Profile)

SetProfile replaces the player's profile (nil means an empty one) and rebuilds its bindings. Overrides that don't apply are skipped and reported to Options.OnError.

func (*Player) Slots

func (p *Player) Slots(mapping string, a Action) []SlotInfo

Slots lists the bindings of action a in mapping, in slot order per class.

func (*Player) State

func (p *Player) State() *State

State returns the player's action state. The pointer is stable for the life of the Router.

func (*Player) Unassign

func (p *Player) Unassign(id DeviceID)

Unassign returns device id to the lobby.

type PlayerDevice

type PlayerDevice struct {
	Player int
	Device DeviceInfo
}

PlayerDevice pairs a player index with a device.

type Pointer

type Pointer struct {
	X, Y float32
	// Valid is false when the player has neither mouse nor touch.
	Valid bool
	// Touch is set when the position comes from a touch.
	Touch bool
}

Pointer is a screen position in logical pixels.

type ProcessorSpec

type ProcessorSpec struct {
	// Deadzone zeroes values below it and rescales the rest to start at 0:
	// radial for Vec2, per axis for Axis.
	Deadzone *float32 `json:"deadzone,omitempty"`
	// Max is the value that maps to 1 (default 1).
	Max *float32 `json:"max,omitempty"`
	// Invert negates "x", "y" or "xy".
	Invert string `json:"invert,omitempty"`
	// Scale multiplies: one value for both axes or [x, y].
	Scale []float32 `json:"scale,omitempty"`
	// Normalize clamps a Vec2's length to 1.
	Normalize bool `json:"normalize,omitempty"`
	// Sensitivity applies the profile's look settings: Sensitivity and
	// InvertY.
	Sensitivity bool `json:"sensitivity,omitempty"`
	// Curve is "linear", "quadratic" or "cubic": finer control near the
	// center.
	Curve string `json:"curve,omitempty"`
}

ProcessorSpec is one processor. Exactly one field is set (Max only together with Deadzone).

type Profile

type Profile struct {
	// Version is the format version, currently 1. Marshal sets it.
	Version   int        `json:"version"`
	Settings  Settings   `json:"settings"`
	Overrides []Override `json:"overrides,omitempty"`
}

Profile is one player's input preferences: settings plus binding overrides on top of the default bindings. It is also the JSON form of a profile file (input.json in the user's config directory); see ParseProfile and Profile.Marshal. Only the diff to the defaults is stored, so a changed default reaches every action the player never rebound.

func ParseProfile

func ParseProfile(data []byte) (*Profile, error)

ParseProfile decodes and checks a profile file, reporting every problem at once. Overrides that name a mapping or action the bindings don't have are not errors here: they are skipped (and reported to Options.OnError) when the profile is applied, so old saves still load.

func (*Profile) Marshal

func (p *Profile) Marshal() ([]byte, error)

Marshal returns the profile as indented JSON, with Version set to 1.

type Recorder

type Recorder struct {

	// MaxTicks caps the recording: when it is exceeded the oldest entries
	// are dropped. 0 means no limit.
	MaxTicks int
	// contains filtered or unexported fields
}

Recorder keeps the raw input of every tick, for replays, bug reports and simulation tests. Attach it with Router.Record; play it back with NewReplaySource. Because every interaction is counted in ticks, a replay reproduces the same State sequence.

Ticks whose frame equals the previous one and carry no device changes are stored as a repeat count, so idle stretches cost nothing. A changed tick appends one entry (a few hundred bytes), which allocates while recording.

func ReadRecording

func ReadRecording(rd io.Reader) (*Recorder, error)

ReadRecording reads a recording written by Recorder.WriteTo.

func (*Recorder) Ticks

func (r *Recorder) Ticks() int

Ticks returns the number of recorded ticks.

func (*Recorder) WriteTo

func (r *Recorder) WriteTo(w io.Writer) (int64, error)

WriteTo writes the recording with encoding/gob.

type RepeatSpec

type RepeatSpec struct {
	// Delay is the time from the press to the first repeat.
	Delay string `json:"delay"`
	// Every is the time between repeats.
	Every string `json:"every"`
}

RepeatSpec configures the repeat interaction.

type ReplaySource

type ReplaySource struct {

	// Names maps keys to layout labels for KeyName; nil uses Key.String.
	Names map[Key]string
	// contains filtered or unexported fields
}

ReplaySource plays a Recorder back as a Source. After the last tick it keeps returning the last frame with every control released.

func NewReplaySource

func NewReplaySource(rec *Recorder) *ReplaySource

NewReplaySource returns a source that replays rec from its first tick.

func (*ReplaySource) Done

func (s *ReplaySource) Done() bool

Done reports whether every recorded tick has been played.

func (*ReplaySource) KeyName

func (s *ReplaySource) KeyName(k Key) string

KeyName implements Source.

func (*ReplaySource) Poll

func (s *ReplaySource) Poll(f *Frame, ch *DeviceChanges)

Poll implements Source.

func (*ReplaySource) Vibrate

Vibrate implements Source; a replay does not rumble.

type ResolvePolicy

type ResolvePolicy uint8

ResolvePolicy decides what Player.Bind does with conflicts.

const (
	// Keep leaves conflicting bindings as they are: both actions fire.
	Keep ResolvePolicy = iota
	// Replace unbinds the conflicting bindings.
	Replace
	// Swap gives the conflicting bindings the target's old control.
	Swap
)

Conflict policies.

type Router

type Router struct {
	// contains filtered or unexported fields
}

Router turns raw device input into per-player action State. It is the World resource of the input system: Router.Update runs once per tick (inputsys.InputSystem does it), systems read player states.

A Router is single-goroutine, like the World.

func NewRouter

func NewRouter(src Source, opts Options) *Router

NewRouter returns a Router reading src. Panics with "input: " if src is nil, Options.Actions is nil or not frozen, Players is out of range, or the Join policy has no Button JoinAction.

func (*Router) Actions

func (r *Router) Actions() *Actions

Actions returns the action table.

func (*Router) Any

func (r *Router) Any() *State

Any returns the combined state of every joined player and the lobby: buttons are ORed, axes take the largest magnitude. For title screens and "press any button" prompts. Edges are computed on the combined value.

func (*Router) BindingName

func (r *Router) BindingName(c Control, mods uint8, fam Family) string

BindingName is ControlName with the modifiers in front: "Ctrl+S".

func (*Router) Bindings

func (r *Router) Bindings() *Bindings

Bindings returns the default bindings.

func (*Router) ControlName

func (r *Router) ControlName(c Control, fam Family) string

ControlName returns a label for c in prompts and rebinding menus. Keys use the current keyboard layout (the key at the US "Q" position shows "A" on AZERTY); gamepad buttons use the family's names ("A" on Xbox, "Cross" on PlayStation); FamilyGeneric uses Xbox names.

func (*Router) Device

func (r *Router) Device(id DeviceID) (DeviceInfo, bool)

Device returns the info of a connected device.

func (*Router) Devices

func (r *Router) Devices() []DeviceInfo

Devices returns the connected devices. Valid until the next Update.

func (*Router) Events

func (r *Router) Events() *Events

Events returns this tick's events. The pointer is stable.

func (*Router) Frame

func (r *Router) Frame() *Frame

Frame returns the raw frame of the current tick (after focus handling).

func (*Router) GlyphKey

func (r *Router) GlyphKey(c Control, fam Family) string

GlyphKey returns a stable key for the prompt glyph of c on a device of family fam: "<family>/<control>" with ':' replaced by '_', for example "xbox/pad_south" or "kbm/key_Space". Games map it to a sprite in their prompt atlas.

func (*Router) Lobby

func (r *Router) Lobby() *Player

Lobby returns the player that owns every unassigned device. With AssignSingle it owns nothing. Push mappings on it like on any player (title and join screens).

func (*Router) Player

func (r *Router) Player(i int) *Player

Player returns player slot i. Panics with "input: player index out of range".

func (*Router) Players

func (r *Router) Players() int

Players returns the number of player slots.

func (*Router) Record

func (r *Router) Record(rec *Recorder)

Record makes every following Update append its raw input to rec; nil stops recording.

func (*Router) SetBindings

func (r *Router) SetBindings(b *Bindings)

SetBindings replaces the default bindings (a loaded or hot-reloaded file). Every player's profile is applied again; action states are kept, so held actions don't fire a new press. Panics with "input: " if b was compiled for another Actions table.

func (*Router) Source

func (r *Router) Source() Source

Source returns the source the router polls.

func (*Router) TPS

func (r *Router) TPS() int

TPS returns the tick rate durations are converted with.

func (*Router) Tick

func (r *Router) Tick() uint64

Tick returns the number of completed Updates.

func (*Router) Update

func (r *Router) Update()

Update polls the source once and evaluates every player. Call it once per tick, before any system reads a State. 0 allocs in steady state.

type Settings

type Settings struct {
	// Deadzone replaces the deadzone of every deadzone processor when it
	// is greater than 0 (and below the processor's max).
	Deadzone float32 `json:"deadzone,omitempty"`
	// InvertY flips Y in bindings with the sensitivity processor.
	InvertY bool `json:"invertY,omitempty"`
	// Sensitivity scales bindings with the sensitivity processor. Zero
	// means 1.
	Sensitivity float32 `json:"sensitivity,omitempty"`
	// Vibration scales rumble. Zero means 1; negative turns it off.
	Vibration float32 `json:"vibration,omitempty"`
}

Settings are per-player options read every tick, so changing them takes effect at the next Update without rebuilding anything.

type Slot

type Slot struct {
	Mapping string
	Action  Action
	Class   SlotClass
	Slot    int
	Part    string
}

Slot names one rebindable slot: the Slot-th binding of class Class of an action in a mapping, or one Part of it ("up" of a dpad, "neg" of an axis).

type SlotClass

type SlotClass uint8

SlotClass groups bindings for rebinding menus: each action has numbered slots per class (keyboard and mouse primary and secondary, gamepad).

const (
	SlotKBM SlotClass = iota + 1 // keyboard and mouse
	SlotGamepad
	SlotTouch
)

Slot classes.

func ParseSlotClass

func ParseSlotClass(s string) (SlotClass, bool)

ParseSlotClass is the inverse of SlotClass.String.

func SlotClassOf

func SlotClassOf(c DeviceClass) SlotClass

SlotClassOf returns the slot class a device class binds through: keyboard and mouse share kbm. Use it to rebind for the player's active device: SlotClassOf(p.ActiveDevice().Class).

func (SlotClass) String

func (c SlotClass) String() string

String returns "kbm", "gamepad" or "touch".

type SlotInfo

type SlotInfo struct {
	Slot
	// Control is the control of a single binding, Mods its modifiers.
	Control Control
	Mods    uint8
	// Parts are the part names and controls of a composite.
	Parts    []string
	Controls []Control
	Locked   bool
	// Unbound is set for a slot the player cleared.
	Unbound bool
}

SlotInfo describes one binding of an action for a rebinding menu.

type Source

type Source interface {
	// Poll fills f with the current device state (f is zeroed first) and
	// appends pad connects and disconnects to ch.
	Poll(f *Frame, ch *DeviceChanges)
	// KeyName returns the label of k on the current keyboard layout, or ""
	// when unknown.
	KeyName(k Key) string
	// Vibrate rumbles the pad d for duration d with motor strengths 0..1.
	Vibrate(id DeviceID, strong, weak float32, d time.Duration)
}

Source produces Frames. ebiteninput.Source reads Ebiten; ManualSource and ReplaySource serve tests and replays. All methods are called on the game goroutine.

type State

type State struct {
	// contains filtered or unexported fields
}

State is one player's action values for the current tick. It is written by Router.Update and read-only to game code; the pointer from Player.State is stable for the life of the Router, so systems cache it.

Queries are an index and a mask: 0 allocs. Asking for an action of the wrong kind panics with `input: action "jump" is Button, not Vec2`; an ID that was never declared panics with "input: unknown action". Actions the bindings never mention read as zero.

func (*State) Axis

func (s *State) Axis(a Action) float32

Axis returns the value of the Axis action a.

func (*State) Down

func (s *State) Down(a Action) bool

Down reports whether the Button action a is down.

func (*State) HeldTicks

func (s *State) HeldTicks(a Action) uint32

HeldTicks returns for how many ticks a has been down, counting this one; 0 while it is up.

func (*State) JustPressed

func (s *State) JustPressed(a Action) bool

JustPressed reports whether a went down this tick.

func (*State) JustReleased

func (s *State) JustReleased(a Action) bool

JustReleased reports whether a went up this tick. It also fires when a mapping that held a down was blocked or popped.

func (*State) Pointer

func (s *State) Pointer() Pointer

Pointer returns the pointer of this player: the mouse cursor when the player has the mouse, else the first touch.

func (*State) PressedWithin

func (s *State) PressedWithin(a Action, ticks uint32) bool

PressedWithin reports whether a went down in the last ticks ticks, counting this one, and that press was not consumed with Player.ConsumePress. PressedWithin(a, 1) equals JustPressed(a); 0 ticks is always false. Use it for input buffering: a Jump pressed a few ticks before landing still jumps.

func (*State) Progress

func (s *State) Progress(a Action) float32

Progress returns how far a hold interaction of a is, 0..1, for a fill ring.

func (*State) Strength

func (s *State) Strength(a Action) float32

Strength returns how far the strongest binding of a is pressed, 0..1: 1 for digital controls, the trigger or stick value for analog ones.

func (*State) Touch

func (s *State) Touch() []TouchControl

Touch returns the live geometry of the touch regions of this player's active mappings, for drawing virtual controls. Empty unless the player has the touch screen. Valid until the next Update.

func (*State) Vec2

func (s *State) Vec2(a Action) (x, y float32)

Vec2 returns the value of the Vec2 action a. Y is down positive.

type Stick

type Stick uint8

Stick is a gamepad stick.

const (
	LeftStick Stick = iota
	RightStick
)

Sticks.

type TouchControl

type TouchControl struct {
	// Name and Mapping identify the region in the bindings file.
	Name, Mapping string
	Kind          TouchKind
	// X0, Y0, X1, Y1 bound the region.
	X0, Y0, X1, Y1 float32
	// Circle is set for circular regions; CX, CY, R are then the circle.
	// For sticks CX, CY is the stick's base and R its travel.
	Circle    bool
	CX, CY, R float32
	// KnobX, KnobY is where a stick's knob is drawn.
	KnobX, KnobY float32
	// Pressed is set while a touch owns the region.
	Pressed bool
}

TouchControl is the live geometry of one touch region, in logical pixels, for drawing virtual controls (inputsys.TouchControlsExtract does).

type TouchFrame

type TouchFrame struct {
	// ID is stable while the finger stays down.
	ID   int32
	X, Y float32
}

TouchFrame is one active touch in a Frame.

type TouchKind

type TouchKind uint8

TouchKind is the kind of a touch region.

const (
	// TouchButton is digital: down while a touch that started in it lasts.
	TouchButton TouchKind = iota
	// TouchStick is a Vec2 from the stick's base to the touch, clamped to
	// its radius.
	TouchStick
	// TouchDrag is a Vec2 delta in logical pixels per tick, like the mouse.
	TouchDrag
)

Touch region kinds.

type TouchRegionSpec

type TouchRegionSpec struct {
	// Kind is "button", "stick" or "drag".
	Kind string `json:"kind"`
	// Area is [x0, y0, x1, y1]. One of Area and Circle is required.
	Area []float32 `json:"area,omitempty"`
	// Circle is [cx, cy, r].
	Circle []float32 `json:"circle,omitempty"`
	// Radius is a stick's travel. Zero means 0.1.
	Radius float32 `json:"radius,omitempty"`
	// Floating centers a stick where the touch starts instead of at the
	// center of its area.
	Floating bool `json:"floating,omitempty"`
}

TouchRegionSpec is a touch region in normalized screen coordinates (0..1 of the logical width and height; radii are fractions of the height).

type Vibration

type Vibration struct {
	Device       DeviceID
	Strong, Weak float32
	Duration     time.Duration
}

Vibration is one recorded Source.Vibrate call.

Directories

Path Synopsis
Package ebiteninput is the Ebiten input.Source: it reads keyboard, mouse, gamepads and touches through ebiten and inpututil into an input.Frame once per tick.
Package ebiteninput is the Ebiten input.Source: it reads keyboard, mouse, gamepads and touches through ebiten and inpututil into an input.Frame once per tick.
Package inputsys connects an input.Router to an ecs World: InputSystem updates the router once per tick and publishes it as a resource, and TouchControlsExtract draws the virtual touch controls.
Package inputsys connects an input.Router to an ecs World: InputSystem updates the router once per tick and publishes it as a resource, and TouchControlsExtract draws the virtual touch controls.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL