feat: port the client to MyGo native UI (0.3.0)
Switch from Asuka to MyGo, keeping the API client and the feature set: - servers: saved servers, passwordless and password login, proxy, self-signed certificates, per-server device tokens (Keystore), connect form, instance list sheet with switch/disconnect - sessions: virtualized list, search, new session, rename/archive/delete, running indicator, event stream keeps it live - chat: pushed window with system back bar, streaming Markdown via ui/markdown, reasoning and tool rows with image previews, footer menu (read aloud via a Kotlin TTS plugin, copy, fork), user message menu (copy, revert, fork), context usage ring and detail sheet, attachments (photos/files via the document picker), permissions - release builds allow plain http:// LAN servers (Go's net/http dials directly, no cleartext manifest needed) - a local fork of MyGo (third_party/mygo) lowers the Android host's minSdk to 24 (Android 7.0); Go 1.27.4 via mise Version 0.3.0.
This commit is contained in:
1 parent
2fb4a8ea79
commit
6c0ee61750
2538 files changed
+675779
-4792
No files matched your search
+234
@@ -0,0 +1,234 @@
|
||||
// Package gamepad reads game controllers: their buttons, triggers and
|
||||
// sticks in the standard layout of an Xbox controller, which the W3C's
|
||||
// Gamepad API and SDL's game controller database name, whatever pad it is:
|
||||
//
|
||||
// for _, pad := range gamepad.Pads() {
|
||||
// s := pad.State()
|
||||
// x, y := s.LeftStick()
|
||||
// if s.Pressed(gamepad.South) {
|
||||
// jump()
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// A game reads the pads' states once a frame, or once a step of its world,
|
||||
// and keeps the last to tell a button just pressed from one held
|
||||
// (State.JustPressed).
|
||||
//
|
||||
// The pads come from GameController.framework on macOS (Xbox, PlayStation,
|
||||
// Switch Pro and MFi controllers), XInput on Windows (Xbox controllers and
|
||||
// those that act as one, as Steam Input makes of others), evdev on Linux
|
||||
// (/dev/input, readable by the user at the seat), and the Gamepad API in
|
||||
// browsers. On macOS, input reaches the app in front only, as games
|
||||
// expect. Every function and method is safe to call from any goroutine.
|
||||
package gamepad
|
||||
|
||||
import (
|
||||
"math"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Button is a button of the standard layout, named by place: South is A
|
||||
// on an Xbox controller, Cross on a PlayStation one, B on a Nintendo one.
|
||||
type Button uint8
|
||||
|
||||
// The buttons, in the order of the W3C's standard gamepad.
|
||||
const (
|
||||
South Button = iota
|
||||
East
|
||||
West
|
||||
North
|
||||
LeftShoulder
|
||||
RightShoulder
|
||||
LeftTrigger // analog: Value is from 0 to 1
|
||||
RightTrigger
|
||||
Back // View, Select, Share, Minus
|
||||
Start
|
||||
LeftStickButton
|
||||
RightStickButton
|
||||
Up
|
||||
Down
|
||||
Left
|
||||
Right
|
||||
Guide // the Xbox, PlayStation or Home button, where the system leaves it
|
||||
ButtonCount
|
||||
)
|
||||
|
||||
// Axis is an axis of the sticks, from -1 to 1: right and down are
|
||||
// positive, as on the screen.
|
||||
type Axis uint8
|
||||
|
||||
// The axes.
|
||||
const (
|
||||
LeftX Axis = iota
|
||||
LeftY
|
||||
RightX
|
||||
RightY
|
||||
AxisCount
|
||||
)
|
||||
|
||||
// State is what a pad's controls read at one time.
|
||||
type State struct {
|
||||
// Buttons are from 0 to 1: 0 or 1 but for the triggers.
|
||||
Buttons [ButtonCount]float32
|
||||
// Axes are from -1 to 1, as the pad reports them, without a dead
|
||||
// zone.
|
||||
Axes [AxisCount]float32
|
||||
}
|
||||
|
||||
// Deadzone is how far from the middle a stick must move to count, as a
|
||||
// fraction of its reach: sticks rest a little off their middle.
|
||||
const Deadzone = 0.15
|
||||
|
||||
// pressThreshold is how far an analog trigger must go to be pressed.
|
||||
const pressThreshold = 0.25
|
||||
|
||||
// Value returns how far b is pressed, from 0 to 1.
|
||||
func (s State) Value(b Button) float32 {
|
||||
if b >= ButtonCount {
|
||||
return 0
|
||||
}
|
||||
return s.Buttons[b]
|
||||
}
|
||||
|
||||
// Pressed reports whether b is pressed: a trigger a quarter of the way.
|
||||
func (s State) Pressed(b Button) bool { return s.Value(b) >= pressThreshold }
|
||||
|
||||
// JustPressed reports whether b is pressed in s and was not in last, the
|
||||
// state read before.
|
||||
func (s State) JustPressed(last State, b Button) bool { return s.Pressed(b) && !last.Pressed(b) }
|
||||
|
||||
// JustReleased reports whether b was pressed in last and is not in s.
|
||||
func (s State) JustReleased(last State, b Button) bool { return !s.Pressed(b) && last.Pressed(b) }
|
||||
|
||||
// Axis returns the raw value of a, from -1 to 1.
|
||||
func (s State) Axis(a Axis) float32 {
|
||||
if a >= AxisCount {
|
||||
return 0
|
||||
}
|
||||
return s.Axes[a]
|
||||
}
|
||||
|
||||
// LeftStick returns where the left stick is, each coordinate from -1 to 1,
|
||||
// right and down positive, with a radial dead zone: 0 near the middle,
|
||||
// then from 0 at Deadzone to 1 at the rim, the same in every direction.
|
||||
func (s State) LeftStick() (x, y float32) { return stick(s.Axes[LeftX], s.Axes[LeftY]) }
|
||||
|
||||
// RightStick returns where the right stick is, as LeftStick.
|
||||
func (s State) RightStick() (x, y float32) { return stick(s.Axes[RightX], s.Axes[RightY]) }
|
||||
|
||||
func stick(x, y float32) (float32, float32) {
|
||||
m := float32(math.Hypot(float64(x), float64(y)))
|
||||
if m < Deadzone {
|
||||
return 0, 0
|
||||
}
|
||||
k := min((m-Deadzone)/(1-Deadzone), 1) / m
|
||||
return x * k, y * k
|
||||
}
|
||||
|
||||
// A Pad is a game controller, from when it connects until it disconnects;
|
||||
// connected again, it is a Pad anew.
|
||||
type Pad struct {
|
||||
dev device
|
||||
name string
|
||||
connected bool
|
||||
}
|
||||
|
||||
// Name returns the pad's name, as its maker gives it.
|
||||
func (p *Pad) Name() string { return p.name }
|
||||
|
||||
// Connected reports whether the pad is still connected.
|
||||
func (p *Pad) Connected() bool {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return p.connected
|
||||
}
|
||||
|
||||
// State reads the pad's controls now; a pad no longer connected reads
|
||||
// nothing pressed.
|
||||
func (p *Pad) State() State {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if !p.connected {
|
||||
return State{}
|
||||
}
|
||||
var s State
|
||||
if !p.dev.read(&s) {
|
||||
p.disconnect()
|
||||
return State{}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (p *Pad) disconnect() {
|
||||
p.connected = false
|
||||
p.dev.close()
|
||||
for i, q := range pads {
|
||||
if q == p {
|
||||
pads = append(pads[:i], pads[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A device is a pad as a platform knows it.
|
||||
type device interface {
|
||||
// key identifies the device while it is connected.
|
||||
key() string
|
||||
name() string
|
||||
// read reads the device's controls, and reports false once it is
|
||||
// gone.
|
||||
read(s *State) bool
|
||||
close()
|
||||
}
|
||||
|
||||
var (
|
||||
mu sync.Mutex
|
||||
pads []*Pad
|
||||
scanned time.Time
|
||||
scanEach = time.Second // how often to look for pads anew
|
||||
)
|
||||
|
||||
// Pads returns the pads connected, in the order they connected. It looks
|
||||
// for pads connected since at most once a second.
|
||||
func Pads() []*Pad {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if now := time.Now(); scanned.IsZero() || now.Sub(scanned) >= scanEach {
|
||||
scanned = now
|
||||
known := map[string]device{}
|
||||
for _, p := range pads {
|
||||
known[p.dev.key()] = p.dev
|
||||
}
|
||||
update(scanDevices(known))
|
||||
}
|
||||
return append([]*Pad(nil), pads...)
|
||||
}
|
||||
|
||||
// scanDevices finds the devices connected, the known ones among them as
|
||||
// they are; tests replace it.
|
||||
var scanDevices = scan
|
||||
|
||||
// update takes the devices a scan found: the pads of devices gone
|
||||
// disconnect, and new devices connect as pads.
|
||||
func update(found []device) {
|
||||
present := map[string]bool{}
|
||||
for _, d := range found {
|
||||
present[d.key()] = true
|
||||
}
|
||||
for _, p := range append([]*Pad(nil), pads...) {
|
||||
if !present[p.dev.key()] {
|
||||
p.disconnect()
|
||||
}
|
||||
}
|
||||
have := map[string]bool{}
|
||||
for _, p := range pads {
|
||||
have[p.dev.key()] = true
|
||||
}
|
||||
for _, d := range found {
|
||||
if !have[d.key()] {
|
||||
have[d.key()] = true
|
||||
pads = append(pads, &Pad{dev: d, name: d.name(), connected: true})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
//go:build !ios
|
||||
|
||||
package gamepad
|
||||
|
||||
import (
|
||||
"runtime"
|
||||
"strconv"
|
||||
"sync"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
"github.com/ebitengine/purego/objc"
|
||||
)
|
||||
|
||||
// macOS reads pads through GameController.framework: GCController's
|
||||
// controllers with an extended gamepad profile, which Xbox, PlayStation,
|
||||
// Switch Pro and MFi controllers have. The framework finds controllers
|
||||
// on the main run loop, which a running MyGo app turns.
|
||||
|
||||
var (
|
||||
gcOnce sync.Once
|
||||
gcOK bool
|
||||
|
||||
poolPush, poolPop uintptr
|
||||
sendFloat func(id objc.ID, sel objc.SEL) float32
|
||||
|
||||
selControllers, selCount, selObjectAt, selExtended, selVendor, selUTF8,
|
||||
selValue, selXAxis, selYAxis, selRetain, selRelease, selResponds objc.SEL
|
||||
buttonSels [ButtonCount]objc.SEL
|
||||
selDpad, selLeftStick, selRightStick, selUp, selDown, selLeft, selRight objc.SEL
|
||||
)
|
||||
|
||||
func loadGC() bool {
|
||||
gcOnce.Do(func() {
|
||||
if _, err := purego.Dlopen("/System/Library/Frameworks/GameController.framework/GameController", purego.RTLD_LAZY|purego.RTLD_GLOBAL); err != nil {
|
||||
return
|
||||
}
|
||||
libobjc, err := purego.Dlopen("/usr/lib/libobjc.A.dylib", purego.RTLD_LAZY|purego.RTLD_GLOBAL)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if poolPush, err = purego.Dlsym(libobjc, "objc_autoreleasePoolPush"); err != nil {
|
||||
return
|
||||
}
|
||||
if poolPop, err = purego.Dlsym(libobjc, "objc_autoreleasePoolPop"); err != nil {
|
||||
return
|
||||
}
|
||||
msgSend, err := purego.Dlsym(libobjc, "objc_msgSend")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
purego.RegisterFunc(&sendFloat, msgSend)
|
||||
sel := objc.RegisterName
|
||||
selControllers, selCount, selObjectAt = sel("controllers"), sel("count"), sel("objectAtIndex:")
|
||||
selExtended, selVendor, selUTF8 = sel("extendedGamepad"), sel("vendorName"), sel("UTF8String")
|
||||
selValue, selXAxis, selYAxis = sel("value"), sel("xAxis"), sel("yAxis")
|
||||
selRetain, selRelease, selResponds = sel("retain"), sel("release"), sel("respondsToSelector:")
|
||||
selDpad, selLeftStick, selRightStick = sel("dpad"), sel("leftThumbstick"), sel("rightThumbstick")
|
||||
selUp, selDown, selLeft, selRight = sel("up"), sel("down"), sel("left"), sel("right")
|
||||
for b, name := range map[Button]string{
|
||||
South: "buttonA", East: "buttonB", West: "buttonX", North: "buttonY",
|
||||
LeftShoulder: "leftShoulder", RightShoulder: "rightShoulder",
|
||||
LeftTrigger: "leftTrigger", RightTrigger: "rightTrigger",
|
||||
Back: "buttonOptions", Start: "buttonMenu", Guide: "buttonHome",
|
||||
LeftStickButton: "leftThumbstickButton", RightStickButton: "rightThumbstickButton",
|
||||
} {
|
||||
buttonSels[b] = sel(name)
|
||||
}
|
||||
gcOK = objc.GetClass("GCController") != 0
|
||||
})
|
||||
return gcOK
|
||||
}
|
||||
|
||||
// withPool runs fn in an autorelease pool, for the objects the framework
|
||||
// returns autoreleased. A pool belongs to its thread: the goroutine stays
|
||||
// on one until the pool is popped.
|
||||
func withPool(fn func()) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
p, _, _ := purego.SyscallN(poolPush)
|
||||
defer purego.SyscallN(poolPop, p)
|
||||
fn()
|
||||
}
|
||||
|
||||
type gcPad struct {
|
||||
ctl objc.ID // retained
|
||||
title string
|
||||
}
|
||||
|
||||
func controllers() []objc.ID {
|
||||
list := objc.ID(objc.GetClass("GCController")).Send(selControllers)
|
||||
if list == 0 {
|
||||
return nil
|
||||
}
|
||||
n := int(objc.Send[uint](list, selCount))
|
||||
ids := make([]objc.ID, n)
|
||||
for i := range n {
|
||||
ids[i] = list.Send(selObjectAt, uint(i))
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
func scan(known map[string]device) []device {
|
||||
if !loadGC() {
|
||||
return nil
|
||||
}
|
||||
var found []device
|
||||
withPool(func() {
|
||||
for _, c := range controllers() {
|
||||
if c.Send(selExtended) == 0 {
|
||||
continue // a remote or a micro gamepad
|
||||
}
|
||||
k := strconv.FormatUint(uint64(c), 16)
|
||||
if d, ok := known[k]; ok {
|
||||
found = append(found, d)
|
||||
continue
|
||||
}
|
||||
d := &gcPad{ctl: c.Send(selRetain)}
|
||||
if v := c.Send(selVendor); v != 0 {
|
||||
d.title = goString(objc.Send[uintptr](v, selUTF8))
|
||||
}
|
||||
found = append(found, d)
|
||||
}
|
||||
})
|
||||
return found
|
||||
}
|
||||
|
||||
func goString(p uintptr) string {
|
||||
if p == 0 {
|
||||
return ""
|
||||
}
|
||||
b := unsafe.Slice((*byte)(*(*unsafe.Pointer)(unsafe.Pointer(&p))), 256)
|
||||
for i, c := range b {
|
||||
if c == 0 {
|
||||
return string(b[:i])
|
||||
}
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func (d *gcPad) key() string { return strconv.FormatUint(uint64(d.ctl), 16) }
|
||||
func (d *gcPad) name() string { return d.title }
|
||||
func (d *gcPad) close() { d.ctl.Send(selRelease) }
|
||||
|
||||
// gcPresent reports whether a controller is still among the controllers;
|
||||
// tests replace it.
|
||||
var gcPresent = func(ctl objc.ID) bool {
|
||||
for _, c := range controllers() {
|
||||
if c == ctl {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func value(input objc.ID) float32 {
|
||||
if input == 0 {
|
||||
return 0
|
||||
}
|
||||
return sendFloat(input, selValue)
|
||||
}
|
||||
|
||||
func (d *gcPad) read(s *State) bool {
|
||||
ok := false
|
||||
withPool(func() {
|
||||
if ok = gcPresent(d.ctl); !ok {
|
||||
return
|
||||
}
|
||||
gp := d.ctl.Send(selExtended)
|
||||
if gp == 0 {
|
||||
ok = false
|
||||
return
|
||||
}
|
||||
for b, sel := range buttonSels {
|
||||
// Older systems have no Home or Options button.
|
||||
if sel != 0 && objc.Send[bool](gp, selResponds, sel) {
|
||||
s.Buttons[b] = value(gp.Send(sel))
|
||||
}
|
||||
}
|
||||
if pad := gp.Send(selDpad); pad != 0 {
|
||||
s.Buttons[Up] = value(pad.Send(selUp))
|
||||
s.Buttons[Down] = value(pad.Send(selDown))
|
||||
s.Buttons[Left] = value(pad.Send(selLeft))
|
||||
s.Buttons[Right] = value(pad.Send(selRight))
|
||||
}
|
||||
// GameController's y axes go up.
|
||||
if st := gp.Send(selLeftStick); st != 0 {
|
||||
s.Axes[LeftX], s.Axes[LeftY] = value(st.Send(selXAxis)), -value(st.Send(selYAxis))
|
||||
}
|
||||
if st := gp.Send(selRightStick); st != 0 {
|
||||
s.Axes[RightX], s.Axes[RightY] = value(st.Send(selXAxis)), -value(st.Send(selYAxis))
|
||||
}
|
||||
})
|
||||
return ok
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//go:build !ios
|
||||
|
||||
package gamepad
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
"github.com/ebitengine/purego/objc"
|
||||
)
|
||||
|
||||
// A controller GameController makes for tests, of the extended gamepad
|
||||
// profile, reads in this package's layout: its y axes turned to go down.
|
||||
func TestGameController(t *testing.T) {
|
||||
if !loadGC() {
|
||||
t.Skip("no GameController.framework")
|
||||
}
|
||||
saved := gcPresent
|
||||
gcPresent = func(objc.ID) bool { return true }
|
||||
defer func() { gcPresent = saved }()
|
||||
var d *gcPad
|
||||
withPool(func() {
|
||||
c := objc.ID(objc.GetClass("GCController")).Send(objc.RegisterName("controllerWithExtendedGamepad"))
|
||||
if c == 0 {
|
||||
return
|
||||
}
|
||||
d = &gcPad{ctl: c.Send(selRetain)}
|
||||
gp := c.Send(selExtended)
|
||||
setValue := objc.RegisterName("setValue:")
|
||||
gp.Send(buttonSels[South]).Send(setValue, float32(1))
|
||||
gp.Send(buttonSels[RightTrigger]).Send(setValue, float32(0.6))
|
||||
setAxes := objc.RegisterName("setValueForXAxis:yAxis:")
|
||||
gp.Send(selLeftStick).Send(setAxes, float32(0.5), float32(0.25))
|
||||
gp.Send(selDpad).Send(setAxes, float32(0), float32(1))
|
||||
})
|
||||
if d == nil {
|
||||
t.Skip("no controllerWithExtendedGamepad")
|
||||
}
|
||||
defer d.close()
|
||||
var s State
|
||||
if !d.read(&s) {
|
||||
t.Fatal("read failed")
|
||||
}
|
||||
if !s.Pressed(South) || s.Pressed(East) || !s.Pressed(Up) || s.Pressed(Down) {
|
||||
t.Errorf("buttons %v", s.Buttons)
|
||||
}
|
||||
if math.Abs(float64(s.Value(RightTrigger))-0.6) > 1e-3 {
|
||||
t.Errorf("right trigger %v", s.Value(RightTrigger))
|
||||
}
|
||||
if math.Abs(float64(s.Axes[LeftX])-0.5) > 1e-3 || math.Abs(float64(s.Axes[LeftY])+0.25) > 1e-3 {
|
||||
t.Errorf("left stick %v, %v: y should go down", s.Axes[LeftX], s.Axes[LeftY])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package gamepad
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"syscall/js"
|
||||
)
|
||||
|
||||
// Browsers report pads through navigator.getGamepads(), each at an index
|
||||
// for as long as it is connected. Those with the "standard" mapping have
|
||||
// their buttons and axes in this package's order; others keep the order
|
||||
// the browser gives, which fits the first buttons and axes of most.
|
||||
|
||||
type jsPad struct {
|
||||
index int
|
||||
id string
|
||||
}
|
||||
|
||||
func pollPads() js.Value {
|
||||
nav := js.Global().Get("navigator")
|
||||
if !nav.Truthy() || !nav.Get("getGamepads").Truthy() {
|
||||
return js.Undefined()
|
||||
}
|
||||
return nav.Call("getGamepads")
|
||||
}
|
||||
|
||||
func scan(known map[string]device) []device {
|
||||
list := pollPads()
|
||||
if !list.Truthy() {
|
||||
return nil
|
||||
}
|
||||
var found []device
|
||||
for i := range list.Length() {
|
||||
g := list.Index(i)
|
||||
if !g.Truthy() || !g.Get("connected").Bool() {
|
||||
continue
|
||||
}
|
||||
d := &jsPad{index: i, id: g.Get("id").String()}
|
||||
if k, ok := known[d.key()]; ok {
|
||||
found = append(found, k)
|
||||
continue
|
||||
}
|
||||
found = append(found, d)
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
func (d *jsPad) key() string { return strconv.Itoa(d.index) + "\x00" + d.id }
|
||||
func (d *jsPad) name() string { return d.id }
|
||||
func (d *jsPad) close() {}
|
||||
|
||||
func (d *jsPad) read(s *State) bool {
|
||||
list := pollPads()
|
||||
if !list.Truthy() || d.index >= list.Length() {
|
||||
return false
|
||||
}
|
||||
g := list.Index(d.index)
|
||||
if !g.Truthy() || !g.Get("connected").Bool() || g.Get("id").String() != d.id {
|
||||
return false
|
||||
}
|
||||
buttons := g.Get("buttons")
|
||||
for i := range min(buttons.Length(), int(ButtonCount)) {
|
||||
b := buttons.Index(i)
|
||||
s.Buttons[i] = float32(b.Get("value").Float())
|
||||
if s.Buttons[i] == 0 && b.Get("pressed").Bool() {
|
||||
s.Buttons[i] = 1 // a browser that reports only pressed
|
||||
}
|
||||
}
|
||||
axes := g.Get("axes")
|
||||
for i := range min(axes.Length(), int(AxisCount)) {
|
||||
s.Axes[i] = float32(axes.Index(i).Float())
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
//go:build linux && !android && (amd64 || arm64) && !android
|
||||
|
||||
package gamepad
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// Linux reads pads from evdev, /dev/input/event*, which systemd-logind
|
||||
// lets the user at the seat read. The kernel's drivers report gamepads in
|
||||
// one layout (Documentation/input/gamepad.rst): BTN_SOUTH and the rest by
|
||||
// place, sticks on ABS_X/Y and ABS_RX/RY, triggers on ABS_Z/RZ, the
|
||||
// d-pad on a hat or buttons. Xbox controllers (xpad, and Steam's virtual
|
||||
// pad) are the exception that predates it: they report X as BTN_X, the
|
||||
// code of BTN_NORTH, and Y as BTN_Y, that of BTN_WEST.
|
||||
|
||||
// Event types and codes.
|
||||
const (
|
||||
evKey = 0x01
|
||||
evAbs = 0x03
|
||||
|
||||
btnSouth = 0x130
|
||||
btnEast = 0x131
|
||||
btnNorth = 0x133 // also BTN_X
|
||||
btnWest = 0x134 // also BTN_Y
|
||||
btnTL = 0x136
|
||||
btnTR = 0x137
|
||||
btnTL2 = 0x138
|
||||
btnTR2 = 0x139
|
||||
btnSelect = 0x13a
|
||||
btnStart = 0x13b
|
||||
btnMode = 0x13c
|
||||
btnThumbL = 0x13d
|
||||
btnThumbR = 0x13e
|
||||
btnUp = 0x220
|
||||
btnDown = 0x221
|
||||
btnLeft = 0x222
|
||||
btnRight = 0x223
|
||||
|
||||
absX = 0x00
|
||||
absY = 0x01
|
||||
absZ = 0x02
|
||||
absRX = 0x03
|
||||
absRY = 0x04
|
||||
absRZ = 0x05
|
||||
absHat0X = 0x10
|
||||
absHat0Y = 0x11
|
||||
absMax = 0x3f
|
||||
keyMax = 0x2ff
|
||||
)
|
||||
|
||||
// ioctl requests of evdev: _IOC(dir, 'E', nr, size).
|
||||
func ioc(dir, nr, size uintptr) uintptr { return dir<<30 | size<<16 | 'E'<<8 | nr }
|
||||
|
||||
const iocRead = 2
|
||||
|
||||
func eviocgname(n uintptr) uintptr { return ioc(iocRead, 0x06, n) }
|
||||
func eviocgbit(ev, n uintptr) uintptr { return ioc(iocRead, 0x20+ev, n) }
|
||||
func eviocgabs(abs uintptr) uintptr { return ioc(iocRead, 0x40+abs, unsafe.Sizeof(absInfo{})) }
|
||||
func eviocgkey(n uintptr) uintptr { return ioc(iocRead, 0x18, n) }
|
||||
func eviocgid() uintptr { return ioc(iocRead, 0x02, unsafe.Sizeof(inputID{})) }
|
||||
func ioctl(fd int, req uintptr, p unsafe.Pointer) bool {
|
||||
_, _, e := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), req, uintptr(p))
|
||||
return e == 0
|
||||
}
|
||||
|
||||
type absInfo struct{ value, minimum, maximum, fuzz, flat, resolution int32 }
|
||||
|
||||
type inputID struct{ bustype, vendor, product, version uint16 }
|
||||
|
||||
type evdevPad struct {
|
||||
path string
|
||||
fd int
|
||||
title string
|
||||
xbox bool // BTN_X and BTN_Y are X and Y, west and north
|
||||
// rightOnZ: a pad of no ABS_RX has its right stick on ABS_Z/RZ, and
|
||||
// triggers only as buttons.
|
||||
rightOnZ bool
|
||||
abs [absMax + 1]absInfo
|
||||
hasAbs [absMax + 1]bool
|
||||
keys [keyMax + 1]bool
|
||||
axes [absMax + 1]int32
|
||||
buf []byte
|
||||
}
|
||||
|
||||
func scan(known map[string]device) []device {
|
||||
paths, _ := filepath.Glob("/dev/input/event*")
|
||||
var found []device
|
||||
for _, p := range paths {
|
||||
if k, ok := known[p]; ok {
|
||||
found = append(found, k)
|
||||
continue
|
||||
}
|
||||
if d := openEvdev(p); d != nil {
|
||||
found = append(found, d)
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
func bit(b []byte, i int) bool { return i/8 < len(b) && b[i/8]&(1<<(i%8)) != 0 }
|
||||
|
||||
// openEvdev opens the device at path if it is a gamepad.
|
||||
func openEvdev(path string) *evdevPad {
|
||||
fd, err := syscall.Open(path, syscall.O_RDONLY|syscall.O_NONBLOCK|syscall.O_CLOEXEC, 0)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
keys := make([]byte, keyMax/8+1)
|
||||
if !ioctl(fd, eviocgbit(evKey, uintptr(len(keys))), unsafe.Pointer(&keys[0])) || !bit(keys, btnSouth) {
|
||||
syscall.Close(fd)
|
||||
return nil
|
||||
}
|
||||
d := &evdevPad{path: path, fd: fd, buf: make([]byte, 24*64)}
|
||||
name := make([]byte, 256)
|
||||
if ioctl(fd, eviocgname(uintptr(len(name))), unsafe.Pointer(&name[0])) {
|
||||
d.title = strings.TrimRight(string(name), "\x00")
|
||||
}
|
||||
var id inputID
|
||||
ioctl(fd, eviocgid(), unsafe.Pointer(&id))
|
||||
d.xbox = id.vendor == 0x045e || id.vendor == 0x28de || driver(path) == "xpad"
|
||||
abs := make([]byte, absMax/8+1)
|
||||
ioctl(fd, eviocgbit(evAbs, uintptr(len(abs))), unsafe.Pointer(&abs[0]))
|
||||
for a := range absMax + 1 {
|
||||
if bit(abs, a) && ioctl(fd, eviocgabs(uintptr(a)), unsafe.Pointer(&d.abs[a])) {
|
||||
d.hasAbs[a] = true
|
||||
d.axes[a] = d.abs[a].value
|
||||
}
|
||||
}
|
||||
d.rightOnZ = !d.hasAbs[absRX] && d.hasAbs[absZ]
|
||||
state := make([]byte, keyMax/8+1)
|
||||
if ioctl(fd, eviocgkey(uintptr(len(state))), unsafe.Pointer(&state[0])) {
|
||||
for k := range keyMax + 1 {
|
||||
d.keys[k] = bit(state, k)
|
||||
}
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// driver returns the name of the kernel driver of an evdev device.
|
||||
func driver(path string) string {
|
||||
link, err := os.Readlink("/sys/class/input/" + filepath.Base(path) + "/device/device/driver")
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return filepath.Base(link)
|
||||
}
|
||||
|
||||
func (d *evdevPad) key() string { return d.path }
|
||||
func (d *evdevPad) name() string { return d.title }
|
||||
func (d *evdevPad) close() { syscall.Close(d.fd) }
|
||||
|
||||
// drain reads the events waiting, and reports false once the device is
|
||||
// gone.
|
||||
func (d *evdevPad) drain() bool {
|
||||
for {
|
||||
n, err := syscall.Read(d.fd, d.buf)
|
||||
if err == syscall.EAGAIN || err == syscall.EINTR {
|
||||
return true
|
||||
}
|
||||
if err != nil || n == 0 {
|
||||
return false // ENODEV: unplugged
|
||||
}
|
||||
for i := 0; i+24 <= n; i += 24 {
|
||||
e := d.buf[i:]
|
||||
typ := binary.LittleEndian.Uint16(e[16:])
|
||||
code := binary.LittleEndian.Uint16(e[18:])
|
||||
value := int32(binary.LittleEndian.Uint32(e[20:]))
|
||||
switch {
|
||||
case typ == evKey && int(code) <= keyMax:
|
||||
d.keys[code] = value != 0
|
||||
case typ == evAbs && int(code) <= absMax:
|
||||
d.axes[code] = value
|
||||
}
|
||||
}
|
||||
if n < len(d.buf) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// norm maps axis a to -1..1, or 0..1 when half.
|
||||
func (d *evdevPad) norm(a int, half bool) float32 {
|
||||
if !d.hasAbs[a] {
|
||||
return 0
|
||||
}
|
||||
lo, hi := float32(d.abs[a].minimum), float32(d.abs[a].maximum)
|
||||
if hi <= lo {
|
||||
return 0
|
||||
}
|
||||
t := (float32(d.axes[a]) - lo) / (hi - lo)
|
||||
if half {
|
||||
return min(max(t, 0), 1)
|
||||
}
|
||||
return min(max(t*2-1, -1), 1)
|
||||
}
|
||||
|
||||
func (d *evdevPad) read(s *State) bool {
|
||||
if !d.drain() {
|
||||
return false
|
||||
}
|
||||
press := func(b Button, code int) {
|
||||
if d.keys[code] {
|
||||
s.Buttons[b] = 1
|
||||
}
|
||||
}
|
||||
press(South, btnSouth)
|
||||
press(East, btnEast)
|
||||
if d.xbox {
|
||||
press(West, btnNorth)
|
||||
press(North, btnWest)
|
||||
} else {
|
||||
press(North, btnNorth)
|
||||
press(West, btnWest)
|
||||
}
|
||||
press(LeftShoulder, btnTL)
|
||||
press(RightShoulder, btnTR)
|
||||
press(Back, btnSelect)
|
||||
press(Start, btnStart)
|
||||
press(Guide, btnMode)
|
||||
press(LeftStickButton, btnThumbL)
|
||||
press(RightStickButton, btnThumbR)
|
||||
press(Up, btnUp)
|
||||
press(Down, btnDown)
|
||||
press(Left, btnLeft)
|
||||
press(Right, btnRight)
|
||||
if d.hasAbs[absHat0X] {
|
||||
if v := d.axes[absHat0X]; v < 0 {
|
||||
s.Buttons[Left] = 1
|
||||
} else if v > 0 {
|
||||
s.Buttons[Right] = 1
|
||||
}
|
||||
if v := d.axes[absHat0Y]; v < 0 {
|
||||
s.Buttons[Up] = 1
|
||||
} else if v > 0 {
|
||||
s.Buttons[Down] = 1
|
||||
}
|
||||
}
|
||||
s.Axes[LeftX], s.Axes[LeftY] = d.norm(absX, false), d.norm(absY, false)
|
||||
if d.rightOnZ {
|
||||
s.Axes[RightX], s.Axes[RightY] = d.norm(absZ, false), d.norm(absRZ, false)
|
||||
} else {
|
||||
s.Axes[RightX], s.Axes[RightY] = d.norm(absRX, false), d.norm(absRY, false)
|
||||
s.Buttons[LeftTrigger] = d.norm(absZ, true)
|
||||
s.Buttons[RightTrigger] = d.norm(absRZ, true)
|
||||
}
|
||||
press(LeftTrigger, btnTL2)
|
||||
press(RightTrigger, btnTR2)
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
//go:build linux && !android && (amd64 || arm64) && !android
|
||||
|
||||
package gamepad
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"os"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/wait"
|
||||
)
|
||||
|
||||
// uinput makes virtual input devices.
|
||||
const (
|
||||
uiDevCreate = 1<<0 | 'U'<<8 | 1 // _IO('U', 1)
|
||||
uiDevDestroy = 'U'<<8 | 2
|
||||
uiSetEvBit = 1<<30 | 4<<16 | 'U'<<8 | 100
|
||||
uiSetKeyBit = 1<<30 | 4<<16 | 'U'<<8 | 101
|
||||
uiSetAbsBit = 1<<30 | 4<<16 | 'U'<<8 | 103
|
||||
)
|
||||
|
||||
type uinputSetup struct {
|
||||
id inputID
|
||||
name [80]byte
|
||||
ff uint32
|
||||
}
|
||||
|
||||
type uinputAbsSetup struct {
|
||||
code uint16
|
||||
_ uint16
|
||||
info absInfo
|
||||
}
|
||||
|
||||
func uiDevSetup() uintptr { return 1<<30 | unsafe.Sizeof(uinputSetup{})<<16 | 'U'<<8 | 3 }
|
||||
func uiAbsSetup() uintptr { return 1<<30 | unsafe.Sizeof(uinputAbsSetup{})<<16 | 'U'<<8 | 4 }
|
||||
|
||||
// A virtual pad, made with uinput, reads as the kernel's drivers report
|
||||
// pads: its buttons by place, sticks, triggers and hat. It needs
|
||||
// /dev/uinput and /dev/input, as in the Linux test container
|
||||
// (MYGO_UINPUT=1).
|
||||
func TestEvdev(t *testing.T) {
|
||||
if os.Getenv("MYGO_UINPUT") == "" {
|
||||
t.Skip("MYGO_UINPUT not set")
|
||||
}
|
||||
// A DualSense reports its left button, Square, as BTN_WEST; an Xbox
|
||||
// controller its left one, X, as BTN_X, BTN_NORTH's code.
|
||||
t.Run("PlayStation", func(t *testing.T) { testEvdev(t, 0x054c, btnWest) })
|
||||
t.Run("Xbox", func(t *testing.T) { testEvdev(t, 0x045e, btnNorth) })
|
||||
}
|
||||
|
||||
func testEvdev(t *testing.T, vendor uint16, west uint16) {
|
||||
fd, err := syscall.Open("/dev/uinput", syscall.O_WRONLY|syscall.O_NONBLOCK, 0)
|
||||
if err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
defer syscall.Close(fd)
|
||||
set := func(req uintptr, v int) {
|
||||
if _, _, e := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), req, uintptr(v)); e != 0 {
|
||||
t.Fatalf("ioctl %#x %d: %v", req, v, e)
|
||||
}
|
||||
}
|
||||
set(uiSetEvBit, evKey)
|
||||
set(uiSetEvBit, evAbs)
|
||||
for _, k := range []int{btnSouth, btnEast, btnNorth, btnWest, btnTL, btnTR, btnSelect, btnStart, btnMode, btnThumbL, btnThumbR} {
|
||||
set(uiSetKeyBit, k)
|
||||
}
|
||||
axes := map[uint16]absInfo{
|
||||
absX: {minimum: -32768, maximum: 32767}, absY: {minimum: -32768, maximum: 32767},
|
||||
absRX: {minimum: -32768, maximum: 32767}, absRY: {minimum: -32768, maximum: 32767},
|
||||
absZ: {maximum: 255}, absRZ: {maximum: 255},
|
||||
absHat0X: {minimum: -1, maximum: 1}, absHat0Y: {minimum: -1, maximum: 1},
|
||||
}
|
||||
for code, info := range axes {
|
||||
set(uiSetAbsBit, int(code))
|
||||
s := uinputAbsSetup{code: code, info: info}
|
||||
if !ioctl(fd, uiAbsSetup(), unsafe.Pointer(&s)) {
|
||||
t.Fatal("UI_ABS_SETUP")
|
||||
}
|
||||
}
|
||||
setup := uinputSetup{id: inputID{bustype: 3, vendor: vendor, product: 0x0ce6}}
|
||||
copy(setup.name[:], "Virtual Pad")
|
||||
if !ioctl(fd, uiDevSetup(), unsafe.Pointer(&setup)) {
|
||||
t.Fatal("UI_DEV_SETUP")
|
||||
}
|
||||
set(uiDevCreate, 0)
|
||||
// Destroyed by the test, unless it fails first.
|
||||
defer syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), uiDevDestroy, 0)
|
||||
|
||||
var pad *Pad
|
||||
wait.Until(t, "the virtual pad", func() bool {
|
||||
scanned = time.Time{}
|
||||
for _, p := range Pads() {
|
||||
if p.Name() == "Virtual Pad" {
|
||||
pad = p
|
||||
}
|
||||
}
|
||||
return pad != nil
|
||||
})
|
||||
emit := func(typ, code uint16, value int32) {
|
||||
var e [24]byte
|
||||
binary.LittleEndian.PutUint16(e[16:], typ)
|
||||
binary.LittleEndian.PutUint16(e[18:], code)
|
||||
binary.LittleEndian.PutUint32(e[20:], uint32(value))
|
||||
if _, err := syscall.Write(fd, e[:]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
emit(evKey, btnSouth, 1)
|
||||
emit(evKey, west, 1)
|
||||
emit(evAbs, absX, 32767)
|
||||
emit(evAbs, absRY, -32768)
|
||||
emit(evAbs, absRZ, 255)
|
||||
emit(evAbs, absHat0Y, -1)
|
||||
emit(0, 0, 0) // SYN_REPORT
|
||||
// State drains what the kernel passed on so far: wait until it has.
|
||||
wait.Until(t, "the report read", func() bool { return pad.State().Axes[LeftX] >= 0.99 })
|
||||
s := pad.State()
|
||||
for _, b := range []Button{South, West, RightTrigger, Up} {
|
||||
if !s.Pressed(b) {
|
||||
t.Errorf("button %d not pressed: %v", b, s.Buttons)
|
||||
}
|
||||
}
|
||||
for _, b := range []Button{East, North, LeftTrigger, Down} {
|
||||
if s.Pressed(b) {
|
||||
t.Errorf("button %d pressed: %v", b, s.Buttons)
|
||||
}
|
||||
}
|
||||
if s.Axes[LeftX] < 0.99 || s.Axes[RightY] > -0.99 || s.Axes[LeftY] < -0.01 || s.Axes[LeftY] > 0.01 {
|
||||
t.Errorf("axes %v", s.Axes)
|
||||
}
|
||||
emit(evKey, btnSouth, 0)
|
||||
emit(0, 0, 0)
|
||||
wait.Until(t, "South released", func() bool { return !pad.State().Pressed(South) })
|
||||
set(uiDevDestroy, 0)
|
||||
wait.Until(t, "the pad disconnected once destroyed", func() bool { pad.State(); return !pad.Connected() })
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
//go:build !(darwin && !ios) && !(linux && !android && (amd64 || arm64)) && !(windows && (amd64 || arm64)) && !js
|
||||
|
||||
package gamepad
|
||||
|
||||
func scan(known map[string]device) []device { return nil }
|
||||
@@ -0,0 +1,96 @@
|
||||
package gamepad
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// fakeDevice is a pad whose state a test sets.
|
||||
type fakeDevice struct {
|
||||
id string
|
||||
state State
|
||||
gone bool
|
||||
closed bool
|
||||
}
|
||||
|
||||
func (d *fakeDevice) key() string { return d.id }
|
||||
func (d *fakeDevice) name() string { return "Fake " + d.id }
|
||||
func (d *fakeDevice) close() { d.closed = true }
|
||||
func (d *fakeDevice) read(s *State) bool {
|
||||
*s = d.state
|
||||
return !d.gone
|
||||
}
|
||||
|
||||
// withDevices has scans find devs, which a test changes.
|
||||
func withDevices(t *testing.T, devs *[]device) {
|
||||
t.Helper()
|
||||
saved, savedEach := scanDevices, scanEach
|
||||
scanDevices = func(known map[string]device) []device { return *devs }
|
||||
scanEach = 0
|
||||
mu.Lock()
|
||||
pads, scanned = nil, scanned.AddDate(-1, 0, 0)
|
||||
mu.Unlock()
|
||||
t.Cleanup(func() {
|
||||
scanDevices, scanEach = saved, savedEach
|
||||
mu.Lock()
|
||||
pads = nil
|
||||
mu.Unlock()
|
||||
})
|
||||
}
|
||||
|
||||
func TestPadsConnectAndDisconnect(t *testing.T) {
|
||||
a, b := &fakeDevice{id: "a"}, &fakeDevice{id: "b"}
|
||||
devs := []device{a}
|
||||
withDevices(t, &devs)
|
||||
ps := Pads()
|
||||
if len(ps) != 1 || ps[0].Name() != "Fake a" || !ps[0].Connected() {
|
||||
t.Fatalf("pads %v", ps)
|
||||
}
|
||||
first := ps[0]
|
||||
devs = []device{b, a}
|
||||
ps = Pads()
|
||||
if len(ps) != 2 || ps[0] != first || ps[1].Name() != "Fake b" {
|
||||
t.Fatalf("pads in connecting order: %v", ps)
|
||||
}
|
||||
// Unplugged between scans: reading finds it gone.
|
||||
a.gone = true
|
||||
a.state.Buttons[South] = 1
|
||||
if first.State().Pressed(South) || first.Connected() || !a.closed {
|
||||
t.Error("a pad gone still reads, or is not closed")
|
||||
}
|
||||
// Gone from a scan.
|
||||
devs = nil
|
||||
if ps = Pads(); len(ps) != 0 {
|
||||
t.Errorf("pads after unplugging: %v", ps)
|
||||
}
|
||||
}
|
||||
|
||||
func TestState(t *testing.T) {
|
||||
var last, s State
|
||||
s.Buttons[South] = 1
|
||||
s.Buttons[LeftTrigger] = 0.2
|
||||
s.Buttons[RightTrigger] = 0.3
|
||||
if !s.Pressed(South) || s.Pressed(LeftTrigger) || !s.Pressed(RightTrigger) {
|
||||
t.Error("Pressed")
|
||||
}
|
||||
if !s.JustPressed(last, South) || s.JustPressed(s, South) || !last.JustReleased(s, South) {
|
||||
t.Error("JustPressed, JustReleased")
|
||||
}
|
||||
// Within the dead zone, nothing; at the rim, all the way, in every
|
||||
// direction alike.
|
||||
s.Axes[LeftX], s.Axes[LeftY] = 0.1, 0.05
|
||||
if x, y := s.LeftStick(); x != 0 || y != 0 {
|
||||
t.Errorf("rest = %v, %v", x, y)
|
||||
}
|
||||
s.Axes[LeftX], s.Axes[LeftY] = 0.7071, 0.7071
|
||||
if x, y := s.LeftStick(); math.Abs(math.Hypot(float64(x), float64(y))-1) > 1e-3 {
|
||||
t.Errorf("diagonal rim = %v, %v", x, y)
|
||||
}
|
||||
s.Axes[RightX] = -(Deadzone + (1-Deadzone)/2)
|
||||
if x, _ := s.RightStick(); math.Abs(float64(x)+0.5) > 1e-4 {
|
||||
t.Errorf("half way past the dead zone = %v", x)
|
||||
}
|
||||
if s.Value(ButtonCount) != 0 || s.Axis(AxisCount) != 0 {
|
||||
t.Error("out of range")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
//go:build windows && (amd64 || arm64)
|
||||
|
||||
package gamepad
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"sync"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// Windows reads pads through XInput, which has four slots, for Xbox
|
||||
// controllers and those that act as one. XInputGetStateEx, exported by
|
||||
// ordinal 100, reads the Guide button too.
|
||||
|
||||
type xinputGamepad struct {
|
||||
buttons uint16
|
||||
leftTrigger uint8
|
||||
rightTrigger uint8
|
||||
thumbLX int16
|
||||
thumbLY int16
|
||||
thumbRX int16
|
||||
thumbRY int16
|
||||
}
|
||||
|
||||
type xinputState struct {
|
||||
packet uint32
|
||||
gamepad xinputGamepad
|
||||
}
|
||||
|
||||
const (
|
||||
errorSuccess = 0
|
||||
xinputSlots = 4
|
||||
xinputDpadUp = 0x0001
|
||||
xinputDpadDown = 0x0002
|
||||
xinputDpadLeft = 0x0004
|
||||
xinputDpadRight = 0x0008
|
||||
xinputStart = 0x0010
|
||||
xinputBack = 0x0020
|
||||
xinputLeftThumb = 0x0040
|
||||
xinputRightThumb = 0x0080
|
||||
xinputLeftShoulder = 0x0100
|
||||
xinputRightShoulder = 0x0200
|
||||
xinputGuide = 0x0400
|
||||
xinputA = 0x1000
|
||||
xinputB = 0x2000
|
||||
xinputX = 0x4000
|
||||
xinputY = 0x8000
|
||||
)
|
||||
|
||||
var (
|
||||
xinputOnce sync.Once
|
||||
xinputGetState uintptr
|
||||
)
|
||||
|
||||
func loadXInput() {
|
||||
xinputOnce.Do(func() {
|
||||
kernel32 := syscall.NewLazyDLL("kernel32.dll")
|
||||
getProc := kernel32.NewProc("GetProcAddress")
|
||||
for _, name := range []string{"xinput1_4.dll", "xinput1_3.dll", "xinput9_1_0.dll"} {
|
||||
lib, err := syscall.LoadLibrary(name)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
// XInputGetStateEx, by ordinal, where there is one.
|
||||
if p, _, _ := getProc.Call(uintptr(lib), 100); p != 0 {
|
||||
xinputGetState = p
|
||||
return
|
||||
}
|
||||
if p, err := syscall.GetProcAddress(lib, "XInputGetState"); err == nil {
|
||||
xinputGetState = p
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func getState(slot int, s *xinputState) bool {
|
||||
r, _, _ := syscall.SyscallN(xinputGetState, uintptr(slot), uintptr(unsafe.Pointer(s)))
|
||||
return r == errorSuccess
|
||||
}
|
||||
|
||||
type xinputPad struct{ slot int }
|
||||
|
||||
func scan(known map[string]device) []device {
|
||||
loadXInput()
|
||||
if xinputGetState == 0 {
|
||||
return nil
|
||||
}
|
||||
var found []device
|
||||
for slot := range xinputSlots {
|
||||
d := &xinputPad{slot}
|
||||
if k, ok := known[d.key()]; ok {
|
||||
// Read as it is used; a slot that empties disconnects there.
|
||||
found = append(found, k)
|
||||
continue
|
||||
}
|
||||
// Asking an empty slot is slow, which is why scans are rare.
|
||||
var st xinputState
|
||||
if getState(slot, &st) {
|
||||
found = append(found, d)
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
func (d *xinputPad) key() string { return "xinput" + strconv.Itoa(d.slot) }
|
||||
func (d *xinputPad) name() string { return "Xbox Controller " + strconv.Itoa(d.slot+1) }
|
||||
func (d *xinputPad) close() {}
|
||||
|
||||
func (d *xinputPad) read(s *State) bool {
|
||||
var st xinputState
|
||||
if !getState(d.slot, &st) {
|
||||
return false
|
||||
}
|
||||
g := st.gamepad
|
||||
bits := [...]struct {
|
||||
b Button
|
||||
mask uint16
|
||||
}{
|
||||
{South, xinputA}, {East, xinputB}, {West, xinputX}, {North, xinputY},
|
||||
{LeftShoulder, xinputLeftShoulder}, {RightShoulder, xinputRightShoulder},
|
||||
{Back, xinputBack}, {Start, xinputStart},
|
||||
{LeftStickButton, xinputLeftThumb}, {RightStickButton, xinputRightThumb},
|
||||
{Up, xinputDpadUp}, {Down, xinputDpadDown}, {Left, xinputDpadLeft}, {Right, xinputDpadRight},
|
||||
{Guide, xinputGuide},
|
||||
}
|
||||
for _, b := range bits {
|
||||
if g.buttons&b.mask != 0 {
|
||||
s.Buttons[b.b] = 1
|
||||
}
|
||||
}
|
||||
s.Buttons[LeftTrigger] = float32(g.leftTrigger) / 255
|
||||
s.Buttons[RightTrigger] = float32(g.rightTrigger) / 255
|
||||
// XInput's y axes go up.
|
||||
s.Axes[LeftX] = thumb(g.thumbLX)
|
||||
s.Axes[LeftY] = -thumb(g.thumbLY)
|
||||
s.Axes[RightX] = thumb(g.thumbRX)
|
||||
s.Axes[RightY] = -thumb(g.thumbRY)
|
||||
return true
|
||||
}
|
||||
|
||||
func thumb(v int16) float32 { return max(float32(v)/32767, -1) }
|
||||
Reference in new issue
Block a user