mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-19 04:46:08 +00:00
feat: add immersive Quest SteamVR to the standard app (#910)
This commit is contained in:
1 parent
d21466be6b
commit
2847910f22
73 files changed
+5916
-289
No files matched your search
@@ -177,6 +177,11 @@ class X:
|
||||
return list(struct.unpack("<%dI" % n, data))
|
||||
return data
|
||||
|
||||
def cardinals(self, window, name, values):
|
||||
self.s.sendall(struct.pack("<BBHIIIB3xI", 18, 0, 6 + len(values), window,
|
||||
self.atom(name), self.atom("CARDINAL"), 32, len(values))
|
||||
+ struct.pack("<%dI" % len(values), *values))
|
||||
|
||||
|
||||
def windows(x):
|
||||
"""Top-level windows that are mapped or carry an app id: what gamescope picks focus from."""
|
||||
@@ -249,6 +254,42 @@ def focus_snapshot():
|
||||
return snap
|
||||
|
||||
|
||||
def vr_scene_app(path=Path('/run/droiddeck/droiddeck-steamvr/scene-focus.json'), proc=Path('/proc')):
|
||||
"""Only a live SteamVR scene with its dashboard hidden may claim game focus."""
|
||||
try:
|
||||
state = json.loads(path.read_text())
|
||||
server, scene = int(state['serverPid']), int(state['scenePid'])
|
||||
if server <= 0 or scene <= 0 or state['dashboard'] is not False:
|
||||
return None
|
||||
if (proc / str(server) / 'comm').read_text().strip() != 'vrserver':
|
||||
return None
|
||||
for entry in (proc / str(scene) / 'environ').read_bytes().split(b'\0'):
|
||||
if entry.startswith(b'SteamAppId='):
|
||||
app = int(entry.split(b'=', 1)[1])
|
||||
return app if 0 < app < 2**32 else None
|
||||
except (OSError, ValueError, TypeError, KeyError):
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
class VrSceneFocus:
|
||||
def __init__(self):
|
||||
self.original = None
|
||||
self.written = None
|
||||
|
||||
def order(self, current, focusable, app):
|
||||
if app is None or app not in focusable:
|
||||
restore = self.original if self.written == current else None
|
||||
self.original = self.written = None
|
||||
return restore
|
||||
if current and current[0] == app:
|
||||
return None
|
||||
if self.original is None:
|
||||
self.original = list(current)
|
||||
self.written = [app] + [item for item in current if item != app]
|
||||
return self.written
|
||||
|
||||
|
||||
class FocusWatcher(threading.Thread):
|
||||
"""Rewrites focus.json when gamescope's focus properties change, and every few seconds when
|
||||
the windows do (a window can change without any root property moving)."""
|
||||
@@ -259,15 +300,28 @@ class FocusWatcher(threading.Thread):
|
||||
self.changed = threading.Event()
|
||||
self.last = None
|
||||
self.seq = 0
|
||||
self.vr_focus = VrSceneFocus()
|
||||
|
||||
def run(self):
|
||||
threading.Thread(target=self.listen, daemon=True, name="focus-events").start()
|
||||
last_app, last_snapshot = None, 0
|
||||
while True:
|
||||
self.changed.wait(timeout=5)
|
||||
notified = self.changed.wait(timeout=0.5)
|
||||
self.changed.clear()
|
||||
app = vr_scene_app()
|
||||
if not notified and app == last_app and time.monotonic() - last_snapshot < 5:
|
||||
continue
|
||||
last_app, last_snapshot = app, time.monotonic()
|
||||
time.sleep(0.2)
|
||||
try:
|
||||
snap = focus_snapshot()
|
||||
order = self.vr_focus.order(snap.get('baselayerAppIds', []), snap.get('focusableApps', []), app)
|
||||
if order is not None:
|
||||
x = X(os.environ['DISPLAY'])
|
||||
try:
|
||||
x.cardinals(x.root, 'GAMESCOPECTRL_BASELAYER_APPID', order)
|
||||
finally:
|
||||
x.close()
|
||||
except (OSError, AgentError) as e:
|
||||
log("focus snapshot failed: %s" % e)
|
||||
time.sleep(2)
|
||||
|
||||
@@ -7,13 +7,21 @@ driver=$vrdir/droiddeck
|
||||
layer=$vrdir/layer
|
||||
logs=$HOME/.local/share/Steam/logs
|
||||
state=${XDG_RUNTIME_DIR:-/tmp}/droiddeck-steamvr
|
||||
umask 077
|
||||
mkdir -p "$state"
|
||||
chmod 700 "$state"
|
||||
|
||||
PKG_URL=https://steamdeck-packages.steamos.cloud/archlinux-deckard-hotfixes/release/0.3.x/deckard-steamvr-rel-r25358740%2B28b72a4f-1-aarch64.pkg.tar.zst
|
||||
PKG_SHA256=90a600775eb3e8856dc475f83166a93a290a0b1f3b4e82a69c8e2a8f06b9ddc9
|
||||
|
||||
running() { pgrep -x vrserver >/dev/null 2>&1; }
|
||||
installed() { [ -x "$steamvr/bin/linuxarm64/vrstartup" ]; }
|
||||
quest_settings() {
|
||||
backup=$HOME/.local/share/droiddeck/steamvr-quest-settings.json
|
||||
[ "$1" != restore ] || [ -f "$backup" ] || return 0
|
||||
python3 "${DROIDDECK_VR_SETTINGS_HELPER:-/usr/local/bin/droiddeck-steamvr-settings}" "$1" \
|
||||
"$HOME/.local/share/Steam/config/steamvr.vrsettings" "$backup"
|
||||
}
|
||||
|
||||
stop() {
|
||||
rm -f "$state/active"
|
||||
@@ -21,7 +29,16 @@ stop() {
|
||||
for p in $(pgrep -x "$n"); do kill "$p" 2>/dev/null; done
|
||||
done
|
||||
for p in $(pgrep -f "$steamvr/bin/linuxarm64/vrcompositor-launcher"); do kill "$p" 2>/dev/null; done
|
||||
return 0
|
||||
attempts=0
|
||||
while pgrep -x 'vrserver|vrcompositor' >/dev/null 2>&1; do
|
||||
attempts=$((attempts + 1))
|
||||
if [ "$attempts" = 10 ]; then
|
||||
for p in $(pgrep -x 'vrserver|vrcompositor'); do kill -KILL "$p" 2>/dev/null; done
|
||||
fi
|
||||
[ "$attempts" -lt 20 ] || { echo 'SteamVR did not stop; preferences remain backed up' >&2; return 1; }
|
||||
sleep 0.1
|
||||
done
|
||||
quest_settings restore
|
||||
}
|
||||
|
||||
case "${1:-status}" in
|
||||
@@ -52,12 +69,12 @@ install)
|
||||
echo "SteamVR installed in $steamvr"
|
||||
;;
|
||||
stop)
|
||||
stop
|
||||
stop || exit 1
|
||||
;;
|
||||
start)
|
||||
installed || { echo "SteamVR is not installed (droiddeck-steamvr install)"; exit 1; }
|
||||
[ -f "$driver/bin/linuxarm64/driver_droiddeck.so" ] || { echo "the Cardboard driver is missing from $driver"; exit 1; }
|
||||
stop
|
||||
stop || exit 1
|
||||
sleep 1
|
||||
mkdir -p "$HOME/.config/openvr" "$HOME/.config/openxr/1" "$logs" "$HOME/.local/share/Steam/config"
|
||||
cat > "$HOME/.config/openvr/openvrpaths.vrpath" <<JSON
|
||||
@@ -75,6 +92,29 @@ JSON
|
||||
export VK_LAYER_PATH="$layer${VK_LAYER_PATH:+:$VK_LAYER_PATH}"
|
||||
export VK_INSTANCE_LAYERS="VK_LAYER_DROIDDECK_vr${VK_INSTANCE_LAYERS:+:$VK_INSTANCE_LAYERS}"
|
||||
export VK_LOADER_LAYERS_DISABLE="${VK_LOADER_LAYERS_DISABLE:-~implicit~}"
|
||||
if [ -S "/run/droiddeck/droiddeck-xr-frames" ] && [ -z "${DROIDDECK_VR_PRESENT:-}" ]; then
|
||||
export DROIDDECK_VR_PRESENT=questwsi
|
||||
fi
|
||||
if [ "${DROIDDECK_VR_PRESENT:-}" = questwsi ]; then
|
||||
quest_settings apply || exit 1
|
||||
startup_handed_off=0
|
||||
trap '[ "$startup_handed_off" = 1 ] || quest_settings restore' EXIT
|
||||
# The pinned Frame package's CVP constructor exits on Quest's unsupported SoC.
|
||||
cvp=$steamvr/drivers/cv/bin/linuxarm64/libArcturusPerception.so
|
||||
if [ -f "$cvp" ]; then
|
||||
disabled=$cvp.droiddeck-disabled
|
||||
if [ -e "$disabled" ]; then disabled=$(mktemp "$disabled.XXXXXX") || exit 1; fi
|
||||
mv "$cvp" "$disabled" || exit 1
|
||||
echo "Disabled Frame-only CVP backend for Quest; SteamVR uses its normal compositor"
|
||||
fi
|
||||
fi
|
||||
if [ "${DROIDDECK_VR_PRESENT:-}" = questframes ]; then
|
||||
export DROIDDECK_VR_PRODUCER_LEASE=${DROIDDECK_VR_PRODUCER_LEASE:-1}
|
||||
fi
|
||||
if [ -z "${DROIDDECK_VR_DISPLAY_MODE:-}" ] && [ -x "$driver/bin/linuxarm64/xr-display-mode" ]; then
|
||||
mode=$("$driver/bin/linuxarm64/xr-display-mode") || mode=
|
||||
if [ -n "$mode" ]; then export DROIDDECK_VR_DISPLAY_MODE="$mode"; fi
|
||||
fi
|
||||
|
||||
shims=$state/shims
|
||||
mkdir -p "$shims"
|
||||
@@ -86,7 +126,10 @@ JSON
|
||||
|
||||
: > "$state/active"
|
||||
cd "$steamvr/bin/linuxarm64" || exit 1
|
||||
setsid ./vrstartup > "$state/vrstartup.log" 2>&1 < /dev/null &
|
||||
startup_log=$logs/droiddeck-vrstartup.log
|
||||
ln -sf "$startup_log" "$state/vrstartup.log"
|
||||
setsid ./vrstartup > "$startup_log" 2>&1 < /dev/null &
|
||||
startup_handed_off=1
|
||||
echo "SteamVR starting; logs in $logs and $state/vrstartup.log"
|
||||
;;
|
||||
*)
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
[ "$#" -gt 0 ] || { echo 'usage: droiddeck-steamvr-game COMMAND [ARG...]' >&2; exit 2; }
|
||||
pgrep -x vrserver >/dev/null 2>&1 || {
|
||||
echo 'Start SteamVR before launching a game with droiddeck-steamvr-game.' >&2
|
||||
exit 1
|
||||
}
|
||||
vrdir=${DROIDDECK_VR_DIR:-/usr/local/lib/droiddeck-vr}
|
||||
export VK_LAYER_PATH="$vrdir/layer${VK_LAYER_PATH:+:$VK_LAYER_PATH}"
|
||||
export VK_INSTANCE_LAYERS="VK_LAYER_DROIDDECK_vr${VK_INSTANCE_LAYERS:+:$VK_INSTANCE_LAYERS}"
|
||||
export VK_LOADER_LAYERS_DISABLE="${VK_LOADER_LAYERS_DISABLE:-~implicit~}"
|
||||
# Quest's guest GPU images use Vulkan sharing rather than DMA-BUF modifiers.
|
||||
if [ -S "/run/droiddeck/droiddeck-xr-frames" ]; then
|
||||
export gamescope_vr_use_modifiers=${gamescope_vr_use_modifiers:-false}
|
||||
fi
|
||||
export gamescope_vr_nudge_to_visible=${gamescope_vr_nudge_to_visible:-true}
|
||||
exec gamescope --backend openvr \
|
||||
--vr-overlay-key "gamescope.droiddeck.game.$$" \
|
||||
--vr-overlay-default-name 'DroidDeck game' \
|
||||
--vr-overlay-show-immediately --vr-overlay-physical-width 2.4 -- "$@"
|
||||
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/python3
|
||||
"""Preserve SteamVR preferences across Quest's required compositor overrides."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
OVERRIDES = {'enableLinuxVulkanAsync': True, 'motionSmoothing': False}
|
||||
|
||||
|
||||
def read(path):
|
||||
try:
|
||||
with path.open() as source:
|
||||
settings = json.load(source)
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
if not isinstance(settings, dict) or not isinstance(settings.get('steamvr', {}), dict):
|
||||
raise ValueError('Invalid SteamVR settings object')
|
||||
return settings
|
||||
|
||||
|
||||
def write(path, value):
|
||||
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
temporary = path.with_name(path.name + '.tmp')
|
||||
with os.fdopen(os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600), 'w') as destination:
|
||||
json.dump(value, destination, indent=3)
|
||||
destination.write('\n')
|
||||
os.replace(temporary, path)
|
||||
|
||||
|
||||
def saved_preferences(path):
|
||||
try:
|
||||
backup = read(path)
|
||||
if not isinstance(backup.get('section'), bool) or not isinstance(backup.get('values'), dict):
|
||||
raise ValueError('invalid backup object')
|
||||
for key in OVERRIDES:
|
||||
entry = backup['values'].get(key)
|
||||
if not isinstance(entry, list) or len(entry) != 2 or not isinstance(entry[0], bool):
|
||||
raise ValueError('invalid saved preference: ' + key)
|
||||
return backup
|
||||
except ValueError as error:
|
||||
raise ValueError(f'Invalid preference backup {path}; repair the saved section/values and retry restore. '
|
||||
'The backup and current preferences have been preserved.') from error
|
||||
|
||||
|
||||
def update(operation, settings_path, backup_path):
|
||||
settings = read(settings_path)
|
||||
if operation == 'apply':
|
||||
if backup_path.exists():
|
||||
saved_preferences(backup_path)
|
||||
else:
|
||||
section = settings.get('steamvr', {})
|
||||
write(backup_path, {'section': 'steamvr' in settings,
|
||||
'values': {key: [key in section, section.get(key)] for key in OVERRIDES}})
|
||||
settings.setdefault('steamvr', {}).update(OVERRIDES)
|
||||
write(settings_path, settings)
|
||||
elif operation == 'restore':
|
||||
if not backup_path.exists():
|
||||
return
|
||||
backup = saved_preferences(backup_path)
|
||||
section = settings.setdefault('steamvr', {})
|
||||
for key in OVERRIDES:
|
||||
present, value = backup['values'][key]
|
||||
if present:
|
||||
section[key] = value
|
||||
else:
|
||||
section.pop(key, None)
|
||||
if not section and not backup['section']:
|
||||
settings.pop('steamvr')
|
||||
write(settings_path, settings)
|
||||
backup_path.unlink()
|
||||
else:
|
||||
raise ValueError('Expected apply or restore')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
update(sys.argv[1], Path(sys.argv[2]), Path(sys.argv[3]))
|
||||
except (OSError, ValueError, KeyError, IndexError, TypeError) as error:
|
||||
sys.exit('Could not update SteamVR settings: ' + str(error))
|
||||
Reference in new issue
Block a user