Add VITURE XR controls, head tracking, and SteamVR (#732)

* Add VITURE glasses support: hardware control, 3D, head tracking

Glasses get their own controller over the MCU (permission, 120 Hz default, brightness, volume, sunblock, 2D/3D) and the game moves onto them when plugged in. The IMU drives Cardboard head tracking and the SteamVR driver. 3D falls back to one eye's view on phones that can't send the 3840x1080 signal. Options open from a glasses button in game and on the Steam page.

* Drop the glasses settings like Steam's: Play-style button, Settings lip, tabs

* Hang the glasses Settings lip over the top of the button

* Space glasses MCU commands so the IMU rate sticks, fit fixed resolutions to the glasses

* Keep Steam alive with SteamVR registered, run SteamVR at the glasses' rate, keep the glasses lip on top

* Fit VR games on the glasses: full view, seated origin at the head, pad hands reach with the d-pad

* Let the pad hands reach a metre out so buttons with deep colliders press

* Show every VR frame in order at 120 fps: wait for SteamVR's GPU work, present only finished copies, skip the grace on idle shared counters

* Glasses: SteamVR starts and stops with them, closer view with a field of view setting, Recenter on the pad

* Glasses: SteamVR field of view defaults to 90°

* VR pad hands: sticks move and aim the hands, left stick click switches the sticks to the game, d-pad pulls a held hand

* Glasses: Play SteamVR beside the glasses button instead of starting SteamVR with them, pad hands drawn as Index controllers and off while other VR controllers are connected, glasses sheet tabs sized like Steam's

* Track glasses mode, refresh-aware glasses window, align Play SteamVR with Play Steam

* Fix 3D on the glasses: full-res SteamVR presenter, revert VR 3D at session end, coalesce vsync ticks, no session restart after end

* Address review: glasses output after installs and session end, VR revert retry, display fallback, presenter swapchain retry, agent hex checks, drawer bumpers, glasses translations, docs

* Harden VITURE stereo negotiation and output refresh tracking

* Localize stereo recovery feedback and record Astra reconnect tests

* Improve test failure diagnostics and refresh Astra firmware findings

* Handle VITURE docks separately and reject truncated USB frames

* Glasses: remember a 3D fallback per model, docks as display only, VR timing fixes

- A 3D attempt that ends at the 640x480 fallback is remembered for that glasses
  model, so Play SteamVR no longer blacks out the glasses after every restart;
  Retry clears it and "3D for VR games" stays reachable
- A VITURE Mobile Dock on its own no longer counts as glasses; through a dock
  Play SteamVR is hidden and the sheet shows the output and why there is no control
- HDR is probed on the glasses when the session starts there
- Glasses frames with a mismatched checksum are marked in the status frame log
- SteamVR layer and driver vblank counters stay monotonic across refresh changes;
  one-eye render scale applies from activation and on mono/3D switches
- Compositor binds announce the refresh clients were last told; the presenter
  retries a failed first swapchain
- Dead strings and helpers removed; docs updated

* Glasses: drop USB frames with a bad checksum

* Glasses: count frames dropped for a bad checksum

* Feat/viture xr (#907)

* Add RayNeo Air and GT support to the XR glasses pipeline

* Add RayNeo Air and GT support to the XR glasses pipeline

* Checkpoint glasses tracking, calibration, and SteamVR launch integration

* Checkpoint glasses tracking, calibration, and SteamVR launch integration

* Add XREAL 1S support and correct GT and Pro 2 tracking

* Add XREAL 1S support and correct GT and Pro 2 tracking

* Fix mirrored glasses tracking and recover SteamVR after device loss

* Fix mirrored glasses tracking and recover SteamVR after device loss

* Document confirmed XREAL 1S brightness control

* Document confirmed XREAL 1S brightness control

* Fix SteamVR glasses defaults and rendering controls

* Fix SteamVR glasses defaults and rendering controls

* chore: keep only the 3 newest session log folders (#852)

* chore: add agent comment rules (#748)

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>

* Fix SteamVR polling, VITURE checksums, and fence tracking

Keep manual SteamVR launches polled, discard corrupt VITURE packets, and retire Vulkan fences out of order without blocking submissions at a fixed capacity. Preserve the contiguous completion watermark used by the presenter.

Fix optional Windows launcher configuration and audited helper staging. Add Android, Windows, and native tracker regression coverage.

* Fix SteamVR polling, VITURE checksums, and fence tracking

Keep manual SteamVR launches polled, discard corrupt VITURE packets, and retire Vulkan fences out of order without blocking submissions at a fixed capacity. Preserve the contiguous completion watermark used by the presenter.

Fix optional Windows launcher configuration and audited helper staging. Add Android, Windows, and native tracker regression coverage.

* fix: wireless ADB page names the child-process switch the way Android shows it (#848)

* l10n: refresh stale and untranslated strings in es, fr, ko, ru (#850)

* l10n: refresh stale and untranslated strings in es, fr, ko, ru

- mode_added_art_hint: now mentions Steam then SteamGridDB (all four locales).
- wincomp_needs_installer / wincomp_installers_note: es and ko still described
  the old "coming soon" behaviour; align with the current English text.
- summary_remove_game: was still English in all four locales.

Machine-assisted translation; native-speaker review is welcome.

* l10n(es): say registro, not grabación, for the missing installer record

---------

Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com>

* fix: a failed cloud save recovery no longer ends the app (#846)

The cloud-recovery thread started at every app start had nothing to
catch an error, so one went to CrashHandler, which halts the process
with status 2. In unit tests the thread can outlive the test that
started it, fail on the torn-down preferences, and take the whole test
run down. The error is now logged and the thread ends.

Co-authored-by: Kirk <12691869+KirkPatrickJunsay@users.noreply.github.com>

* fix: an interrupted Linux runtime download resumes instead of starting again (#847)

* fix: an interrupted Linux runtime download resumes instead of starting again

installOnce() asked the downloader to resume but always deleted the archive in its finally block, so the next attempt began at zero. The archive is now named after the release version and checksum, a failed download keeps what it fetched, and archives of other releases (and the old fixed name) are removed. A checksum or extraction failure still deletes the file.

* test: Downloader resumes a cut-off download from the bytes it kept

Starts a socket server that promises the whole file, hangs up part way and then answers a Range request, and checks that the second downloadFile call resumes with the right offset and ends with identical bytes.

* fix: a resumed download discards a 206 that does not start where the kept bytes end

Downloader appended every 206 response to the partial file without
looking at Content-Range. A server or proxy that answers a Range request
with a different offset would leave a corrupt file. Check that the range
starts at the kept length; otherwise delete the partial file and start
again without a Range header.

Adds a test with a server that answers the Range request from offset 0.

---------

Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com>

* l10n: German, French, Spanish, Italian, Portuguese and Russian for the zRAM, reset-settings and store free-space strings (#849)

* l10n: German, French, Spanish, Italian, Portuguese and Russian for the zRAM, reset-settings and store free-space strings

Adds the strings values-de, values-it and values-pt were missing (14 each) and the six that values-fr, values-es and values-ru were missing. Machine-assisted drafts that follow each file's existing register and terms; native review is welcome.

* l10n: correct missing active swap translations

---------

Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com>
Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com>

* fix: droiddeckctl reaches variant-package builds (recover #842) (#854)

fix: droiddeckctl reaches builds shipped under a variant package

The provider authority and the start Activity's component were fixed to
com.droiddeck.launcher, so droiddeckctl could not talk to the antutu,
ludashi or pubg builds from tools/release/variants.txt. DROIDDECK_PACKAGE
now picks the package; the Activity's class name stays the same in every
variant.

Co-authored-by: angelrenefm <17342133+angelrenefm@users.noreply.github.com>

* feat: droiddeckctl reports on-screen pacing (recover #843) (#855)

feat: droiddeckctl pacing reports the frames that reached the screen

Reads SurfaceFlinger's timestats for the game's layer (or the session's
SurfaceView) over a capture: frames on screen, fps on screen, the
present-to-present histogram and how many intervals were off the usual
cadence. Records split by a refresh-rate change are summed. A game's own fps
counter counts frames handed over, so it can't show dropped or doubled frames.

Co-authored-by: angelrenefm <17342133+angelrenefm@users.noreply.github.com>

* fix: Steam can restart more than twice in a session (#754)

* fix: Steam can restart more than twice in a session

Every exit 42 counted toward the cap that stops an update which will
not install, and the count was never cleared, so the third restart of
a session ended it however far apart they were. A client that ran for
a minute before asking is not that loop: the count starts again.

* fix: measure the client's run time as it exits

The time spent collecting logs and checking FEX after the client exits
counted toward its run, so a slow cleanup could make a quick exit 42
look like a long one and clear the count.

---------

Co-authored-by: Kirk <12691869+KirkPatrickJunsay@users.noreply.github.com>
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>

* fix: the front end keeps its page when the Fold is folded or unfolded (#832)

* fix: the front end keeps its page when the Fold is folded or unfolded

MainActivity, FileManagerActivity, FilePickerActivity and StoreLoginActivity did not declare the screen-size configuration changes, so folding or unfolding a foldable recreated them and dropped their in-memory state. They now handle orientation, screenSize, screenLayout, smallestScreenSize and density themselves, like SessionActivity already does. uiMode is left out on purpose.

* fix: store login keeps rebuilding its toolbar when the display density changes

StoreLoginActivity builds its toolbar in code with dp-to-pixel values taken at creation time and has no onConfigurationChanged. It no longer declares density in configChanges, so a density change recreates it as before this PR. Size and layout changes are still handled in place.

---------

Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com>

* Release pointer buttons without replaying stale motion (#803)

* Fix cursor warping on native touch down

* Preserve input cleanup without replaying stale pointer motion

---------

Co-authored-by: siyuan.qsy <siyuan.qsy@alibaba-inc.com>

* l10n: translate the strings added since #284 into zh-CN, zh-HK, zh-TW and ja (#539)

* l10n: translate the 184 strings added since #284 (zh-CN/HK/TW, ja)

The stores, cloud saves, Windows components, Steam touch, desktop
removal and background-downloads strings landed after #284's
translation snapshot, so every one of them fell back to English.
Translate all 184 into Simplified Chinese, Traditional Chinese
(Taiwan and Hong Kong) and Japanese, keeping each locale file's own
vocabulary (工作階段/會話, 解除安裝/卸載, 元件/組件, 設定).

Also fix four Hong Kong strings that kept the simplified 着色器.

* l10n(zh): fix stale and ambiguous strings found in review

Severe: summary_remove_game was untranslated English in all three
files; mode_added_art_hint, wincomp_installers_note and
wincomp_needs_installer still described the pre-#480/#492 English.

Also: distinguish the Setup wizard from Android system settings in
zh-HK/zh-TW (初始設定 / 系統設定 / Android 設定), unify library as
收藏庫, component as 組件 in zh-HK, session as 會話 in zh-HK, account
as 帳戶 in zh-HK, Trending as 趋势/趨勢, Forget as 清除, reword the
re-applied-at-launch, action-failed and already-in-Games strings, and
play as 執行/開啟遊戲 in zh-TW/zh-HK.

* l10n(ja): fix stale and ambiguous strings found in review

---------

Co-authored-by: Dantalian <Dantalian-dev@users.noreply.github.com>
Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com>

* Rebuild and verify Windows VR runtime components

* Rebuild and verify Windows VR runtime components

* Add top, bottom, and centered picture positions for Steam sessions (#871)

* fix: dependency scan ignores folders above the game folder (#859)

* DroidDeck-Proton: get releases from the Droid-Deck org repo

DroidDeck-Proton is now built and released on Droid-Deck/DroidDeck-Proton
(11-9.1 is Latest there), so the Components page, the update check and the
guest installer read releases from the org repo instead of The412Banner's.

* feat: low-latency controller and touch toggles in the session drawer (#808)

* fix: SteamGridDB lookups no longer stick as "no match" after a failure; add a search to the art chooser (#876)

* feat: Steam home wall fills from the signed-in library instead of store picks (#878)

* test: cover GPU family and support classification (#880)

* Fix local builds on Linux failing after the first Comet build (#866)

* feat: sort the store library and installed tabs, and switch between card and list views (#798)

* feat: three-finger tap toggles Steam's on-screen keyboard in game mode (#782)

* fix: keep Quest-patched Turnip as the auto default (#853)

* Fix deploy_local.sh and droiddeckctl not finding a phone connected over wireless debugging (#864)

* fix: keep proot sessions alive when the kernel loses fork events (#457)

* fix(quest): correct desktop and Steam display corruption across sessions (#733)

fix(quest): stabilize desktop and Steam layer presentation

Keep Quest SDR scenes and the black backdrop off the Android Vulkan swapchain regardless of session order or HDR preferences. Only report the first frame after client content is submitted.

Add backdrop lifecycle and first-frame regression coverage. Record the user's successful Quest 3 Test 2 result.

Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com>

* fix: keep SteamVR syscall hooks and report Steam crashes (#905)

* fix: preserve SteamVR syscall hooks

* fix: report Steam crashes through gamescope

* fix: honor glasses pacing and resolution in SteamVR launches

---------

Co-authored-by: connor g <connorsspam1992@gmail.com>
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
Co-authored-by: Yassine Gherbi <y.gherbi.dev@gmail.com>
Co-authored-by: Resul Övür <92828257+ovurrsl@users.noreply.github.com>
Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com>
Co-authored-by: Kirk <kirtoy.junsay@gmail.com>
Co-authored-by: Kirk <12691869+KirkPatrickJunsay@users.noreply.github.com>
Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com>
Co-authored-by: angelrenefm <17342133+angelrenefm@users.noreply.github.com>
Co-authored-by: asdf17128 <asdf17128@gmail.com>
Co-authored-by: siyuan.qsy <siyuan.qsy@alibaba-inc.com>
Co-authored-by: Dantalian <wsu091227@qq.com>
Co-authored-by: Dantalian <Dantalian-dev@users.noreply.github.com>
Co-authored-by: The412Banner <the412banner@users.noreply.github.com>
Co-authored-by: The412Banner <205237651+The412Banner@users.noreply.github.com>
Co-authored-by: FX1922 <120828496+FX192@users.noreply.github.com>
Co-authored-by: Muaz Kadan <32595066+muazkadan@users.noreply.github.com>
Co-authored-by: kingokksa <47888451+kingokksa@users.noreply.github.com>
Co-authored-by: Jamie Schenker <jam1esch3nk3r@gmail.com>
Co-authored-by: Jagger15 <jagger2333@live.com>

* Glasses: keep a pending 2D restore and the SteamVR recovery offer, show Play SteamVR only with a picture

* Translate the glasses calibration, XREAL and SteamVR recovery strings

* SteamVR recovery: give a finished teardown time to collect logs before restarting

* Credit the projects the XR glasses support builds on

* Joy-Cons: SteamVR hands from their gyro while SteamVR runs, one combined pad otherwise

* Headsets: settings badge on Play SteamVR instead of a top-right button, both shown only once connected

* Hand tracking: camera-tracked Joy-Cons and bare hands in SteamVR, drawn as white gloves

- Joy-Con movement from the accelerometer (report reordering, per-Joy-Con calibration, zero-velocity updates)
- MediaPipe pose and hand landmarks from the device camera, placement check, per-hand Kalman filter with the Joy-Con
- No controller connected: bare camera hands with Quest-style gestures, 1€ filtered, rendered as a white glove model built from a distance field
- SteamVR safe mode cleared before each start so one crash no longer blocks the driver

---------

Co-authored-by: MaxsTechReview <6025299+maxjivi05@users.noreply.github.com>
Co-authored-by: informalTechCode <informaltechyt@gmail.com>
Co-authored-by: connor g <connorsspam1992@gmail.com>
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
Co-authored-by: Yassine Gherbi <y.gherbi.dev@gmail.com>
Co-authored-by: Resul Övür <92828257+ovurrsl@users.noreply.github.com>
Co-authored-by: ovurrsl <ovurrsl@users.noreply.github.com>
Co-authored-by: Kirk <kirtoy.junsay@gmail.com>
Co-authored-by: Kirk <12691869+KirkPatrickJunsay@users.noreply.github.com>
Co-authored-by: xXJsonDeruloXx <danielhimebauch@gmail.com>
Co-authored-by: angelrenefm <17342133+angelrenefm@users.noreply.github.com>
Co-authored-by: asdf17128 <asdf17128@gmail.com>
Co-authored-by: siyuan.qsy <siyuan.qsy@alibaba-inc.com>
Co-authored-by: Dantalian <wsu091227@qq.com>
Co-authored-by: Dantalian <Dantalian-dev@users.noreply.github.com>
Co-authored-by: The412Banner <the412banner@users.noreply.github.com>
Co-authored-by: The412Banner <205237651+The412Banner@users.noreply.github.com>
Co-authored-by: FX1922 <120828496+FX192@users.noreply.github.com>
Co-authored-by: Muaz Kadan <32595066+muazkadan@users.noreply.github.com>
Co-authored-by: kingokksa <47888451+kingokksa@users.noreply.github.com>
Co-authored-by: Jamie Schenker <jam1esch3nk3r@gmail.com>
Co-authored-by: Jagger15 <jagger2333@live.com>
This commit is contained in:
221 files changed
+24369 -491

No files matched your search

@@ -47,6 +47,7 @@ object ControllerPrefs {
val qamButton: Boolean,
val keyboardButton: Boolean,
val selectSteam: Boolean,
val joyConVr: Boolean,
val snap: Boolean,
val customLayout: Boolean,
val mapping: Map<String, String>,
@@ -67,6 +68,7 @@ object ControllerPrefs {
qamButton = p.getBoolean("qamButton", true),
keyboardButton = p.getBoolean("keyboardButton", true),
selectSteam = p.getBoolean("selectSteam", false),
joyConVr = joyConVr(context),
snap = p.getBoolean("snap", true),
customLayout = p.all.keys.any { it.startsWith("layout.") },
mapping = mappable.associate { (id, _) -> id to target(context, id) },
@@ -127,6 +129,12 @@ object ControllerPrefs {
prefs(context).edit().putBoolean("selectSteam", on).apply()
}
fun joyConVr(context: Context): Boolean = prefs(context).getBoolean("joyConVr", true)
fun setJoyConVr(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("joyConVr", on).apply()
}
fun setSnap(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("snap", on).apply()
}
@@ -119,6 +119,10 @@ public class FakeInputWriter {
private static native void nativeStoreFence();
public static void storeFence() {
nativeStoreFence();
}
private final File eventFile;
private final int slot;
private final ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER_SIZE);
@@ -0,0 +1,143 @@
package com.droiddeck.launcher.input
import android.view.InputDevice
import android.view.KeyEvent
import android.view.MotionEvent
object JoyCon {
const val LEFT = 0
const val RIGHT = 1
const val VR_TRIGGER = 1 shl 0
const val VR_GRIP = 1 shl 1
const val VR_A = 1 shl 2
const val VR_B = 1 shl 3
const val VR_STICK = 1 shl 4
const val VR_SYSTEM = 1 shl 5
const val VR_RUMBLE_SLOT = 0x100
private const val VENDOR = 0x057e
private const val PRODUCT_LEFT = 0x2006
private const val PRODUCT_RIGHT = 0x2007
private const val BTN_SOUTH = 0x130
private const val BTN_EAST = 0x131
private const val BTN_NORTH = 0x133
private const val BTN_WEST = 0x134
private const val BTN_Z = 0x135
private const val BTN_TL = 0x136
private const val BTN_TR = 0x137
private const val BTN_TL2 = 0x138
private const val BTN_TR2 = 0x139
private const val BTN_SELECT = 0x13a
private const val BTN_START = 0x13b
private const val BTN_MODE = 0x13c
private const val BTN_THUMBL = 0x13d
private const val BTN_THUMBR = 0x13e
private const val BTN_DPAD_UP = 0x220
private const val BTN_DPAD_DOWN = 0x221
private const val BTN_DPAD_LEFT = 0x222
private const val BTN_DPAD_RIGHT = 0x223
private val NO_VR_DEVICES = intArrayOf(PadBridge.NO_CONTROLLER, PadBridge.NO_CONTROLLER)
private var vrOwner: Any? = null
@Volatile private var vrDevices = NO_VR_DEVICES
@JvmStatic
fun side(device: InputDevice?): Int = when {
device == null || device.isVirtual || device.vendorId != VENDOR -> -1
device.productId == PRODUCT_LEFT -> LEFT
device.productId == PRODUCT_RIGHT -> RIGHT
else -> -1
}
@JvmStatic
fun stickAxes(side: Int, device: InputDevice, source: Int): IntArray = when {
side == LEFT -> intArrayOf(MotionEvent.AXIS_X, MotionEvent.AXIS_Y)
device.getMotionRange(MotionEvent.AXIS_RX, source) != null -> intArrayOf(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY)
else -> intArrayOf(MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ)
}
@JvmStatic
fun isRail(side: Int, scanCode: Int): Boolean = when (side) {
LEFT -> scanCode == BTN_TR || scanCode == BTN_TR2
RIGHT -> scanCode == BTN_TL || scanCode == BTN_TL2
else -> false
}
internal fun padKey(side: Int, scanCode: Int): Int = when (side) {
LEFT -> when (scanCode) {
BTN_TL -> KeyEvent.KEYCODE_BUTTON_L1
BTN_TL2 -> KeyEvent.KEYCODE_BUTTON_L2
BTN_SELECT -> KeyEvent.KEYCODE_BUTTON_SELECT
BTN_THUMBL -> KeyEvent.KEYCODE_BUTTON_THUMBL
BTN_Z -> KeyEvent.KEYCODE_BUTTON_Z
BTN_DPAD_UP -> KeyEvent.KEYCODE_DPAD_UP
BTN_DPAD_DOWN -> KeyEvent.KEYCODE_DPAD_DOWN
BTN_DPAD_LEFT -> KeyEvent.KEYCODE_DPAD_LEFT
BTN_DPAD_RIGHT -> KeyEvent.KEYCODE_DPAD_RIGHT
else -> KeyEvent.KEYCODE_UNKNOWN
}
RIGHT -> when (scanCode) {
BTN_SOUTH -> KeyEvent.KEYCODE_BUTTON_A
BTN_EAST -> KeyEvent.KEYCODE_BUTTON_B
BTN_NORTH -> KeyEvent.KEYCODE_BUTTON_Y
BTN_WEST -> KeyEvent.KEYCODE_BUTTON_X
BTN_TR -> KeyEvent.KEYCODE_BUTTON_R1
BTN_TR2 -> KeyEvent.KEYCODE_BUTTON_R2
BTN_START -> KeyEvent.KEYCODE_BUTTON_START
BTN_THUMBR -> KeyEvent.KEYCODE_BUTTON_THUMBR
BTN_MODE -> KeyEvent.KEYCODE_BUTTON_MODE
else -> KeyEvent.KEYCODE_UNKNOWN
}
else -> KeyEvent.KEYCODE_UNKNOWN
}
@JvmStatic
fun normalize(event: KeyEvent): KeyEvent {
val side = side(event.device)
if (side < 0) return event
val code = padKey(side, event.scanCode)
if (code == KeyEvent.KEYCODE_UNKNOWN || code == event.keyCode) return event
return KeyEvent(event.downTime, event.eventTime, event.action, code, event.repeatCount, event.metaState,
event.deviceId, event.scanCode, event.flags, event.source)
}
internal fun vrButton(side: Int, scanCode: Int): Int = when (side) {
LEFT -> when (scanCode) {
BTN_TL2 -> VR_TRIGGER
BTN_TL, BTN_TR, BTN_TR2 -> VR_GRIP
BTN_DPAD_DOWN, BTN_DPAD_RIGHT -> VR_A
BTN_DPAD_UP, BTN_DPAD_LEFT, BTN_SELECT -> VR_B
BTN_THUMBL -> VR_STICK
BTN_Z -> VR_SYSTEM
else -> 0
}
RIGHT -> when (scanCode) {
BTN_TR2 -> VR_TRIGGER
BTN_TR, BTN_TL, BTN_TL2 -> VR_GRIP
BTN_SOUTH, BTN_EAST -> VR_A
BTN_NORTH, BTN_WEST, BTN_START -> VR_B
BTN_THUMBR -> VR_STICK
BTN_MODE -> VR_SYSTEM
else -> 0
}
else -> 0
}
@JvmStatic
fun vrRumbleDevice(slot: Int): Int? =
if (slot == VR_RUMBLE_SLOT + LEFT || slot == VR_RUMBLE_SLOT + RIGHT) vrDevices[slot - VR_RUMBLE_SLOT] else null
@Synchronized
internal fun setVrDevices(owner: Any, devices: IntArray) {
vrOwner = owner
vrDevices = devices
}
@Synchronized
internal fun clearVrDevices(owner: Any) {
if (vrOwner !== owner) return
vrOwner = null
vrDevices = NO_VR_DEVICES
}
}
@@ -0,0 +1,213 @@
package com.droiddeck.launcher.input
import android.content.Context
import com.droiddeck.launcher.glasses.Quaternion
import com.droiddeck.launcher.glasses.Vec3
import kotlin.math.abs
import kotlin.math.exp
import kotlin.math.roundToInt
import kotlin.math.sqrt
internal class JoyConAccelCalibration {
var bias = Vec3(0f, 0f, 0f)
private set
var scale = 1f
private set
var ready = false
private set
private val sums = HashMap<Int, DoubleArray>()
fun restore(saved: FloatArray?) {
if (saved == null || saved.size != 4 || saved.any { it.isNaN() || it.isInfinite() }) return
val b = Vec3(saved[0], saved[1], saved[2])
if (!plausible(b, saved[3])) return
bias = b
scale = saved[3]
ready = true
}
fun saved(): FloatArray? = if (ready) floatArrayOf(bias.x, bias.y, bias.z, scale) else null
fun correct(raw: Vec3): Vec3 = if (ready) (raw - bias) * scale else raw
fun addResting(raw: Vec3): Boolean {
val n = raw.length()
if (n < 1e-3f) return false
val key = bin(raw.x / n) * 9 + bin(raw.y / n) * 3 + bin(raw.z / n)
val s = sums.getOrPut(key) { DoubleArray(4) }
s[0] += raw.x.toDouble()
s[1] += raw.y.toDouble()
s[2] += raw.z.toDouble()
s[3] += 1.0
return s[3] % SOLVE_EVERY == 0.0 && solve()
}
private fun solve(): Boolean {
val points = sums.values.filter { it[3] >= MIN_SAMPLES }.map { doubleArrayOf(it[0] / it[3], it[1] / it[3], it[2] / it[3]) }
if (points.size < MIN_BINS || smallestSpread(points) < MIN_SPREAD) return false
val ata = Array(4) { DoubleArray(4) }
val atb = DoubleArray(4)
for (p in points) {
val row = doubleArrayOf(2 * p[0], 2 * p[1], 2 * p[2], 1.0)
val rhs = p[0] * p[0] + p[1] * p[1] + p[2] * p[2]
for (i in 0..3) {
atb[i] += row[i] * rhs
for (j in 0..3) ata[i][j] += row[i] * row[j]
}
}
val x = solve4(ata, atb) ?: return false
val radius2 = x[3] + x[0] * x[0] + x[1] * x[1] + x[2] * x[2]
if (radius2 <= 0) return false
val b = Vec3(x[0].toFloat(), x[1].toFloat(), x[2].toFloat())
val s = (GRAVITY / sqrt(radius2)).toFloat()
if (!plausible(b, s)) return false
bias = b
scale = s
ready = true
return true
}
private fun bin(v: Float) = (v * 1.5f).roundToInt().coerceIn(-1, 1) + 1
companion object {
private const val GRAVITY = 9.80665
private const val MIN_SAMPLES = 20.0
private const val MIN_BINS = 5
private const val MIN_SPREAD = 2.0
private const val SOLVE_EVERY = 25.0
private const val MAX_BIAS = 1.5f
private const val MAX_SCALE_ERROR = 0.1f
private fun plausible(b: Vec3, s: Float) = b.length() <= MAX_BIAS && abs(s - 1f) <= MAX_SCALE_ERROR
private fun smallestSpread(points: List<DoubleArray>): Double {
val mean = DoubleArray(3) { i -> points.sumOf { it[i] } / points.size }
val c = Array(3) { DoubleArray(3) }
for (p in points) for (i in 0..2) for (j in 0..2) c[i][j] += (p[i] - mean[i]) * (p[j] - mean[j])
return sqrt(maxOf(smallestEigenvalue(c), 0.0))
}
private fun smallestEigenvalue(m: Array<DoubleArray>): Double {
val a = Array(3) { m[it].copyOf() }
repeat(50) {
var p = 0
var q = 1
for ((i, j) in listOf(0 to 2, 1 to 2)) if (abs(a[i][j]) > abs(a[p][q])) { p = i; q = j }
if (abs(a[p][q]) < 1e-12) return minOf(a[0][0], a[1][1], a[2][2])
val theta = (a[q][q] - a[p][p]) / (2 * a[p][q])
val t = (if (theta >= 0) 1.0 else -1.0) / (abs(theta) + sqrt(theta * theta + 1))
val c = 1 / sqrt(t * t + 1)
val s = t * c
for (k in 0..2) {
val kp = a[k][p]
val kq = a[k][q]
a[k][p] = c * kp - s * kq
a[k][q] = s * kp + c * kq
}
for (k in 0..2) {
val pk = a[p][k]
val qk = a[q][k]
a[p][k] = c * pk - s * qk
a[q][k] = s * pk + c * qk
}
}
return minOf(a[0][0], a[1][1], a[2][2])
}
private fun solve4(a: Array<DoubleArray>, b: DoubleArray): DoubleArray? {
val m = Array(4) { i -> DoubleArray(5) { j -> if (j < 4) a[i][j] else b[i] } }
for (col in 0..3) {
val pivot = (col..3).maxBy { abs(m[it][col]) }
if (abs(m[pivot][col]) < 1e-9) return null
val swap = m[col]
m[col] = m[pivot]
m[pivot] = swap
for (r in 0..3) {
if (r == col) continue
val f = m[r][col] / m[col][col]
for (k in col..4) m[r][k] -= f * m[col][k]
}
}
return DoubleArray(4) { m[it][4] / m[it][it] }
}
}
}
internal class JoyConMotion {
var velocity = Vec3(0f, 0f, 0f)
private set
var displacement = Vec3(0f, 0f, 0f)
private set
var inertial = Vec3(0f, 0f, 0f)
private set
var resting = false
private set
private var gravity = Float.NaN
private var average = Vec3(0f, 0f, 0f)
private var calmFor = 0f
private var stillFor = 0f
private var movingFor = 0f
fun update(rotation: Quaternion, accel: Vec3, rate: Vec3, calibrated: Boolean, dt: Float) {
if (dt <= 0f) return
if (gravity.isNaN()) {
gravity = accel.length()
average = accel
}
if (calibrated) gravity = GRAVITY
average += (accel - average) * (dt / AVERAGE_SECONDS).coerceAtMost(1f)
val world = rotation.rotate(accel)
val linear = Vec3(world.x, world.y - gravity, world.z)
inertial = inertial * exp(-dt / INERTIAL_SECONDS) + linear * dt
val calm = rate.length() < CALM_RATE && (accel - average).length() < CALM_ACCEL
calmFor = if (calm) calmFor + dt else 0f
val still = rate.length() < CALM_RATE &&
(linear.length() < STILL_ACCEL || calmFor >= if (calibrated) CALIBRATED_CALM_SECONDS else UNCALIBRATED_CALM_SECONDS)
stillFor = if (still) stillFor + dt else 0f
resting = calmFor >= RESTING_SECONDS && rate.length() < RESTING_RATE
if (stillFor >= STILL_SECONDS) {
movingFor = 0f
velocity *= exp(-dt / SETTLE_SECONDS)
if (!calibrated) gravity += (accel.length() - gravity) * (dt / GRAVITY_SECONDS).coerceAtMost(1f)
} else {
movingFor += dt
val leak = if (movingFor < FREE_SECONDS) LEAK_SECONDS else LONG_MOVE_LEAK_SECONDS
velocity = velocity * exp(-dt / leak) + linear * dt
}
displacement += velocity * dt
}
companion object {
private const val GRAVITY = 9.80665f
private const val AVERAGE_SECONDS = 0.1f
private const val CALM_RATE = 0.2f
private const val CALM_ACCEL = 0.25f
private const val STILL_ACCEL = 0.12f
private const val STILL_SECONDS = 0.2f
private const val UNCALIBRATED_CALM_SECONDS = 0.5f
private const val CALIBRATED_CALM_SECONDS = 2f
private const val SETTLE_SECONDS = 0.05f
private const val LEAK_SECONDS = 20f
private const val FREE_SECONDS = 1f
private const val LONG_MOVE_LEAK_SECONDS = 0.2f
private const val GRAVITY_SECONDS = 0.5f
private const val INERTIAL_SECONDS = 30f
private const val RESTING_SECONDS = 0.3f
private const val RESTING_RATE = 0.05f
}
}
internal object JoyConCalibrations {
fun load(context: Context, descriptor: String?): FloatArray? {
if (descriptor.isNullOrEmpty()) return null
val text = ControllerPrefs.prefs(context).getString(KEY + descriptor, null) ?: return null
return text.split(',').mapNotNull { it.toFloatOrNull() }.toFloatArray().takeIf { it.size == 4 }
}
fun save(context: Context, descriptor: String?, values: FloatArray?) {
if (descriptor.isNullOrEmpty() || values == null) return
ControllerPrefs.prefs(context).edit().putString(KEY + descriptor, values.joinToString(",")).apply()
}
private const val KEY = "joyConAccel."
}
@@ -0,0 +1,113 @@
package com.droiddeck.launcher.input
import com.droiddeck.launcher.glasses.Quaternion
import com.droiddeck.launcher.glasses.Vec3
import kotlin.math.abs
internal class JoyConOrientation {
var rotation = Quaternion.IDENTITY
private set
var rate = Vec3(0f, 0f, 0f)
private set
var ready = false
private set
private var bias = Vec3(0f, 0f, 0f)
private var stillFor = 0f
fun update(accelKernel: FloatArray, gyroKernel: FloatArray, dt: Float) = update(axes(accelKernel), axes(gyroKernel), dt)
fun update(accel: Vec3, gyro: Vec3, dt: Float) {
val norm = accel.length()
val gravityValid = abs(norm - GRAVITY) < GRAVITY_TOLERANCE
if (!ready) {
if (!gravityValid) return
val up = accel.normalized()
val axis = up.cross(WORLD_UP)
rotation = if (up.y < -0.9999f) Quaternion.fromAxisAngle(Vec3(1f, 0f, 0f), Math.PI.toFloat())
else Quaternion(1f + up.y, axis.x, axis.y, axis.z).normalized()
rate = Vec3(0f, 0f, 0f)
ready = true
return
}
if (dt <= 0f) return
val still = gravityValid && abs(norm - GRAVITY) < STILL_ACCEL && (gyro - bias).length() < STILL_RATE
stillFor = if (still) stillFor + dt else 0f
if (stillFor >= STILL_SECONDS) {
val alpha = (dt / BIAS_SECONDS).coerceAtMost(1f)
bias = bias * (1f - alpha) + gyro * alpha
}
rate = gyro - bias
var corrected = rate
if (gravityValid && rate.length() < MOVING_RATE) {
val predictedUp = rotation.conjugate().rotate(WORLD_UP)
corrected += accel.normalized().cross(predictedUp) * (GAIN * (1f - abs(norm - GRAVITY) / GRAVITY_TOLERANCE))
}
rotation = rotation.integrateBodyRate(corrected, dt).normalized()
}
companion object {
private val WORLD_UP = Vec3(0f, 1f, 0f)
private const val GRAVITY = 9.80665f
private const val GRAVITY_TOLERANCE = 1.0f
private const val STILL_ACCEL = 0.5f
private const val STILL_RATE = 0.05f
private const val STILL_SECONDS = 0.3f
private const val BIAS_SECONDS = 2f
private const val GAIN = 1.0f
private const val MOVING_RATE = 1.0f
fun axes(v: FloatArray) = Vec3(-v[1], v[2], -v[0])
}
}
internal class JoyConReports {
class Sample(val accel: FloatArray, val gyro: FloatArray, val dt: Float)
private val pending = ArrayList<FloatArray>(4)
private var pendingAt = 0L
private var previousFirst: FloatArray? = null
private var previousLast: FloatArray? = null
private var previousSample: FloatArray? = null
private var previousAt = 0L
private var order = NEWEST_FIRST_START
val size: Int get() = pending.size
fun add(accel: FloatArray, gyro: FloatArray, arrivalNs: Long) {
if (pending.isEmpty()) pendingAt = arrivalNs
pending += floatArrayOf(accel[0], accel[1], accel[2], gyro[0], gyro[1], gyro[2])
}
fun flush(): List<Sample> {
if (pending.isEmpty()) return emptyList()
val first = pending.first()
val last = pending.last()
if (pending.size > 1) {
if (previousFirst?.contentEquals(last) == true) order = (order + 1).coerceAtMost(ORDER_LIMIT)
else if (previousLast?.contentEquals(first) == true) order = (order - 1).coerceAtLeast(-ORDER_LIMIT)
}
val chronological = if (order >= 0) pending.asReversed() else pending
val fresh = ArrayList<FloatArray>(chronological.size)
var before = previousSample
for (sample in chronological) {
if (before?.contentEquals(sample) != true) fresh += sample
before = sample
}
val used = fresh.ifEmpty { listOf(chronological.last()) }
val dt = if (previousAt == 0L) 0f else ((pendingAt - previousAt).coerceAtLeast(0L) * 1e-9f / used.size).coerceAtMost(MAX_STEP_S)
val out = used.map { Sample(it.copyOfRange(0, 3), it.copyOfRange(3, 6), dt) }
previousFirst = first
previousLast = last
previousSample = chronological.last()
previousAt = pendingAt
pending.clear()
return out
}
companion object {
const val SAMPLES_PER_REPORT = 3
private const val NEWEST_FIRST_START = 2
private const val ORDER_LIMIT = 20
private const val MAX_STEP_S = 0.05f
}
}
@@ -0,0 +1,116 @@
package com.droiddeck.launcher.input
import android.util.Log
import com.droiddeck.launcher.glasses.Quaternion
import com.droiddeck.launcher.glasses.Vec3
import java.io.File
import java.io.RandomAccessFile
import java.nio.ByteOrder
import java.nio.MappedByteBuffer
import java.nio.channels.FileChannel
internal class JoyConShm private constructor(
private val file: RandomAccessFile,
private val map: MappedByteBuffer,
private val fence: () -> Unit,
) {
class Hand(
val connected: Boolean,
val charging: Boolean = false,
val buttons: Int = 0,
val rotation: Quaternion = Quaternion.IDENTITY,
val rate: Vec3 = Vec3(0f, 0f, 0f),
val displacement: Vec3 = Vec3(0f, 0f, 0f),
val velocity: Vec3 = Vec3(0f, 0f, 0f),
val inertial: Vec3 = Vec3(0f, 0f, 0f),
val stickX: Float = 0f,
val stickY: Float = 0f,
val battery: Float = -1f,
val recenter: Int = 0,
val timeNs: Long = 0L,
)
private var seq = map.getInt(SEQ).let { if (it and 1 != 0) it + 1 else it }
init {
begin()
map.putInt(MAGIC_AT, MAGIC)
map.putInt(VERSION_AT, VERSION)
for (at in HANDS until SIZE step 4) map.putInt(at, 0)
end()
}
fun write(side: Int, hand: Hand) {
val at = HANDS + side * HAND_SIZE
begin()
map.putInt(at, (if (hand.connected) CONNECTED else 0) or (if (hand.charging) CHARGING else 0))
map.putInt(at + 4, hand.buttons)
map.putFloat(at + 8, hand.rotation.w)
map.putFloat(at + 12, hand.rotation.x)
map.putFloat(at + 16, hand.rotation.y)
map.putFloat(at + 20, hand.rotation.z)
map.putFloat(at + 24, hand.rate.x)
map.putFloat(at + 28, hand.rate.y)
map.putFloat(at + 32, hand.rate.z)
map.putFloat(at + 36, hand.stickX)
map.putFloat(at + 40, hand.stickY)
map.putFloat(at + 44, hand.battery)
map.putInt(at + 48, hand.recenter)
map.putLong(at + 56, hand.timeNs)
map.putFloat(at + 64, hand.displacement.x)
map.putFloat(at + 68, hand.displacement.y)
map.putFloat(at + 72, hand.displacement.z)
map.putFloat(at + 76, hand.velocity.x)
map.putFloat(at + 80, hand.velocity.y)
map.putFloat(at + 84, hand.velocity.z)
map.putFloat(at + 88, hand.inertial.x)
map.putFloat(at + 92, hand.inertial.y)
map.putFloat(at + 96, hand.inertial.z)
map.putInt(at + 100, 0)
end()
}
fun close() {
write(JoyCon.LEFT, Hand(connected = false))
write(JoyCon.RIGHT, Hand(connected = false))
runCatching { file.close() }
}
private fun begin() {
map.putInt(SEQ, ++seq)
fence()
}
private fun end() {
fence()
map.putInt(SEQ, ++seq)
}
companion object {
const val FILE = "droiddeck-joycon"
const val SIZE = 224
private const val MAGIC = 0x4E434A44
private const val VERSION = 3
private const val MAGIC_AT = 0
private const val VERSION_AT = 4
private const val SEQ = 8
private const val HANDS = 16
private const val HAND_SIZE = 104
private const val CONNECTED = 1
private const val CHARGING = 2
fun open(path: File, fence: () -> Unit = FakeInputWriter::storeFence): JoyConShm? = runCatching {
path.parentFile?.mkdirs()
val file = RandomAccessFile(path, "rw")
try {
file.setLength(SIZE.toLong())
val map = file.channel.map(FileChannel.MapMode.READ_WRITE, 0, SIZE.toLong())
map.order(ByteOrder.LITTLE_ENDIAN)
JoyConShm(file, map, fence)
} catch (e: Exception) {
file.close()
throw e
}
}.onFailure { Log.w("JoyConVr", "Joy-Con pose file unavailable: $path", it) }.getOrNull()
}
}
@@ -0,0 +1,363 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.hardware.BatteryState
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.CombinedVibration
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.os.Process
import android.os.VibrationEffect
import android.util.Log
import android.view.InputDevice
import android.view.KeyEvent
import android.view.MotionEvent
import androidx.annotation.RequiresApi
import java.io.File
import kotlin.math.min
import kotlin.math.sqrt
@RequiresApi(31)
class JoyConVr(
private val context: Context,
private val path: File,
private val onDevicesChanged: (taken: List<Int>, released: List<Int>) -> Unit,
) {
private val thread = HandlerThread("joycon-vr", Process.THREAD_PRIORITY_DISPLAY).apply { start() }
private val worker = Handler(thread.looper)
private val main = Handler(Looper.getMainLooper())
@Volatile private var owned = IntArray(0)
private var wanted = false
private var closed = false
private var retries = 0
private var shm: JoyConShm? = null
private val hands = arrayOfNulls<Hand>(2)
private val retry = Runnable { apply() }
fun setActive(on: Boolean) {
worker.post {
if (closed || wanted == on) return@post
wanted = on
retries = 0
apply()
}
}
fun refresh() {
worker.post {
if (closed) return@post
retries = 0
apply()
}
}
fun owns(deviceId: Int): Boolean = owned.contains(deviceId)
val holding: Boolean get() = owned.isNotEmpty()
fun onKeyEvent(event: KeyEvent): Boolean {
if (!owns(event.deviceId)) return false
if (event.repeatCount > 0) return true
val down = when (event.action) {
KeyEvent.ACTION_DOWN -> true
KeyEvent.ACTION_UP -> false
else -> return true
}
val id = event.deviceId
val scanCode = event.scanCode
worker.post { hand(id)?.key(scanCode, down) }
return true
}
fun onMotionEvent(event: MotionEvent): Boolean {
if (!owns(event.deviceId)) return false
if (!event.isFromSource(InputDevice.SOURCE_JOYSTICK) || event.actionMasked != MotionEvent.ACTION_MOVE) return true
val device = event.device ?: return true
val side = JoyCon.side(device)
if (side < 0) return true
val axes = JoyCon.stickAxes(side, device, event.source)
val x = event.getAxisValue(axes[0])
val y = event.getAxisValue(axes[1])
val id = event.deviceId
worker.post { hand(id)?.stick(x, -y) }
return true
}
fun releaseButtons() {
worker.post { hands.forEach { it?.release() } }
}
fun close() {
worker.post {
closed = true
wanted = false
apply()
shm?.close()
shm = null
}
thread.quitSafely()
}
private fun hand(id: Int): Hand? = hands.firstOrNull { it?.device?.id == id }
private fun apply() {
worker.removeCallbacks(retry)
val found = arrayOfNulls<InputDevice>(2)
var waiting = false
if (wanted && !closed) {
for (id in InputDevice.getDeviceIds()) {
val device = InputDevice.getDevice(id) ?: continue
val side = JoyCon.side(device)
if (side < 0 || found[side] != null) continue
if (hasMotion(device)) found[side] = device else waiting = true
}
}
val before = owned
for (side in 0..1) {
val current = hands[side]
val device = found[side]
if (current != null && current.device.id == device?.id) continue
current?.stop()
hands[side] = null
if (device != null) {
hands[side] = start(side, device)
if (hands[side] == null) waiting = true
}
}
val now = hands.mapNotNull { it?.device?.id }.toIntArray()
owned = now
if (closed) JoyCon.clearVrDevices(this)
else JoyCon.setVrDevices(this, IntArray(2) { hands[it]?.device?.id ?: PadBridge.NO_CONTROLLER })
if (!closed) {
val taken = now.filter { it !in before }
val released = before.filter { it !in now }
if (taken.isNotEmpty() || released.isNotEmpty()) main.post { onDevicesChanged(taken, released) }
}
if (wanted && waiting && retries < MAX_RETRIES) {
retries++
worker.postDelayed(retry, RETRY_MS)
}
}
private fun hasMotion(device: InputDevice): Boolean =
runCatching {
val sensors = device.sensorManager
sensors.getDefaultSensor(Sensor.TYPE_GYROSCOPE) != null && sensors.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null
}.getOrDefault(false)
private fun start(side: Int, device: InputDevice): Hand? {
val out = shm ?: JoyConShm.open(path)?.also { shm = it } ?: return null
val sensors = runCatching { device.sensorManager }.getOrNull() ?: return null
val gyro = runCatching { sensors.getDefaultSensor(Sensor.TYPE_GYROSCOPE) }.getOrNull() ?: return null
val accel = runCatching { sensors.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) }.getOrNull() ?: return null
val hand = Hand(side, device, sensors, out)
val listening = runCatching {
sensors.registerListener(hand, accel, SensorManager.SENSOR_DELAY_FASTEST, worker) &&
sensors.registerListener(hand, gyro, SensorManager.SENSOR_DELAY_FASTEST, worker)
}.onFailure { Log.w(TAG, "Joy-Con motion unavailable for \"${device.name}\"", it) }.getOrDefault(false)
if (!listening) {
runCatching { sensors.unregisterListener(hand) }
return null
}
Log.i(TAG, "${SIDES[side]} Joy-Con \"${device.name}\" (id ${device.id}) is a VR controller")
return hand
}
private inner class Hand(
val side: Int,
val device: InputDevice,
private val sensors: SensorManager,
private val out: JoyConShm,
) : SensorEventListener {
private val filter = JoyConOrientation()
private val motion = JoyConMotion()
private val calibration = JoyConAccelCalibration().apply { restore(JoyConCalibrations.load(context, device.descriptor)) }
private val reports = JoyConReports()
private val accel = FloatArray(3)
private var accelStamp = 0L
private var haveAccel = false
private val pressed = HashSet<Int>()
private var stickX = 0f
private var stickY = 0f
private var systemDown = false
private var systemTap = false
private var held = false
private var recenter = 0
private var battery = -1f
private var charging = false
private var batteryAt = 0L
private var sampleAt = 0L
private var live = true
private val hold = Runnable {
if (!systemDown || held) return@Runnable
held = true
recenter++
confirm()
publish()
}
private val tapEnd = Runnable {
systemTap = false
publish()
}
private val flush = Runnable { flushReport() }
override fun onSensorChanged(event: SensorEvent) {
if (!live) return
when (event.sensor.type) {
Sensor.TYPE_ACCELEROMETER -> {
if (event.timestamp == accelStamp) return
accelStamp = event.timestamp
event.values.copyInto(accel, 0, 0, 3)
haveAccel = true
}
Sensor.TYPE_GYROSCOPE -> {
if (!haveAccel) return
reports.add(accel, event.values, System.nanoTime())
worker.removeCallbacks(flush)
if (reports.size >= JoyConReports.SAMPLES_PER_REPORT) flushReport() else worker.postDelayed(flush, FLUSH_MS)
}
}
}
private fun flushReport() {
val samples = reports.flush()
if (samples.isEmpty() || !live) return
for (sample in samples) {
val raw = JoyConOrientation.axes(sample.accel)
val corrected = calibration.correct(raw)
filter.update(corrected, JoyConOrientation.axes(sample.gyro), sample.dt)
if (!filter.ready) continue
motion.update(filter.rotation, corrected, filter.rate, calibration.ready, sample.dt)
if (motion.resting && calibration.addResting(raw)) JoyConCalibrations.save(context, device.descriptor, calibration.saved())
}
val now = System.nanoTime()
sampleAt = now
if (now - batteryAt > BATTERY_NS) refreshBattery(now)
publish()
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit
fun key(scanCode: Int, down: Boolean) {
if (!live) return
val bit = JoyCon.vrButton(side, scanCode)
if (bit == 0) return
if (bit == JoyCon.VR_SYSTEM) {
system(down)
return
}
if (down) pressed += scanCode else pressed -= scanCode
publish()
}
fun stick(x: Float, y: Float) {
if (!live) return
val length = sqrt(x * x + y * y)
if (length < STICK_DEADZONE) {
stickX = 0f
stickY = 0f
} else {
val scale = min((length - STICK_DEADZONE) / (1f - STICK_DEADZONE), 1f) / length
stickX = x * scale
stickY = y * scale
}
publish()
}
fun release() {
if (!live) return
pressed.clear()
stickX = 0f
stickY = 0f
systemDown = false
systemTap = false
held = false
worker.removeCallbacks(hold)
worker.removeCallbacks(tapEnd)
publish()
}
fun stop() {
live = false
runCatching { sensors.unregisterListener(this) }
worker.removeCallbacks(hold)
worker.removeCallbacks(tapEnd)
worker.removeCallbacks(flush)
out.write(side, JoyConShm.Hand(connected = false))
Log.i(TAG, "${SIDES[side]} Joy-Con \"${device.name}\" (id ${device.id}) is a game pad again")
}
private fun system(down: Boolean) {
if (down == systemDown) return
systemDown = down
if (down) {
held = false
worker.postDelayed(hold, HOLD_MS)
return
}
worker.removeCallbacks(hold)
if (held) return
systemTap = true
publish()
worker.removeCallbacks(tapEnd)
worker.postDelayed(tapEnd, TAP_MS)
}
private fun buttons(): Int {
var bits = if (systemTap) JoyCon.VR_SYSTEM else 0
for (scanCode in pressed) bits = bits or JoyCon.vrButton(side, scanCode)
return bits
}
private fun publish() {
out.write(side, JoyConShm.Hand(
connected = filter.ready,
charging = charging,
buttons = buttons(),
rotation = filter.rotation,
rate = filter.rate,
displacement = motion.displacement,
velocity = motion.velocity,
inertial = motion.inertial,
stickX = stickX,
stickY = stickY,
battery = battery,
recenter = recenter,
timeNs = sampleAt,
))
}
private fun refreshBattery(now: Long) {
batteryAt = now
val state = runCatching { device.batteryState }.getOrNull() ?: return
battery = if (state.isPresent && !state.capacity.isNaN()) state.capacity else -1f
charging = state.isPresent && state.status == BatteryState.STATUS_CHARGING
}
private fun confirm() {
if (!ControllerPrefs.rumbleEnabled(context)) return
runCatching {
device.vibratorManager.vibrate(CombinedVibration.createParallel(
VibrationEffect.createOneShot(CONFIRM_MS, VibrationEffect.DEFAULT_AMPLITUDE)))
}
}
}
companion object {
const val FILE = JoyConShm.FILE
private const val TAG = "JoyConVr"
private val SIDES = arrayOf("left", "right")
private const val MAX_RETRIES = 6
private const val RETRY_MS = 500L
private const val HOLD_MS = 800L
private const val TAP_MS = 120L
private const val CONFIRM_MS = 80L
private const val BATTERY_NS = 30_000_000_000L
private const val STICK_DEADZONE = 0.12f
private const val FLUSH_MS = 3L
}
}
@@ -92,6 +92,7 @@ class OnScreenControls(
private val groups = controls.map { it.group }.distinct()
private var buttonsOnly = false
val isButtonsOnly: Boolean get() = buttonsOnly
private var quickHidden = false
private var quickPressedBy = -1
private var keyboardPressedBy = -1
@@ -46,6 +46,8 @@ public final class PadBridge {
private final FakeInputWriter writer;
private final PadState state = new PadState();
private final int[] owners = new int[SLOTS];
private final int[] partners = new int[SLOTS];
private volatile java.util.function.IntPredicate excluded = id -> false;
private final FakeInputWriter[] playerWriters = new FakeInputWriter[SLOTS];
private final PadState[] playerStates = new PadState[SLOTS];
private final PadState effectiveState = new PadState();
@@ -72,8 +74,10 @@ public final class PadBridge {
public static final int NO_CONTROLLER = -1;
private static volatile int activeControllerId = NO_CONTROLLER;
private static final AtomicIntegerArray slotControllers = new AtomicIntegerArray(SLOTS);
private static final AtomicIntegerArray slotJoyCons = new AtomicIntegerArray(SLOTS * 2);
static {
for (int slot = 0; slot < SLOTS; slot++) slotControllers.set(slot, NO_CONTROLLER);
for (int i = 0; i < SLOTS * 2; i++) slotJoyCons.set(i, NO_CONTROLLER);
}
public static int activeControllerId() { return activeControllerId; }
@@ -82,10 +86,16 @@ public final class PadBridge {
return slot >= 0 && slot < SLOTS ? slotControllers.get(slot) : activeControllerId;
}
public static int joyConForSlot(int slot, int side) {
return slot >= 0 && slot < SLOTS && (side == JoyCon.LEFT || side == JoyCon.RIGHT)
? slotJoyCons.get(slot * 2 + side) : NO_CONTROLLER;
}
public PadBridge(File fakeInputDir) {
this.fakeInputDir = fakeInputDir;
writer = new FakeInputWriter(fakeInputDir.getAbsolutePath(), 0);
Arrays.fill(owners, NO_CONTROLLER);
Arrays.fill(partners, NO_CONTROLLER);
for (int slot = 1; slot < SLOTS; slot++) playerStates[slot] = new PadState();
}
@@ -93,6 +103,10 @@ public final class PadBridge {
selectSteam = on;
}
public void setExcluded(java.util.function.IntPredicate devices) {
excluded = devices;
}
public synchronized boolean start() {
if (!open) {
open = writer.open();
@@ -106,7 +120,9 @@ public final class PadBridge {
activeControllerId = NO_CONTROLLER;
for (int slot = 0; slot < SLOTS; slot++) {
owners[slot] = NO_CONTROLLER;
partners[slot] = NO_CONTROLLER;
slotControllers.set(slot, NO_CONTROLLER);
clearJoyCons(slot);
if (playerWriters[slot] != null) {
playerWriters[slot].destroy();
playerWriters[slot] = null;
@@ -206,7 +222,7 @@ public final class PadBridge {
public synchronized void syncConnectedControllers() {
for (int deviceId : InputDevice.getDeviceIds()) {
InputDevice device = InputDevice.getDevice(deviceId);
if (isFromController(device)) publish(slotFor(device));
if (isFromController(device) && !excluded.test(deviceId)) publish(slotFor(device));
}
}
@@ -224,8 +240,10 @@ public final class PadBridge {
}
public synchronized boolean onKeyEvent(KeyEvent event) {
if (!isControllerKeyEvent(event)) return false;
if (!isControllerKeyEvent(event) || excluded.test(event.getDeviceId())) return false;
int slot = slotFor(event.getDevice());
int side = JoyCon.side(event.getDevice());
if (side >= 0 && partners[slot] != NO_CONTROLLER && JoyCon.isRail(side, event.getScanCode())) return true;
PadState pad = stateFor(slot);
boolean pressed = event.getAction() == KeyEvent.ACTION_DOWN;
switch (event.getKeyCode()) {
@@ -269,16 +287,32 @@ public final class PadBridge {
}
public synchronized boolean onMotionEvent(MotionEvent event) {
if (!isControllerMotionEvent(event)) return false;
if (!isControllerMotionEvent(event) || excluded.test(event.getDeviceId())) return false;
if (event.getAction() != MotionEvent.ACTION_MOVE) return false;
int slot = slotFor(event.getDevice());
PadState pad = stateFor(slot);
noteDevice(event.getDevice(), slot);
statAxes++;
scheduleStats();
InputDevice device = event.getDevice();
int side = JoyCon.side(device);
if (side >= 0) {
int[] stick = JoyCon.stickAxes(side, device, event.getSource());
float x = axis(event, stick[0]);
float y = axis(event, stick[1]);
if (side == JoyCon.LEFT) {
pad.leftX = x;
pad.leftY = y;
} else {
pad.rightX = x;
pad.rightY = y;
}
if (Math.max(Math.abs(x), Math.abs(y)) > 0.5f) notePlayerInput();
publish(slot);
return true;
}
pad.leftX = axis(event, MotionEvent.AXIS_X);
pad.leftY = axis(event, MotionEvent.AXIS_Y);
InputDevice device = event.getDevice();
boolean wiredXboxLayout = device != null
&& ((device.getVendorId() == 0x20d6 && device.getProductId() == 0x2063)
|| (device.getVendorId() == 0x0e6f && device.getProductId() == 0x02f0))
@@ -358,7 +392,7 @@ public final class PadBridge {
public synchronized void onDeviceRemoved(int deviceId) {
for (int slot = 0; slot < SLOTS; slot++) {
if (owners[slot] == deviceId) free(slot);
if (owners[slot] == deviceId || partners[slot] == deviceId) leave(slot, deviceId);
}
}
@@ -425,12 +459,26 @@ public final class PadBridge {
private int slotFor(InputDevice device) {
int id = device.getId();
if (owners[0] == id) return 0;
if (owners[0] == id || partners[0] == id) return 0;
for (int slot = 1; slot < SLOTS; slot++) {
if (owners[slot] == id) return slot;
if (owners[slot] == id || partners[slot] == id) return slot;
}
for (int slot = 0; slot < SLOTS; slot++) {
if (owners[slot] != NO_CONTROLLER && InputDevice.getDevice(owners[slot]) == null) free(slot);
if (partners[slot] != NO_CONTROLLER && InputDevice.getDevice(partners[slot]) == null) leave(slot, partners[slot]);
if (owners[slot] != NO_CONTROLLER && InputDevice.getDevice(owners[slot]) == null) leave(slot, owners[slot]);
}
int side = JoyCon.side(device);
for (int slot = 0; side >= 0 && slot < SLOTS; slot++) {
if (owners[slot] == NO_CONTROLLER || partners[slot] != NO_CONTROLLER) continue;
InputDevice owner = InputDevice.getDevice(owners[slot]);
if (JoyCon.side(owner) != 1 - side) continue;
partners[slot] = id;
slotJoyCons.set(slot * 2 + side, id);
slotJoyCons.set(slot * 2 + 1 - side, owner.getId());
if (slot == 0) releaseBackPaddles();
stateFor(slot).clear();
Log.i(TAG, "\"" + device.getName() + "\" (id " + id + ") joins \"" + owner.getName() + "\" as player " + (slot + 1));
return slot;
}
for (int slot = 0; slot < SLOTS; slot++) {
if (owners[slot] != NO_CONTROLLER) continue;
@@ -446,7 +494,8 @@ public final class PadBridge {
}
private boolean isPrimary(KeyEvent event) {
return owners[0] == event.getDevice().getId();
int id = event.getDevice().getId();
return owners[0] == id || partners[0] == id;
}
private void releaseBackPaddles() {
@@ -454,9 +503,32 @@ public final class PadBridge {
DeckControls.INSTANCE.setGrip(DeckControls.R4, false);
}
private void leave(int slot, int id) {
if (partners[slot] == NO_CONTROLLER) {
free(slot);
return;
}
Log.i(TAG, "player " + (slot + 1) + " Joy-Con (id " + id + ") left");
if (owners[slot] == id) owners[slot] = partners[slot];
partners[slot] = NO_CONTROLLER;
clearJoyCons(slot);
if (slotControllers.get(slot) == id) slotControllers.set(slot, owners[slot]);
if (activeControllerId == id) activeControllerId = owners[slot];
if (slot == 0) releaseBackPaddles();
stateFor(slot).clear();
publish(slot);
}
private static void clearJoyCons(int slot) {
slotJoyCons.set(slot * 2, NO_CONTROLLER);
slotJoyCons.set(slot * 2 + 1, NO_CONTROLLER);
}
private void free(int slot) {
Log.i(TAG, "player " + (slot + 1) + " (id " + owners[slot] + ") left");
owners[slot] = NO_CONTROLLER;
partners[slot] = NO_CONTROLLER;
clearJoyCons(slot);
slotControllers.set(slot, NO_CONTROLLER);
if (slot == 0) {
releaseBackPaddles();