Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions crates/pf-nx-app/src/core/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,10 +254,16 @@ impl GamepadType {
})
}

/// The dial's Controller type step: the shared order (`overlay_actions::next_pad_type`),
/// skipping the kinds this client offers no row for.
/// The dial's Controller type step: Automatic, the two Nintendo kinds this console's pads
/// are, then the shared order (`overlay_actions::next_pad_type`) over the kinds this client
/// offers. The shared order names no Nintendo kind yet (`docs/improvements.md`).
pub fn next_on_dial(self) -> Self {
let mut pref = self.to_core();
let mut pref = match self {
Self::Auto => return Self::JoyConPair,
Self::JoyConPair => return Self::SwitchPro,
Self::SwitchPro => punktfunk_core::config::GamepadPref::Auto,
other => other.to_core(),
};
loop {
pref = pf_client_core::overlay_actions::next_pad_type(pref);
if let Some(next) = Self::from_core(pref) {
Expand Down Expand Up @@ -356,7 +362,7 @@ pub struct GameEntry {
mod tests {
use super::*;

/// The dial steps the shared order over this client's rows; a Settings-only kind steps back.
/// The dial steps the Nintendo kinds, then the shared order over this client's rows.
#[test]
fn the_dial_steps_the_types_this_client_offers() {
let mut seen = vec![GamepadType::Auto];
Expand All @@ -369,12 +375,13 @@ mod tests {
seen,
[
GamepadType::Auto,
GamepadType::JoyConPair,
GamepadType::SwitchPro,
GamepadType::XboxOne,
GamepadType::DualSense,
GamepadType::DualShock4
]
);
assert_eq!(GamepadType::SwitchPro.next_on_dial(), GamepadType::Auto);
}

/// The saved record is the shared one plus this console's fields, in one flat object (plan D8):
Expand Down
16 changes: 14 additions & 2 deletions crates/pf-nx-app/src/platform/fake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ use std::sync::{Arc, Mutex};
use anyhow::Result;

use super::{
AudioOut, AudioPort, Display, Fit, FrameReport, Lifecycle, PadFeedback, PadSample, Pads, Refresh, Rgba, Storage,
StreamSpec, SystemEvent, VideoDecoders,
AudioOut, AudioPort, Display, Fit, FrameReport, Lifecycle, Motion, PadFeedback, PadSample, Pads, Refresh, Rgba,
Storage, StreamSpec, SystemEvent, TouchPoint, VideoDecoders,
};
use crate::core::caps::VideoCaps;
use crate::core::media::{VideoSink, VideoSinkCaps};
Expand Down Expand Up @@ -179,6 +179,10 @@ pub struct FakePads {
pub script: Arc<Mutex<VecDeque<Vec<PadSample>>>>,
pub feedback: Arc<Mutex<Vec<(u8, PadFeedback)>>>,
pub released: Arc<Mutex<u32>>,
/// Every pad's motion, held until changed.
pub motion: Arc<Mutex<Option<Motion>>>,
/// The fingers down, held until changed.
pub touches: Arc<Mutex<Vec<TouchPoint>>>,
/// The last batch, repeated while the script is empty: a held pad stays held.
last: Vec<PadSample>,
}
Expand All @@ -201,6 +205,14 @@ impl Pads for FakePads {
fn release_all(&mut self) {
*self.released.lock().expect("fake pads poisoned") += 1;
}

fn motion(&mut self, _slot: u8) -> Option<Motion> {
*self.motion.lock().expect("fake pads poisoned")
}

fn touches(&mut self, out: &mut Vec<TouchPoint>) {
out.clone_from(&self.touches.lock().expect("fake pads poisoned"));
}
}

/// A directory the test owns.
Expand Down
33 changes: 33 additions & 0 deletions crates/pf-nx-app/src/platform/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ pub struct DeviceInfo {
pub gpu: String,
/// How the UI layer draws: backend, size, and why it fell back to the CPU.
pub ui: String,
/// Launched as an applet (from the album), with a fraction of the title's memory (plan D13).
pub applet_mode: bool,
}

/// Refresh rate of the scan-out, in millihertz (60 000, 59 940).
Expand Down Expand Up @@ -202,6 +204,25 @@ pub enum PadKind {
SwitchPro,
}

/// One motion sample in the wire's frame, SDL's: +x right, +y up, +z toward the player.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Motion {
/// Rotation about each axis, rad/s.
pub gyro: [f32; 3],
/// In g; a pad lying still reads +1 on y.
pub accel: [f32; 3],
}

/// One finger on the console's own screen.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct TouchPoint {
/// Stable while the finger stays down.
pub id: u32,
/// 0.0..=1.0 across the screen from its top-left corner.
pub x: f32,
pub y: f32,
}

/// What the host asked a pad to do.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PadFeedback {
Expand All @@ -218,6 +239,18 @@ pub trait Pads: Send {

/// Stops every pad's motors.
fn release_all(&mut self);

/// The latest motion sample of the pad in `slot`, after a [`Self::poll`]; `None` without
/// a sensor.
fn motion(&mut self, _slot: u8) -> Option<Motion> {
None
}

/// The fingers on the screen now, replacing `out`'s contents. Nothing without a touch
/// screen, or while the screen is off in the dock.
fn touches(&mut self, out: &mut Vec<TouchPoint>) {
out.clear();
}
}

/// Where identity, settings, logs and bundles live.
Expand Down
24 changes: 17 additions & 7 deletions crates/pf-nx-app/src/runtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@
mod connect;
mod hud;
mod menu;
mod motion;
pub mod pads;
mod stream;
pub mod testrun;
mod touch;

use std::sync::atomic::{AtomicBool, Ordering};

Expand Down Expand Up @@ -92,13 +94,14 @@ pub fn run(platform: Platform) -> ! {
let flush = crate::logger::init_subscriber(&crate::services::paths::logs_dir(), log).ok();
install_panic_hook();
tracing::info!(
"punktfunk-switch {} on {} ({} firmware {}), gpu {}, ui {}",
"punktfunk-switch {} on {} ({} firmware {}), gpu {}, ui {}{}",
crate::core::build_id(),
device.platform,
device.model,
device.firmware,
device.gpu,
device.ui,
if device.applet_mode { ", applet mode" } else { "" },
);
punktfunk_core::client::set_client_label(&client_label(&device));
crate::core::caps::install(video.caps());
Expand Down Expand Up @@ -144,9 +147,13 @@ pub fn run(platform: Platform) -> ! {
lifecycle.exit()
}

/// What the first menu says when the title runs as an applet (plan D13).
const APPLET_MODE_NOTICE: &str =
"Opened from the Album, punktfunk has little memory and may close — hold R while starting a game to open it with full memory.";

/// The menu and the stream in turn, until one of them quits.
fn alternate(app: &mut App) -> Option<ExitPlan> {
let mut notice = None;
let mut notice = app.device.applet_mode.then(|| APPLET_MODE_NOTICE.to_string());
loop {
let outcome = match menu::run(app, notice.take()) {
Ok(outcome) => outcome,
Expand All @@ -170,14 +177,17 @@ fn client_label(device: &crate::platform::DeviceInfo) -> String {
format!("Switch {}", device.firmware).trim_end().to_string()
}

/// A panic on any thread goes to the log with its frames, then the process aborts.
/// A panic on any thread goes to the log, then its frames where the target can walk them, then
/// the process aborts. The message is flushed before the walk: on the console, which builds
/// without unwind tables, the walk itself aborts.
fn install_panic_hook() {
std::panic::set_hook(Box::new(|info| {
let thread = std::thread::current();
let name = thread.name().unwrap_or("unnamed");
tracing::error!("PANIC on thread {name:?}: {info}");
crate::logger::flush();
let backtrace = std::backtrace::Backtrace::force_capture();
tracing::error!(
"PANIC on thread {:?}: {info}\n{backtrace}",
std::thread::current().name().unwrap_or("unnamed"),
);
tracing::error!("PANIC on thread {name:?}, frames:\n{backtrace}");
crate::logger::flush();
}));
}
Expand Down
130 changes: 130 additions & 0 deletions crates/pf-nx-app/src/runtime/motion.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
//! Each pad's gyro and accelerometer onto its pad on the host, in the wire's units. Pure: samples
//! in, rich input out.

use punktfunk_core::input::gamepad::{MOTION_ACCEL_LSB_PER_G, MOTION_GYRO_LSB_PER_DEG_S};
use punktfunk_core::quic::RichInput;

use super::pads::SLOTS;
use crate::platform::Motion;

/// The wire's gyro counts per rad/s.
const GYRO_LSB_PER_RAD_S: f32 = MOTION_GYRO_LSB_PER_DEG_S as f32 * 180.0 / std::f32::consts::PI;

/// A sample in the wire's counts, `(gyro, accel)`.
type Counts = ([i16; 3], [i16; 3]);

fn counts(m: &Motion) -> Counts {
let scale = |v: [f32; 3], per: f32| v.map(|c| (c * per).clamp(-32768.0, 32767.0) as i16);
(
scale(m.gyro, GYRO_LSB_PER_RAD_S),
scale(m.accel, MOTION_ACCEL_LSB_PER_G as f32),
)
}

/// What each pad last sent.
#[derive(Default)]
pub struct MotionRouter {
sent: [Option<Counts>; SLOTS],
}

impl MotionRouter {
/// One pad's latest sample, `None` when the pad is gone: the rich input to send when it
/// changed. A pad's first sample is logged, so a run shows the frame hid reports in.
pub fn step(&mut self, pad: u8, sample: Option<Motion>) -> Option<RichInput> {
let slot = self.sent.get_mut(usize::from(pad))?;
let Some(m) = sample else {
*slot = None;
return None;
};
let now = counts(&m);
if *slot == Some(now) {
return None;
}
if slot.is_none() {
tracing::info!("pad {pad}: motion, gyro {:?} rad/s, accel {:?} g", m.gyro, m.accel);
}
*slot = Some(now);
Some(RichInput::Motion {
pad,
gyro: now.0,
accel: now.1,
})
}

/// Stops every pad turning on the host, gravity kept: the host holds the last rate it got.
pub fn still_all(&mut self, out: &mut Vec<RichInput>) {
for (pad, slot) in self.sent.iter_mut().enumerate() {
if let Some((gyro, accel)) = slot {
if *gyro != [0; 3] {
*gyro = [0; 3];
out.push(RichInput::Motion {
pad: pad as u8,
gyro: [0; 3],
accel: *accel,
});
}
}
}
}
}

#[cfg(test)]
mod tests {
use super::*;

fn still() -> Motion {
Motion {
gyro: [0.0; 3],
accel: [0.0, 1.0, 0.0],
}
}

#[test]
fn samples_go_out_in_the_wire_units_once_each() {
let mut r = MotionRouter::default();
let turning = Motion {
gyro: [std::f32::consts::PI, 0.0, -100.0],
..still()
};
let Some(RichInput::Motion { pad, gyro, accel }) = r.step(1, Some(turning)) else {
panic!("a first sample goes out");
};
// π rad/s is 180 °/s, 20 counts each; past the range clamps.
assert_eq!((pad, gyro, accel), (1, [3600, 0, -32768], [0, 10_000, 0]));
assert!(r.step(1, Some(turning)).is_none(), "an unchanged sample stays home");
}

#[test]
fn still_all_stops_the_turning_and_keeps_gravity() {
let mut r = MotionRouter::default();
let turning = Motion {
gyro: [1.0, 0.0, 0.0],
..still()
};
r.step(0, Some(turning));
r.step(2, Some(still()));
let mut out = Vec::new();
r.still_all(&mut out);
assert_eq!(
out,
[RichInput::Motion {
pad: 0,
gyro: [0; 3],
accel: [0, 10_000, 0]
}]
);
out.clear();
r.still_all(&mut out);
assert!(out.is_empty());
assert!(r.step(0, Some(turning)).is_some(), "turning again goes out");
}

#[test]
fn a_pad_that_leaves_starts_over() {
let mut r = MotionRouter::default();
r.step(0, Some(still()));
assert!(r.step(0, None).is_none());
assert!(r.step(0, Some(still())).is_some());
assert!(r.step(9, Some(still())).is_none(), "no such slot");
}
}
54 changes: 54 additions & 0 deletions crates/pf-nx-app/src/runtime/pads.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,20 @@ impl PadRouter {
}
}

/// Unplugs every pad from the host and plugs it in again as `kind`: the dial's Controller
/// type, for this stream only. The slots stay, so a button held through it is not pressed
/// again: the A that picked the type would pick the next one, a frame later, until let go.
pub fn replug_all(&mut self, kind: GamepadType, wire: &mut Vec<InputEvent>) {
for (index, slot) in self.slots.iter_mut().enumerate() {
if let Some(slot) = slot {
let pad = index as u8;
release_into(pad, &slot.last, wire);
wire.push(remove_event(pad));
wire.extend(arrival_event(resolve_kind(kind, slot.last.kind), pad));
}
}
}

/// Lets go of everything the host holds and forgets the pads, so the next step re-declares
/// them. For focus loss and every way out of a stream.
pub fn release_all(&mut self, wire: &mut Vec<InputEvent>) {
Expand Down Expand Up @@ -383,6 +397,46 @@ mod tests {
assert!(routed.is_empty(), "re-arms only after a release");
}

#[test]
fn replug_plugs_in_as_the_new_kind_and_a_held_button_stays_held() {
let mut r = PadRouter::default();
let (mut wire, mut routed) = (Vec::new(), Vec::new());
let now = Instant::now();
r.step(
&[pad(gamepad::BTN_A)],
now,
false,
GamepadType::Auto,
&mut wire,
&mut routed,
);
wire.clear();
r.replug_all(GamepadType::DualSense, &mut wire);
let kinds: Vec<InputKind> = wire.iter().map(|e| e.kind).collect();
assert_eq!(
kinds,
[
InputKind::GamepadButton,
InputKind::GamepadRemove,
InputKind::GamepadArrival
]
);
assert_eq!(wire[2].code, u32::from(GamepadType::DualSense.to_core().to_u8()));
wire.clear();
r.step(
&[pad(gamepad::BTN_A)],
now,
false,
GamepadType::DualSense,
&mut wire,
&mut routed,
);
assert!(
wire.is_empty() && routed.is_empty(),
"the held button is not a new press"
);
}

#[test]
fn release_all_centres_sticks_and_lifts_buttons() {
let mut r = PadRouter::default();
Expand Down
Loading
Loading