diff --git a/CHANGELOG.md b/CHANGELOG.md
index d582491a18..2a372d98db 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,10 @@ Built with Unity 6.5
### Added
+- Windows Open Pinball Device support for Pinscape Pico with named nudge axes, firmware scale presets and preassigned cabinet buttons. The updated NativeInput library is required for OPD discovery.
+
+- Shared Pinscape joystick nudge setup and sampled rest calibration in the editor and Player, with explicit velocity presets, device-axis selection, editable SI scales, and sensor state reset on disconnect.
+
- Closed shared cabinet output roles with independent LCD/HD game display routing and preserved custom scene bindings.
- Cabinet output content rotation, mirroring, and explicit-load inset composition with asymmetric GPU validation.
diff --git a/VisualPinball.Engine/VisualPinball.Engine.csproj b/VisualPinball.Engine/VisualPinball.Engine.csproj
index 8caa6df913..2984aa52af 100644
--- a/VisualPinball.Engine/VisualPinball.Engine.csproj
+++ b/VisualPinball.Engine/VisualPinball.Engine.csproj
@@ -15,7 +15,7 @@
https://visualpinball.org
icon.png
LICENSE
- 0.0.5
+ 0.0.6
diff --git a/VisualPinball.Unity/Documentation~/creators-guide/manual/nudging.md b/VisualPinball.Unity/Documentation~/creators-guide/manual/nudging.md
index 817bfcd197..459c6d39a2 100644
--- a/VisualPinball.Unity/Documentation~/creators-guide/manual/nudging.md
+++ b/VisualPinball.Unity/Documentation~/creators-guide/manual/nudging.md
@@ -88,26 +88,33 @@ Sensor types mean:
Most Xbox-style controllers do not provide accelerometer data for nudging. Map
their sticks as `GamepadIntent`.
-KL25Z/Pinscape boards are cabinet sensors. Map their acceleration axes, then use
-mount rotation and mirror to match how the board is installed in the cabinet.
-The available rotations are 0, 90, 180, and 270 degrees. Mirror flips the board X
-axis before rotation.
-
-## Editor Calibration
-
-For direct play in the editor, use the `SimulationThreadComponent` inspector:
-
-1. Enter Play Mode with the cabinet sensor connected.
-2. Use auto-configuration if the first device should be mapped as the cabinet
- sensor.
-3. Set mount rotation and mirror until graph movement matches cabinet movement.
-4. Keep the cabinet still and calibrate sensor centers.
-5. Nudge the cabinet lightly and watch the input graph.
-
-Calibration captures the current resting raw value as zero. It does not remove
-spikes, pick better axes, or tune the overall gain. If the graph spikes while the
-cabinet is still, check the mapped axes, increase dead zone, reduce scale, or
-inspect the physical board/device signal.
+KL25Z/Pinscape boards are cabinet sensors. Map their acceleration axes, then use mount rotation and mirror to match how the board is installed in the cabinet. The available rotations are 0, 90, 180, and 270 degrees. Mirror flips the board X axis before rotation.
+
+### Pinscape Joystick Setup
+
+On Windows, recognized Pinscape joystick layouts offer acceleration and velocity presets in the Player's Nudge settings and the `SimulationThreadComponent` inspector. Acceleration uses X/Y with an initial full-scale value of 9.80665 m/s² (1 g). Set the scale to match the range configured in firmware. The Player offers 1, 2, 4, and 8 g presets and an editable custom scale. Negative scale reverses an axis.
+
+Velocity setup uses RX/RY with the default Pinscape joystick full-scale value of 0.2048 m/s. Enable velocity reporting in firmware before selecting this preset. Pinscape Pico can assign arbitrary signals to joystick axes, so use the named axis selectors and custom scales when its layout differs from the standard Pinscape layout. Velocity mode uses the reported integrated velocity directly through VPE's cabinet sensor model.
+
+Auto-map recognizes cabinet layouts and explicitly typed accelerometer axes. Generic joystick X/Y axes require manual assignment. The Player adds a sensor slot when auto-mapping and preserves existing slots. The inspector's setup buttons configure its first sensor slot. Player settings are saved in the cabinet profile and applied to loaded tables.
+
+### Pinscape Pico Open Pinball Device Setup
+
+Enable Open Pinball Device in the Pico firmware. With an OPD-capable Windows NativeInput library, VPE lists the Pico with an OPD suffix and named nudge axes. Auto-map prefers OPD when both interfaces are present. If you already mapped the Pico's joystick axes, select the OPD preset in that sensor slot to switch interfaces and then calibrate again.
+
+Auto-map uses acceleration. Choose the velocity preset if the firmware reports integrated X/Y nudge velocity. The Pico velocity preset uses 0.32768 m/s at full scale, matching the default firmware `vscale` of 100 counts per mm/s. Set custom scales if you use a different `vscale` or accelerometer range. The report format allows firmware to send zero for unused fields, so confirm which signals your firmware exposes.
+
+Preassigned OPD buttons use the existing VPE cabinet actions, including digital nudge and physical tilt. Physical tilt follows the table's tilt-bob routing and the Player's Tilt Source setting. OPD also exposes plunger position and speed for diagnostics. Mechanical plunger gameplay and generic OPD button assignments need their own input routing.
+
+For a local checkout, build the matching NativeInput branch and install its Windows DLL in `VisualPinball.Unity/Plugins/win-x64` before starting Unity. The default NuGet dependency supplies OPD after an OPD-capable NativeInput release is published and pinned. Linux and macOS use their existing keyboard backends.
+
+### Rest Calibration
+
+In the Player, open the Nudge settings and choose Calibrate under Rest Calibration. This works from the main menu before loading a table. In the editor, enter Play Mode and choose Calibrate Centers in the `SimulationThreadComponent` inspector.
+
+Keep the cabinet still for about one second. Calibration averages fresh input reports for every active mapped channel. It checks sample count, sample duration, and input variation before updating any center. A disconnected device, stale reports, or excessive motion causes calibration to fail with the saved centers intact. Changing settings or leaving the tab cancels a running calibration.
+
+Calibration adjusts neutral centers. Gain, axis selection, mount orientation, and dead zone remain explicit settings. Use the signed raw input labels to check side and forward directions, then check the cabinet acceleration/offset graph while a table runs. A disconnected sensor is cleared on the physics thread and resumes from rest when all of its mapped devices reconnect.
## Shipping Tables
diff --git a/VisualPinball.Unity/Documentation~/developer-guide/accelerometer-input-design.md b/VisualPinball.Unity/Documentation~/developer-guide/accelerometer-input-design.md
index 076659190f..42fc3d9d76 100644
--- a/VisualPinball.Unity/Documentation~/developer-guide/accelerometer-input-design.md
+++ b/VisualPinball.Unity/Documentation~/developer-guide/accelerometer-input-design.md
@@ -6,7 +6,9 @@ description: Proposed architecture for adding accelerometer-based nudging to VPE
# Accelerometer Input Design
-This page describes the proposed design for adding accelerometer-based nudging to VPE. It covers the intended runtime architecture, where the work should land in the codebase, how Open Pinball Device support should fit into the plan, and how calibration should work for both velocity-capable and legacy-style devices.
+This page records an earlier design proposal. VPE now has Windows HID joystick and Open Pinball Device input, cabinet sensor fusion, editor and Player setup, and sampled rest calibration. See [Nudging](xref:nudging) and [Nudge System](nudge-system.md) for the implementation. Cross-platform analog backends are follow-up work.
+
+The proposal below describes the original design for adding accelerometer-based nudging to VPE. It covers the intended runtime architecture, where the work should land in the codebase, how Open Pinball Device support should fit into the plan, and how calibration should work for both velocity-capable and legacy-style devices.
## Summary
diff --git a/VisualPinball.Unity/VisualPinball.Unity.Editor/Simulation/SimulationThreadComponentInspector.cs b/VisualPinball.Unity/VisualPinball.Unity.Editor/Simulation/SimulationThreadComponentInspector.cs
index 7324acc253..c2a025c2f4 100644
--- a/VisualPinball.Unity/VisualPinball.Unity.Editor/Simulation/SimulationThreadComponentInspector.cs
+++ b/VisualPinball.Unity/VisualPinball.Unity.Editor/Simulation/SimulationThreadComponentInspector.cs
@@ -51,6 +51,9 @@ public sealed class SimulationThreadComponentInspector : UnityEditor.Editor
private MessageType _statusType = MessageType.Info;
private GUIStyle _graphLegendStyle;
private double _lastGraphSampleTime;
+ private NudgeSensorCalibration _calibration;
+ private List _calibrationSensors;
+ private double _calibrationStart;
///
/// Draws default simulation fields plus live nudge calibration controls for
@@ -65,6 +68,7 @@ public override void OnInspectorGUI()
serializedObject.ApplyModifiedProperties();
if (targets.Length == 1 && target is SimulationThreadComponent component) {
+ if (changed) _calibration = null;
if (changed && Application.isPlaying) {
component.ApplyNudgeSensorSettings();
}
@@ -90,6 +94,7 @@ private void DrawNudgeCalibration(SimulationThreadComponent component)
EditorGUILayout.LabelField("Nudge Calibration", EditorStyles.boldLabel);
if (!Application.isPlaying) {
+ _calibration = null;
EditorGUILayout.HelpBox("Enter Play Mode to read native input devices and calibrate the current sensor centers.", MessageType.Info);
return;
}
@@ -98,6 +103,24 @@ private void DrawNudgeCalibration(SimulationThreadComponent component)
EditorGUILayout.LabelField("Input Thread", $"{component.InputThreadActualHz:0.#} Hz / target {component.InputThreadTargetHz:0.#} Hz");
var devices = component.ListNudgeInputDevices();
+ UpdateCalibration(component, devices);
+ foreach (var device in devices) {
+ if (NudgeSensorSetup.TryCreateGamepadSensor(device, out _)) {
+ EditorGUILayout.LabelField(device.Name, EditorStyles.miniBoldLabel);
+ if (GUILayout.Button("Map Left Stick")) ApplyNudgePreset(component, device, false);
+ continue;
+ }
+ var opd = NudgeSensorSetup.IsOpenPinballDevice(device);
+ if (!device.IsConnected || (!opd && !NudgeSensorSetup.IsPinscape(device))) continue;
+ EditorGUILayout.LabelField(device.Name, EditorStyles.miniBoldLabel);
+ EditorGUILayout.HelpBox(opd
+ ? "Open Pinball Device. Select Velocity if enabled in firmware. Check the configured full-scale range before play."
+ : "Standard Pinscape layout. Select Velocity only after enabling RX/RY velocity in firmware. Check the mapped full-scale range before play.", MessageType.Info);
+ EditorGUILayout.BeginHorizontal();
+ if (GUILayout.Button("Acceleration")) ApplyNudgePreset(component, device, false);
+ if (GUILayout.Button("Velocity")) ApplyNudgePreset(component, device, true);
+ EditorGUILayout.EndHorizontal();
+ }
if (devices.Count == 0) {
EditorGUILayout.HelpBox("No native input devices are visible. Check that native input is enabled and that the device was connected before polling started.", MessageType.Warning);
} else {
@@ -108,7 +131,8 @@ private void DrawNudgeCalibration(SimulationThreadComponent component)
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
EditorGUI.BeginDisabledGroup(devices.Count == 0);
- if (GUILayout.Button("Auto-map First Device")) {
+ if (GUILayout.Button("Auto-map Cabinet Sensor")) {
+ _calibration = null;
Undo.RecordObject(component, "Auto-map nudge sensor");
if (component.TryAutoConfigureFirstCabinetSensor(out var message)) {
SetStatus(message, MessageType.Info);
@@ -121,20 +145,18 @@ private void DrawNudgeCalibration(SimulationThreadComponent component)
EditorGUI.BeginDisabledGroup(devices.Count == 0 || component.NudgeSensors == null || component.NudgeSensors.Count == 0);
if (GUILayout.Button("Calibrate Centers")) {
- Undo.RecordObject(component, "Calibrate nudge sensor centers");
- var calibrated = component.CalibrateNudgeSensorCenters();
- if (calibrated > 0) {
- SetStatus($"Calibrated {calibrated} mapped nudge channel(s).", MessageType.Info);
- EditorUtility.SetDirty(component);
- } else {
- SetStatus("No mapped channels matched the currently visible devices.", MessageType.Warning);
- }
+ _calibrationSensors = CabinetNudgeSensorSettings.FromSimulationThreadSensors(component.NudgeSensors)
+ .ConvertAll(sensor => sensor.ToEngineConfig());
+ _calibration = new NudgeSensorCalibration(_calibrationSensors, devices);
+ _calibrationStart = EditorApplication.timeSinceStartup;
+ SetStatus("Calibrating. Keep the cabinet still...", MessageType.Info);
}
EditorGUI.EndDisabledGroup();
EditorGUILayout.EndHorizontal();
EditorGUI.BeginDisabledGroup(component.NudgeSensors == null || component.NudgeSensors.Count == 0);
if (GUILayout.Button("Reset Centers")) {
+ _calibration = null;
Undo.RecordObject(component, "Reset nudge sensor centers");
var reset = component.ResetNudgeSensorCenters();
SetStatus(reset > 0 ? "Cleared nudge sensor raw centers." : "No nudge sensors to reset.", MessageType.Info);
@@ -147,6 +169,51 @@ private void DrawNudgeCalibration(SimulationThreadComponent component)
}
}
+ private void UpdateCalibration(SimulationThreadComponent component, IReadOnlyList devices)
+ {
+ if (_calibration == null) return;
+ _calibration.Sample(devices);
+ if (EditorApplication.timeSinceStartup - _calibrationStart < 1.2) return;
+ var success = _calibration.TryComplete(out var message);
+ _calibration = null;
+ if (success) {
+ Undo.RecordObject(component, "Calibrate nudge sensor centers");
+ component.NudgeSensors = _calibrationSensors.ConvertAll(sensor => CabinetNudgeSensorSettings.From(sensor).ToSimulationThreadConfig());
+ component.ApplyNudgeSensorSettings();
+ EditorUtility.SetDirty(component);
+ }
+ _calibrationSensors = null;
+ SetStatus(message, success ? MessageType.Info : MessageType.Warning);
+ }
+
+ private void ApplyNudgePreset(SimulationThreadComponent component, NativeInputDeviceInfo device, bool velocity)
+ {
+ var gamepad = NudgeSensorSetup.TryCreateGamepadSensor(device, out var sensor);
+ if (!gamepad && !NudgeSensorSetup.TryCreateCabinetPreset(device, velocity, out sensor)) {
+ SetStatus("The required axes are unavailable.", MessageType.Warning);
+ return;
+ }
+ _calibration = null;
+ Undo.RecordObject(component, "Map nudge sensor");
+ component.NudgeSensors ??= new List();
+ if (component.NudgeSensors.Count > 0) {
+ var old = component.NudgeSensors[0];
+ if (old != null) {
+ sensor.mountRotation = (int)old.MountRotation;
+ sensor.mountMirror = old.MountMirror;
+ sensor.strength = old.Strength;
+ sensor.cabinetMassKg = old.CabinetMassKg;
+ }
+ component.NudgeSensors[0] = sensor.ToSimulationThreadConfig();
+ } else {
+ component.NudgeSensors.Add(sensor.ToSimulationThreadConfig());
+ }
+ component.ApplyNudgeSensorSettings();
+ EditorUtility.SetDirty(component);
+ SetStatus(gamepad ? "Mapped the left stick to the first sensor slot."
+ : "Mapped the first sensor slot. Check the range and calibrate at rest.", MessageType.Info);
+ }
+
///
/// Lists visible native input devices and their first few axes.
///
diff --git a/VisualPinball.Unity/VisualPinball.Unity.Test/Input/NudgeSensorSetupTests.cs b/VisualPinball.Unity/VisualPinball.Unity.Test/Input/NudgeSensorSetupTests.cs
new file mode 100644
index 0000000000..a708bd3d68
--- /dev/null
+++ b/VisualPinball.Unity/VisualPinball.Unity.Test/Input/NudgeSensorSetupTests.cs
@@ -0,0 +1,271 @@
+// Visual Pinball Engine
+// Copyright (C) 2026 freezy and VPE Team
+//
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+using NUnit.Framework;
+using System.Reflection;
+using UnityEngine;
+using VisualPinball.Unity.Simulation;
+
+namespace VisualPinball.Unity.Test
+{
+ public class NudgeSensorSetupTests
+ {
+ private static NativeInputDeviceInfo Device(string name, float x = 0.1f, long timestamp = 1000, bool connected = true)
+ {
+ return new NativeInputDeviceInfo(0, "board", name, connected, new[] {
+ new NativeInputAxisInfo(3, "X", 1, 0x30, NativeInputApi.AxisKind.Position, x, timestamp),
+ new NativeInputAxisInfo(5, "Y", 1, 0x31, NativeInputApi.AxisKind.Position, 0.2f, timestamp),
+ new NativeInputAxisInfo(7, "RX", 1, 0x33, NativeInputApi.AxisKind.Position, 0f, timestamp),
+ new NativeInputAxisInfo(9, "RY", 1, 0x34, NativeInputApi.AxisKind.Position, 0f, timestamp)
+ });
+ }
+
+ [Test]
+ public void AutoSetupRejectsGenericGamepadXY()
+ {
+ Assert.That(NudgeSensorSetup.TryCreateCabinetSensor(Device("Xbox controller"), out _), Is.False);
+ Assert.That(NudgeSensorSetup.TryCreateGamepadSensor(Device("Xbox controller"), out _), Is.False);
+ }
+
+ [Test]
+ public void GamepadPresetUsesStandardizedLeftStickAxes()
+ {
+ var device = new NativeInputDeviceInfo(1, "sdl-gamepad:test", "Gamepad", true, new[] {
+ new NativeInputAxisInfo(2, "Right Stick X", 0xff00, 2, NativeInputApi.AxisKind.Position, 0f, 0),
+ new NativeInputAxisInfo(5, "Left Stick Y", 0xff00, 1, NativeInputApi.AxisKind.Position, 0f, 0),
+ new NativeInputAxisInfo(3, "Left Stick X", 0xff00, 0, NativeInputApi.AxisKind.Position, 0f, 0)
+ });
+ Assert.That(NudgeSensorSetup.TryCreateGamepadSensor(device, out var settings), Is.True);
+ var sensor = settings.ToEngineConfig();
+ Assert.That(sensor.Type, Is.EqualTo(NudgeSensorType.GamepadIntent));
+ Assert.That(sensor.X.DeviceId, Is.EqualTo(device.Id));
+ Assert.That(sensor.X.AxisId, Is.EqualTo(3));
+ Assert.That(sensor.Y.AxisId, Is.EqualTo(5));
+ Assert.That(sensor.X.Kind, Is.EqualTo(SensorMappingKind.Position));
+ }
+
+ [TestCase("mjrnet Pinscape Controller")]
+ [TestCase("Pinscape Controller")]
+ [TestCase("PinscapePico")]
+ public void PinscapeAccelerationUsesUsageInsteadOfAxisIndex(string name)
+ {
+ Assert.That(NudgeSensorSetup.TryCreateCabinetSensor(Device(name), out var sensor), Is.True);
+ Assert.That(SensorMapping.TryParse(sensor.accX, out var x), Is.True);
+ Assert.That(x.AxisId, Is.EqualTo(3));
+ Assert.That(x.Kind, Is.EqualTo(SensorMappingKind.Acceleration));
+ Assert.That(x.Scale, Is.EqualTo(NudgeSensorSetup.Gravity));
+ Assert.That(sensor.velX, Is.Empty, "Velocity requires an explicit firmware/setup choice.");
+ }
+
+ [Test]
+ public void PinscapeVelocityUsesRXRYAndDeviceUnits()
+ {
+ Assert.That(NudgeSensorSetup.TryCreatePinscapeSensor(Device("Pinscape Controller"), true, out var sensor), Is.True);
+ Assert.That(SensorMapping.TryParse(sensor.velX, out var x), Is.True);
+ Assert.That(SensorMapping.TryParse(sensor.velY, out var y), Is.True);
+ Assert.That(x.AxisId, Is.EqualTo(7));
+ Assert.That(y.AxisId, Is.EqualTo(9));
+ Assert.That(x.Kind, Is.EqualTo(SensorMappingKind.Velocity));
+ Assert.That(x.Scale, Is.EqualTo(0.2048f));
+ Assert.That(x.DeadZone, Is.Zero);
+ Assert.That(sensor.accX, Is.Empty);
+ }
+
+ [Test]
+ public void DisconnectedDeviceCannotBeAutoMapped()
+ {
+ Assert.That(NudgeSensorSetup.TryCreateCabinetSensor(Device("Pinscape Controller", connected: false), out _), Is.False);
+ }
+
+ [Test]
+ public void OpdDefaultsToAccelerationAndUsesThePicoVelocityScaleWhenSelected()
+ {
+ var device = new NativeInputDeviceInfo(1, "pico-opd", "Pinscape Pico (OPD)", true, new[] {
+ new NativeInputAxisInfo(5, "Plunger Velocity", 5, 2, NativeInputApi.AxisKind.Velocity, 0f, 0),
+ new NativeInputAxisInfo(3, "Nudge Y Velocity", 5, 2, NativeInputApi.AxisKind.Velocity, 0f, 0),
+ new NativeInputAxisInfo(0, "Nudge X Acceleration", 5, 2, NativeInputApi.AxisKind.Acceleration, 0f, 0),
+ new NativeInputAxisInfo(2, "Nudge X Velocity", 5, 2, NativeInputApi.AxisKind.Velocity, 0f, 0),
+ new NativeInputAxisInfo(1, "Nudge Y Acceleration", 5, 2, NativeInputApi.AxisKind.Acceleration, 0f, 0)
+ });
+ Assert.That(NudgeSensorSetup.TryCreateCabinetSensor(device, out var acceleration), Is.True);
+ var acc = acceleration.ToEngineConfig();
+ Assert.That(acc.AccelerationX.AxisId, Is.Zero);
+ Assert.That(acc.AccelerationY.AxisId, Is.EqualTo(1));
+ Assert.That(acc.VelocityX.IsMapped, Is.False);
+ Assert.That(NudgeSensorSetup.TryCreateCabinetPreset(device, true, out var velocity), Is.True);
+ var vel = velocity.ToEngineConfig();
+ Assert.That(vel.VelocityX.DeviceId, Is.EqualTo("pico-opd"));
+ Assert.That(vel.VelocityX.AxisId, Is.EqualTo(2));
+ Assert.That(vel.VelocityY.AxisId, Is.EqualTo(3));
+ Assert.That(vel.VelocityX.Scale, Is.EqualTo(0.32768f));
+ Assert.That(vel.AccelerationX.IsMapped, Is.False);
+ }
+
+ [Test]
+ public void OpdVelocityPresetRequiresBothNudgeVelocityChannels()
+ {
+ var device = new NativeInputDeviceInfo(1, "pico-opd", "Pinscape Pico (OPD)", true, new[] {
+ new NativeInputAxisInfo(2, "Nudge X Velocity", 5, 2, NativeInputApi.AxisKind.Velocity, 0f, 0),
+ new NativeInputAxisInfo(5, "Plunger Velocity", 5, 2, NativeInputApi.AxisKind.Velocity, 0f, 0)
+ });
+ Assert.That(NudgeSensorSetup.TryCreateCabinetPreset(device, true, out _), Is.False);
+ }
+
+ [Test]
+ public void ExistingDeviceCheckUsesOnlyTheActiveSensorChannels()
+ {
+ var sensor = new NudgeSensorConfig {
+ Type = NudgeSensorType.GamepadIntent,
+ Y = new SensorMapping { DeviceId = "stick", AxisId = 1 },
+ VelocityY = new SensorMapping { DeviceId = "pico-hid", AxisId = 4 }
+ };
+ Assert.That(NudgeSensorSetup.IsMappedToDevice(sensor, "stick"), Is.True);
+ Assert.That(NudgeSensorSetup.IsMappedToDevice(sensor, "pico-hid"), Is.False);
+ sensor.Type = NudgeSensorType.CabinetDirect;
+ Assert.That(NudgeSensorSetup.IsMappedToDevice(sensor, "pico-hid"), Is.True);
+ Assert.That(NudgeSensorSetup.IsMappedToDevice(sensor, "stick"), Is.False);
+ }
+
+ private static NudgeSensorConfig Sensor()
+ {
+ NudgeSensorSetup.TryCreateCabinetSensor(Device("Pinscape Controller"), out var settings);
+ return settings.ToEngineConfig();
+ }
+
+ [Test]
+ public void CalibrationAveragesFreshSamplesAndPreservesGain()
+ {
+ var sensor = Sensor();
+ sensor.AccelerationX.Scale = -19.6133f;
+ var calibration = new NudgeSensorCalibration(new[] { sensor }, new[] { Device("Pinscape Controller") });
+ for (var i = 1; i <= 20; i++) {
+ calibration.Sample(new[] { Device("Pinscape Controller", i % 2 == 0 ? 0.102f : 0.098f, 1000 + i * 50000) });
+ }
+ Assert.That(calibration.TryComplete(out _), Is.True);
+ Assert.That(sensor.AccelerationX.RawCenter, Is.EqualTo(0.1f).Within(0.00001f));
+ Assert.That(sensor.AccelerationY.RawCenter, Is.EqualTo(0.2f).Within(0.00001f));
+ Assert.That(sensor.AccelerationX.Scale, Is.EqualTo(-19.6133f));
+ }
+
+ [Test]
+ public void RepeatedSnapshotsCannotCalibrateAStoppedDevice()
+ {
+ var sensor = Sensor();
+ sensor.AccelerationX.RawCenter = -0.1f;
+ var devices = new[] { Device("Pinscape Controller") };
+ var calibration = new NudgeSensorCalibration(new[] { sensor }, devices);
+ for (var i = 0; i < 30; i++) calibration.Sample(devices);
+ Assert.That(calibration.TryComplete(out _), Is.False);
+ Assert.That(sensor.AccelerationX.RawCenter, Is.EqualTo(-0.1f));
+ }
+
+ [TestCase(true)]
+ [TestCase(false)]
+ public void CalibrationFailureDoesNotPartiallyUpdateCenters(bool disconnect)
+ {
+ var sensor = Sensor();
+ sensor.AccelerationX.RawCenter = -0.1f;
+ sensor.AccelerationY.RawCenter = -0.2f;
+ var calibration = new NudgeSensorCalibration(new[] { sensor }, new[] { Device("Pinscape Controller") });
+ for (var i = 1; i <= 20; i++) {
+ var x = !disconnect && i == 10 ? 0.5f : 0.1f;
+ calibration.Sample(new[] { Device("Pinscape Controller", x, 1000 + i * 50000, !disconnect || i != 10) });
+ }
+ Assert.That(calibration.TryComplete(out _), Is.False);
+ Assert.That(sensor.AccelerationX.RawCenter, Is.EqualTo(-0.1f));
+ Assert.That(sensor.AccelerationY.RawCenter, Is.EqualTo(-0.2f));
+ }
+
+ [Test]
+ public void DisconnectResetClearsMotionAndReconnectStartsAtRest()
+ {
+ var state = new NudgeState(KeyboardNudgeMode.CabModel, 1f, 5f);
+ var config = new NudgeSensorRuntimeConfig { Type = NudgeSensorType.CabinetDirect, Strength = 1f, CabinetMassKg = 113f, AccelerationXMapped = 1 };
+ state.ConfigureSensor(0, config);
+ state.ApplySensorSample(0, NudgeSensorChannel.AccelerationX, -12f, 1000);
+ for (var i = 0; i < 10; i++) state.StepOneMillisecond();
+ Assert.That(state.ActiveSourceIndex, Is.EqualTo(0));
+ state.ConfigureSensor(0, config, false);
+ state.StepOneMillisecond();
+ Assert.That(state.ActiveSourceIndex, Is.EqualTo(-2));
+ Assert.That(state.CabinetAcceleration.x, Is.Zero);
+ Assert.That(state.CabinetOffset.x, Is.Zero);
+ state.ConfigureSensor(0, config, true);
+ state.StepOneMillisecond();
+ Assert.That(state.ActiveSourceIndex, Is.EqualTo(-2));
+ }
+
+ [Test]
+ public void RemappingDropsPendingSamplesFromThePreviousDevice()
+ {
+ var go = new GameObject("Nudge input test");
+ go.SetActive(false);
+ try {
+ var engine = go.AddComponent();
+ var system = new NudgeSystem(engine);
+ var context = (PhysicsEngineContext)typeof(PhysicsEngine).GetField("_ctx", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(engine);
+ system.ConfigureSensors(new[] { Sensor() });
+ engine.EnqueueNudgeSensorSample(0, NudgeSensorChannel.AccelerationX, 10f, 1000);
+ system.ConfigureSensors(new[] { Sensor() });
+ Assert.That(context.PendingNudgeSensorSamples, Is.Empty);
+ } finally {
+ Object.DestroyImmediate(go);
+ }
+ }
+
+ [Test]
+ public void LosingOneDeviceResetsItsSensorInOrderWithoutResettingTheOther()
+ {
+ var go = new GameObject("Nudge hotplug test");
+ go.SetActive(false);
+ try {
+ var engine = go.AddComponent();
+ var system = new NudgeSystem(engine);
+ var context = (PhysicsEngineContext)typeof(PhysicsEngine).GetField("_ctx", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(engine);
+ var otherSensor = Sensor();
+ otherSensor.AccelerationX.DeviceId = "other";
+ otherSensor.AccelerationY.DeviceId = "other";
+ var board = Device("Pinscape Controller");
+ var other = new NativeInputDeviceInfo(1, "other", "Other sensor", true, board.Axes);
+ system.UpdateConnectedDevices(new[] { board, other });
+ system.ConfigureSensors(new[] { Sensor(), otherSensor });
+ engine.EnqueueNudgeSensorSample(0, NudgeSensorChannel.AccelerationX, 10f, 1000);
+ system.UpdateConnectedDevices(new[] { other });
+ Assert.That(context.PendingNudgeSensorSamples.Count, Is.EqualTo(2));
+ Assert.That(context.PendingNudgeSensorSamples.Dequeue().IsConfiguration, Is.False);
+ var reset = context.PendingNudgeSensorSamples.Dequeue();
+ Assert.That(reset.IsConfiguration, Is.True);
+ Assert.That(reset.SensorIndex, Is.Zero);
+ Assert.That(reset.Enabled, Is.False);
+ system.UpdateConnectedDevices(new[] { board, other });
+ Assert.That(context.PendingNudgeSensorSamples.Dequeue().Enabled, Is.True);
+ } finally {
+ Object.DestroyImmediate(go);
+ }
+ }
+
+ [Test]
+ public void QueueOverflowRetainsDisconnectWhileDiscardingStaleMotion()
+ {
+ var go = new GameObject("Nudge backlog test");
+ go.SetActive(false);
+ try {
+ var engine = go.AddComponent();
+ var context = (PhysicsEngineContext)typeof(PhysicsEngine).GetField("_ctx", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(engine);
+ engine.EnqueueNudgeSensorReset(0, default, false);
+ for (var i = 0; i < 9000; i++) {
+ engine.EnqueueNudgeSensorSample(1, NudgeSensorChannel.X, 0.1f, (ulong)i);
+ }
+ Assert.That(context.PendingNudgeSensorSamples.Count, Is.LessThanOrEqualTo(8192));
+ var reset = context.PendingNudgeSensorSamples.Dequeue();
+ Assert.That(reset.IsConfiguration, Is.True);
+ Assert.That(reset.SensorIndex, Is.Zero);
+ Assert.That(reset.Enabled, Is.False);
+ } finally {
+ Object.DestroyImmediate(go);
+ }
+ }
+ }
+}
diff --git a/VisualPinball.Unity/VisualPinball.Unity.Test/Input/NudgeSensorSetupTests.cs.meta b/VisualPinball.Unity/VisualPinball.Unity.Test/Input/NudgeSensorSetupTests.cs.meta
new file mode 100644
index 0000000000..e4d02cb980
--- /dev/null
+++ b/VisualPinball.Unity/VisualPinball.Unity.Test/Input/NudgeSensorSetupTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: dbbfc78585d017244b0591aa55110b77
\ No newline at end of file
diff --git a/VisualPinball.Unity/VisualPinball.Unity.Test/Physics/CabinetPhysicsTests.cs b/VisualPinball.Unity/VisualPinball.Unity.Test/Physics/CabinetPhysicsTests.cs
index baf74aa6bf..f13d41a3d5 100644
--- a/VisualPinball.Unity/VisualPinball.Unity.Test/Physics/CabinetPhysicsTests.cs
+++ b/VisualPinball.Unity/VisualPinball.Unity.Test/Physics/CabinetPhysicsTests.cs
@@ -14,8 +14,13 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see .
+using System.Collections.Generic;
+using System.Reflection;
using NUnit.Framework;
using Unity.Mathematics;
+using UnityEngine;
+using VisualPinball.Engine.Common;
+using VisualPinball.Unity.Simulation;
namespace VisualPinball.Unity.Test
{
@@ -100,6 +105,104 @@ public void PlumbTiltLatchesAndQueuesTiltEvent()
Assert.That(plumb.PendingTiltStates.Length, Is.EqualTo(0));
}
+ [Test]
+ public void NativeTiltAndSimulatedPlumbKeepTheSwitchClosedUntilBothRelease()
+ {
+ const BindingFlags privateInstance = BindingFlags.Instance | BindingFlags.NonPublic;
+ var table = new GameObject("Tilt routing test");
+ table.SetActive(false);
+ try {
+ var playfield = new GameObject("Playfield");
+ playfield.transform.SetParent(table.transform);
+ var physics = playfield.AddComponent();
+ var player = table.AddComponent();
+ var bob = table.AddComponent();
+ var direct = new SwitchMapping { Id = "tilt", Source = SwitchSource.InputSystem, InputAction = InputConstants.ActionTilt };
+ var device = new SwitchMapping { Id = "tilt", Source = SwitchSource.Playfield, Device = bob, DeviceItem = TiltBobComponent.SwitchItem };
+ Assert.That(TiltBobComponent.OwnsTiltInputDestination(direct, new[] { direct, device }), Is.False,
+ "An inactive, unregistered bob does not take over the direct Tilt binding.");
+ typeof(TiltBobComponent).GetMethod("Awake", privateInstance).Invoke(bob, null);
+ var api = (TiltBobApi)player.Switch(bob, TiltBobComponent.SwitchItem);
+ Assert.That(api, Is.Not.Null, "The table-root Tilt Bob registers with the child playfield engine.");
+ var edges = new List();
+ api.Switch += (_, evt) => edges.Add(evt.IsEnabled);
+
+ using var simulation = new SimulationThread(physics, null, null);
+ var simulated = bob.CreateSimulatedTiltDispatcher();
+ simulation.SetTiltBobDispatchers(bob.SetPhysicalTilt, simulated);
+ var processInput = typeof(SimulationThread).GetMethod("ProcessInputEvents", privateInstance);
+ var queueTilt = typeof(SimulationThread).GetMethod("QueueMainThreadTiltState", privateInstance);
+
+ void Physical(bool pressed)
+ {
+ simulation.EnqueueInputEvent(new NativeInputApi.InputEvent {
+ EventType = (int)NativeInputApi.InputEventType.Action,
+ Action = (int)NativeInputApi.InputAction.Tilt,
+ Value = pressed ? 1f : 0f
+ });
+ processInput.Invoke(simulation, null);
+ }
+ void Simulated(bool pressed) =>
+ queueTilt.Invoke(simulation, new object[] { simulated, pressed });
+
+ Physical(true);
+ Simulated(true);
+ Physical(false);
+ simulation.FlushMainThreadInputDispatch();
+ Assert.That(api.IsSwitchEnabled, Is.True);
+ Assert.That(edges, Is.EqualTo(new[] { true }));
+ Physical(true);
+ Simulated(false);
+ simulation.FlushMainThreadInputDispatch();
+ Assert.That(edges, Is.EqualTo(new[] { true }));
+
+ Simulated(true);
+ bob.ApplySettings(new CabinetPlumbSettings { mode = TiltBobMode.Physical });
+ bob.ApplySettings(new CabinetPlumbSettings());
+ Physical(false);
+ simulation.FlushMainThreadInputDispatch();
+ Assert.That(edges, Is.EqualTo(new[] { true, false }), "An old simulated edge cannot close the switch after a mode change.");
+
+ player.NotifyCabinetInputAction(InputConstants.ActionTilt, true);
+ player.NotifyCabinetInputAction(InputConstants.ActionTilt, false);
+ Assert.That(edges, Is.EqualTo(new[] { true, false, true, false }));
+
+ Assert.That(TiltBobComponent.OwnsTiltInputDestination(direct, new[] { direct, device }), Is.True);
+ direct.Id = "other";
+ Assert.That(TiltBobComponent.OwnsTiltInputDestination(direct, new[] { direct, device }), Is.False);
+ } finally {
+ Object.DestroyImmediate(table);
+ }
+ }
+
+ [Test]
+ public void PlumbPlayerTuningOverridesAndRestoresAuthoredValues()
+ {
+ var table = new GameObject("Tilt tuning test");
+ table.SetActive(false);
+ try {
+ var playfield = new GameObject("Playfield");
+ playfield.transform.SetParent(table.transform);
+ var physics = playfield.AddComponent();
+ var bob = table.AddComponent();
+ bob.PlumbDamping = .8f;
+ bob.PlumbThresholdAngle = 2f;
+
+ bob.ApplySettings(new CabinetPlumbSettings { damping = 1.5f, thresholdDeg = 10f });
+ Assert.That(physics.PlumbDamping, Is.EqualTo(.8f));
+ Assert.That(physics.PlumbThresholdAngle, Is.EqualTo(2f));
+ TiltBobComponent.ApplySettings(physics, new CabinetPlumbSettings { overrideTuning = true, damping = 1.5f, thresholdDeg = 20f });
+ Assert.That(physics.PlumbDamping, Is.EqualTo(1.5f));
+ Assert.That(physics.PlumbThresholdAngle, Is.EqualTo(15f));
+ Assert.That(physics.GetNudgeSettings().plumb.overrideTuning, Is.True);
+ TiltBobComponent.ApplySettings(physics, new CabinetPlumbSettings());
+ Assert.That(physics.PlumbDamping, Is.EqualTo(.8f));
+ Assert.That(physics.PlumbThresholdAngle, Is.EqualTo(2f));
+ } finally {
+ Object.DestroyImmediate(table);
+ }
+ }
+
///
/// Computes the closed-form underdamped oscillator response used to verify
/// the one-millisecond integrator.
diff --git a/VisualPinball.Unity/VisualPinball.Unity/Game/CabinetInputSettings.cs b/VisualPinball.Unity/VisualPinball.Unity/Game/CabinetInputSettings.cs
index f1f3c5496d..76288d51e6 100644
--- a/VisualPinball.Unity/VisualPinball.Unity/Game/CabinetInputSettings.cs
+++ b/VisualPinball.Unity/VisualPinball.Unity/Game/CabinetInputSettings.cs
@@ -139,6 +139,7 @@ public sealed class CabinetNudgeSettings
public float visualStrength = 1f;
public CabinetPlumbSettings plumb = new();
public List sensors = new();
+ public string preferredDeviceId;
///
/// Clamps values and guarantees nested objects/lists are non-null.
@@ -161,6 +162,9 @@ public void Normalize()
sensors[i] ??= new CabinetNudgeSensorSettings();
sensors[i].Normalize();
}
+ if (!string.IsNullOrEmpty(preferredDeviceId) && !sensors.Exists(sensor => sensor.SingleDeviceId() == preferredDeviceId)) {
+ preferredDeviceId = null;
+ }
}
///
@@ -185,7 +189,7 @@ public List ToEngineSensorConfigs()
Normalize();
var sensorConfigs = new List(sensors.Count);
foreach (var sensor in sensors) {
- sensorConfigs.Add(sensor.ToEngineConfig());
+ if (UsesSensor(sensor)) sensorConfigs.Add(sensor.ToEngineConfig());
}
return sensorConfigs;
}
@@ -199,11 +203,14 @@ public List ToSimulationThreadSensorConfigs()
Normalize();
var sensorConfigs = new List(sensors.Count);
foreach (var sensor in sensors) {
- sensorConfigs.Add(sensor.ToSimulationThreadConfig());
+ if (UsesSensor(sensor)) sensorConfigs.Add(sensor.ToSimulationThreadConfig());
}
return sensorConfigs;
}
+ private bool UsesSensor(CabinetNudgeSensorSettings sensor) =>
+ string.IsNullOrEmpty(preferredDeviceId) || sensor.SingleDeviceId() == preferredDeviceId;
+
///
/// Captures the nudge fields currently stored on a physics engine.
///
@@ -218,10 +225,7 @@ public static CabinetNudgeSettings From(PhysicsEngine physicsEngine)
settings.keyboardStrength = physicsEngine.KeyboardNudgeStrength;
settings.keyboardCabinetDamping = physicsEngine.KeyboardCabinetDamping;
settings.visualStrength = physicsEngine.VisualNudgeStrength;
- settings.plumb = new CabinetPlumbSettings {
- enabled = true,
- mode = TiltBobComponent.FindFor(physicsEngine)?.Mode ?? TiltBobMode.Simulated
- };
+ settings.plumb = TiltBobComponent.FindFor(physicsEngine)?.CaptureSettings() ?? new CabinetPlumbSettings();
settings.Normalize();
return settings;
}
@@ -243,24 +247,25 @@ public sealed class CabinetPlumbSettings
public TiltBobMode mode = TiltBobMode.Simulated;
///
- /// Legacy player-config fields retained for JSON compatibility. Current
- /// tilt-bob tuning is authored on .
+ /// Applies player tuning in place of the table's authored values. The
+ /// opt-in flag keeps legacy profiles' unused tuning fields inactive.
///
+ public bool overrideTuning;
[HideInInspector]
- public float damping = 1f;
-
- [HideInInspector]
- public float thresholdDeg = 2f;
+ public bool hasCustomTuning;
+ public float damping = PlumbState.DefaultDamping;
+ public float thresholdDeg = PlumbState.DefaultThresholdAngle;
///
- /// Clamps the tilt-bob source mode and legacy tuning fields to useful ranges.
+ /// Clamps the tilt-bob source mode and tuning to supported ranges.
///
public void Normalize()
{
enabled = true;
mode = (TiltBobMode)Mathf.Clamp((int)mode, (int)TiltBobMode.Simulated, (int)TiltBobMode.Physical);
- damping = Mathf.Clamp(damping, 0f, 2f);
- thresholdDeg = Mathf.Clamp(thresholdDeg, 0.5f, 4f);
+ hasCustomTuning |= overrideTuning;
+ damping = hasCustomTuning ? PlumbState.ClampDamping(damping) : PlumbState.DefaultDamping;
+ thresholdDeg = hasCustomTuning ? PlumbState.ClampThresholdAngle(thresholdDeg) : PlumbState.DefaultThresholdAngle;
}
}
@@ -292,6 +297,22 @@ public sealed class CabinetNudgeSensorSettings
public int mountRotation;
public bool mountMirror;
+ /// Returns the device ID when all mapped channels belong to one device.
+ public string SingleDeviceId()
+ {
+ string deviceId = null;
+ bool SameDevice(string value)
+ {
+ if (!SensorMapping.TryParse(value, out var mapping) || !mapping.IsMapped) return true;
+ deviceId ??= mapping.DeviceId;
+ return mapping.DeviceId == deviceId;
+ }
+ var singleDevice = type == TypeGamepad
+ ? SameDevice(x) && SameDevice(y)
+ : SameDevice(accX) && SameDevice(accY) && SameDevice(velX) && SameDevice(velY);
+ return singleDevice ? deviceId : null;
+ }
+
///
/// Clamps values, normalizes type names, and guarantees mapping strings are
/// non-null.
diff --git a/VisualPinball.Unity/VisualPinball.Unity/Game/NudgeSystem.cs b/VisualPinball.Unity/VisualPinball.Unity/Game/NudgeSystem.cs
index 0a4019706f..41491e96f5 100644
--- a/VisualPinball.Unity/VisualPinball.Unity/Game/NudgeSystem.cs
+++ b/VisualPinball.Unity/VisualPinball.Unity/Game/NudgeSystem.cs
@@ -96,6 +96,8 @@ public sealed class NudgeSystem : IDisposable
private readonly object _configLock = new();
private readonly List _sensors = new(NudgeState.MaxSensors);
private volatile NativeInputManager _inputManager;
+ private HashSet _connectedDevices = new();
+ private readonly bool[] _sensorAvailable = new bool[NudgeState.MaxSensors];
///
/// Creates a nudge system attached to a physics engine.
@@ -142,10 +144,12 @@ public void ConfigureSensors(IReadOnlyList sensors)
}
}
- _physicsEngine.ConfigureNudgeSensorCount(_sensors.Count);
+ var configs = new NudgeSensorRuntimeConfig[_sensors.Count];
for (var i = 0; i < _sensors.Count; i++) {
- _physicsEngine.ConfigureNudgeSensor(i, _sensors[i].ToRuntimeConfig());
+ configs[i] = _sensors[i].ToRuntimeConfig();
+ _sensorAvailable[i] = IsSensorAvailable(_sensors[i]);
}
+ _physicsEngine.ApplyNudgeSensorConfigurations(configs, _sensorAvailable);
}
}
@@ -161,6 +165,8 @@ internal void AttachNativeInputManager(NativeInputManager inputManager)
_inputManager = inputManager;
if (_inputManager != null) {
_inputManager.AxisInputReceived += OnAxisInputReceived;
+ _inputManager.DevicesChanged += OnDevicesChanged;
+ OnDevicesChanged();
}
}
@@ -184,7 +190,9 @@ private void DetachNativeInputManager()
{
if (_inputManager != null) {
_inputManager.AxisInputReceived -= OnAxisInputReceived;
+ _inputManager.DevicesChanged -= OnDevicesChanged;
_inputManager = null;
+ UpdateConnectedDevices(Array.Empty());
}
}
@@ -209,7 +217,11 @@ private void OnAxisInputReceived(NativeInputApi.InputEvent evt)
}
lock (_configLock) {
+ if (_inputManager != inputManager) return;
for (var i = 0; i < _sensors.Count; i++) {
+ if (!_sensorAvailable[i]) {
+ continue;
+ }
var sensor = _sensors[i];
if (sensor.Type == NudgeSensorType.GamepadIntent) {
TryQueueSample(i, sensor.X, NudgeSensorChannel.X, deviceId, evt);
@@ -224,6 +236,50 @@ private void OnAxisInputReceived(NativeInputApi.InputEvent evt)
}
}
+ private void OnDevicesChanged()
+ {
+ var inputManager = _inputManager;
+ if (inputManager != null) {
+ var devices = inputManager.ListDevices();
+ lock (_configLock) {
+ if (_inputManager == inputManager) UpdateConnectedDevices(devices);
+ }
+ }
+ }
+
+ // Device notifications run on the input thread. Queue resets for physics instead
+ // of taking PhysicsLock while a simulation callback may be stopping input.
+ internal void UpdateConnectedDevices(IReadOnlyList devices)
+ {
+ lock (_configLock) {
+ var connected = new HashSet();
+ foreach (var device in devices) {
+ if (device.IsConnected) connected.Add(device.Id);
+ }
+ _connectedDevices = connected;
+ for (var i = 0; i < _sensors.Count; i++) {
+ var available = IsSensorAvailable(_sensors[i]);
+ if (available == _sensorAvailable[i]) continue;
+ _sensorAvailable[i] = available;
+ _physicsEngine.EnqueueNudgeSensorReset(i, _sensors[i].ToRuntimeConfig(), available);
+ }
+ }
+ }
+
+ private bool IsSensorAvailable(NudgeSensorConfig sensor)
+ {
+ if (sensor.Type == NudgeSensorType.GamepadIntent) {
+ return IsMappingAvailable(sensor.X) && IsMappingAvailable(sensor.Y);
+ }
+ return IsMappingAvailable(sensor.AccelerationX) && IsMappingAvailable(sensor.AccelerationY)
+ && IsMappingAvailable(sensor.VelocityX) && IsMappingAvailable(sensor.VelocityY);
+ }
+
+ private bool IsMappingAvailable(SensorMapping mapping)
+ {
+ return !mapping.IsMapped || _connectedDevices.Contains(mapping.DeviceId);
+ }
+
///
/// Matches one native axis event against one mapping and enqueues the
/// normalized sample when it belongs to that channel.
diff --git a/VisualPinball.Unity/VisualPinball.Unity/Game/PhysicsEngine.cs b/VisualPinball.Unity/VisualPinball.Unity/Game/PhysicsEngine.cs
index b91a039f15..4a06f2f919 100644
--- a/VisualPinball.Unity/VisualPinball.Unity/Game/PhysicsEngine.cs
+++ b/VisualPinball.Unity/VisualPinball.Unity/Game/PhysicsEngine.cs
@@ -137,13 +137,13 @@ public class PhysicsEngine : MonoBehaviour, IPackable
[HideInInspector]
[Tooltip("Mechanical plumb-bob damping scale.")]
- [Range(0f, 2f)]
- public float PlumbDamping = 1f;
+ [Range(PlumbState.MinDamping, PlumbState.MaxDamping)]
+ public float PlumbDamping = PlumbState.DefaultDamping;
[HideInInspector]
[Tooltip("Mechanical plumb-bob tilt threshold angle in degrees.")]
- [Range(0.5f, 4f)]
- public float PlumbThresholdAngle = 2f;
+ [Range(PlumbState.MinThresholdAngle, PlumbState.MaxThresholdAngle)]
+ public float PlumbThresholdAngle = PlumbState.DefaultThresholdAngle;
[Tooltip("Render-only visual nudge strength scale.")]
[Range(0f, 2f)]
@@ -449,8 +449,8 @@ public void ConfigureKeyboardNudge(KeyboardNudgeMode mode, float strength, float
public void ConfigurePlumb(bool simulatedPlumb, float damping, float thresholdAngle)
{
SimulatedPlumb = simulatedPlumb;
- PlumbDamping = math.clamp(damping, 0f, 2f);
- PlumbThresholdAngle = math.clamp(thresholdAngle, 0.5f, 4f);
+ PlumbDamping = PlumbState.ClampDamping(damping);
+ PlumbThresholdAngle = PlumbState.ClampThresholdAngle(thresholdAngle);
if (_ctx == null || !_ctx.IsInitialized) {
return;
@@ -499,28 +499,26 @@ public void ConfigureNudgeSensors(IReadOnlyList sensors)
_nudgeSystem?.ConfigureSensors(sensors);
}
- ///
- /// Updates the number of active analog sensor slots inside physics state.
- ///
- internal void ConfigureNudgeSensorCount(int count)
+ /// Replaces sensor state atomically and discards samples from the old mappings.
+ internal void ApplyNudgeSensorConfigurations(NudgeSensorRuntimeConfig[] configs, bool[] enabled)
{
lock (_ctx.PhysicsLock) {
+ lock (_ctx.PendingNudgeSensorSamplesLock) {
+ _ctx.PendingNudgeSensorSamples.Clear();
+ }
var nudge = _ctx.PhysicsEnv.Nudge;
- nudge.ConfigureSensors(count);
+ nudge.ConfigureSensors(configs.Length);
+ for (var i = 0; i < configs.Length; i++) {
+ nudge.ConfigureSensor(i, configs[i], enabled[i]);
+ }
_ctx.PhysicsEnv.Nudge = nudge;
}
}
- ///
- /// Updates one analog nudge sensor slot inside physics state.
- ///
- internal void ConfigureNudgeSensor(int index, NudgeSensorRuntimeConfig config)
+ // Queued in the same stream as input samples so hotplug cannot race older motion.
+ internal void EnqueueNudgeSensorReset(int index, NudgeSensorRuntimeConfig config, bool enabled)
{
- lock (_ctx.PhysicsLock) {
- var nudge = _ctx.PhysicsEnv.Nudge;
- nudge.ConfigureSensor(index, config);
- _ctx.PhysicsEnv.Nudge = nudge;
- }
+ EnqueueNudgeSensorCommand(new NudgeSensorSampleCommand(index, config, enabled));
}
///
@@ -528,23 +526,35 @@ internal void ConfigureNudgeSensor(int index, NudgeSensorRuntimeConfig config)
///
///
/// A streaming accelerometer can generate thousands of samples per second,
- /// so the queue is bounded and drops the oldest sample if the drain stalls.
+ /// so the queue is bounded and discards stale motion if the drain stalls.
/// Fresh samples are more useful than stale motion history after a pause or
/// debugger break.
///
internal void EnqueueNudgeSensorSample(int sensorIndex, NudgeSensorChannel channel, float value, ulong timestampUsec)
+ {
+ EnqueueNudgeSensorCommand(new NudgeSensorSampleCommand(sensorIndex, channel, value, timestampUsec));
+ }
+
+ private void EnqueueNudgeSensorCommand(NudgeSensorSampleCommand command)
{
lock (_ctx.PendingNudgeSensorSamplesLock) {
if (_ctx.PendingNudgeSensorSamples.Count >= PendingSensorSampleQueueCap) {
- // A stalled drain (pause, breakpoint) must not let a streaming
- // accelerometer grow the queue without bound; new samples win.
- _ctx.PendingNudgeSensorSamples.Dequeue();
+ // Motion history is stale after a long stall. Preserve the latest
+ // connection reset per sensor so overflow cannot leave a lost device active.
+ var resets = new NudgeSensorSampleCommand[NudgeState.MaxSensors];
+ while (_ctx.PendingNudgeSensorSamples.Count > 0) {
+ var pending = _ctx.PendingNudgeSensorSamples.Dequeue();
+ if (pending.IsConfiguration) resets[pending.SensorIndex] = pending;
+ }
+ foreach (var reset in resets) {
+ if (reset.IsConfiguration) _ctx.PendingNudgeSensorSamples.Enqueue(reset);
+ }
if (!_pendingSensorSampleQueueWarningIssued) {
_pendingSensorSampleQueueWarningIssued = true;
- LogQueueWarning($"[PhysicsEngine] PendingNudgeSensorSamples backlog reached {PendingSensorSampleQueueCap} items, dropping oldest. Is the drain stalled?");
+ LogQueueWarning($"[PhysicsEngine] PendingNudgeSensorSamples backlog reached {PendingSensorSampleQueueCap} items, discarding stale motion. Is the drain stalled?");
}
}
- _ctx.PendingNudgeSensorSamples.Enqueue(new NudgeSensorSampleCommand(sensorIndex, channel, value, timestampUsec));
+ _ctx.PendingNudgeSensorSamples.Enqueue(command);
}
}
diff --git a/VisualPinball.Unity/VisualPinball.Unity/Game/PhysicsEngineThreading.cs b/VisualPinball.Unity/VisualPinball.Unity/Game/PhysicsEngineThreading.cs
index ea6163f225..97aa25973f 100644
--- a/VisualPinball.Unity/VisualPinball.Unity/Game/PhysicsEngineThreading.cs
+++ b/VisualPinball.Unity/VisualPinball.Unity/Game/PhysicsEngineThreading.cs
@@ -372,7 +372,11 @@ private void ProcessPendingNudgeSensorSamples()
foreach (var sample in _pendingNudgeSensorSamples) {
var nudgeState = _ctx.PhysicsEnv.Nudge;
- nudgeState.ApplySensorSample(sample.SensorIndex, sample.Channel, sample.Value, sample.TimestampUsec);
+ if (sample.IsConfiguration) {
+ nudgeState.ConfigureSensor(sample.SensorIndex, sample.Configuration, sample.Enabled);
+ } else {
+ nudgeState.ApplySensorSample(sample.SensorIndex, sample.Channel, sample.Value, sample.TimestampUsec);
+ }
_ctx.PhysicsEnv.Nudge = nudgeState;
}
}
diff --git a/VisualPinball.Unity/VisualPinball.Unity/Game/PhysicsEnv.cs b/VisualPinball.Unity/VisualPinball.Unity/Game/PhysicsEnv.cs
index 63b54e721b..7c3d0782d0 100644
--- a/VisualPinball.Unity/VisualPinball.Unity/Game/PhysicsEnv.cs
+++ b/VisualPinball.Unity/VisualPinball.Unity/Game/PhysicsEnv.cs
@@ -49,7 +49,8 @@ public struct PhysicsEnv
///
public PhysicsEnv(ulong startTimeUsec, PlayfieldComponent playfield, float gravityStrength,
KeyboardNudgeMode keyboardNudgeMode = KeyboardNudgeMode.CabModel, float keyboardNudgeStrength = 1f,
- float nudgeTime = 5f, bool simulatedPlumb = true, float plumbDamping = 1f, float plumbThresholdAngle = 2f,
+ float nudgeTime = 5f, bool simulatedPlumb = true, float plumbDamping = PlumbState.DefaultDamping,
+ float plumbThresholdAngle = PlumbState.DefaultThresholdAngle,
float keyboardCabinetDamping = CabinetPhysicsState.DefaultKeyboardDampingRatio) : this()
{
StartTimeUsec = startTimeUsec;
diff --git a/VisualPinball.Unity/VisualPinball.Unity/Game/SwitchPlayer.cs b/VisualPinball.Unity/VisualPinball.Unity/Game/SwitchPlayer.cs
index 8a0ecb46f2..64b154c159 100644
--- a/VisualPinball.Unity/VisualPinball.Unity/Game/SwitchPlayer.cs
+++ b/VisualPinball.Unity/VisualPinball.Unity/Game/SwitchPlayer.cs
@@ -103,6 +103,9 @@ public void OnStart()
}
case SwitchSource.InputSystem:
+ // One switch destination cannot independently receive a physical Tilt
+ // release and the merged physical/simulated Tilt Bob state.
+ if (TiltBobComponent.OwnsTiltInputDestination(switchMapping, config.Switches)) break;
var inputAction = InputManager.GetCanonicalActionName(switchMapping.InputAction);
if (!_keySwitchAssignments.ContainsKey(inputAction)) {
_keySwitchAssignments[inputAction] = new List();
diff --git a/VisualPinball.Unity/VisualPinball.Unity/Input/NudgeSensorSetup.cs b/VisualPinball.Unity/VisualPinball.Unity/Input/NudgeSensorSetup.cs
new file mode 100644
index 0000000000..ea37d2d85a
--- /dev/null
+++ b/VisualPinball.Unity/VisualPinball.Unity/Input/NudgeSensorSetup.cs
@@ -0,0 +1,283 @@
+// Visual Pinball Engine
+// Copyright (C) 2026 freezy and VPE Team
+//
+// SPDX-License-Identifier: GPL-3.0-or-later
+
+using System;
+using System.Collections.Generic;
+using Unity.Mathematics;
+using VisualPinball.Unity.Simulation;
+
+namespace VisualPinball.Unity
+{
+ /// Shared device recognition and cabinet-axis defaults for editor and player setup.
+ public static class NudgeSensorSetup
+ {
+ public const float Gravity = 9.80665f;
+ // Pinscape's default joystick velocity range is +/-4096 / 20 mm/s.
+ public const float PinscapeVelocityScale = 0.2048f;
+ // Pico defaults to 100 signed report counts per mm/s.
+ public const float PinscapePicoVelocityScale = 0.32768f;
+ private const int OpdUsagePage = 0x05;
+ private const int OpdUsage = 0x02;
+ private const int GamepadUsagePage = 0xff00; // VPE_GAMEPAD_AXIS_USAGE_PAGE
+
+ public static bool IsOpenPinballDevice(NativeInputDeviceInfo device)
+ {
+ if (device?.Axes != null) {
+ foreach (var axis in device.Axes) {
+ if (axis.UsagePage == OpdUsagePage && axis.Usage == OpdUsage) return true;
+ }
+ }
+ return false;
+ }
+
+ public static bool IsPinscape(NativeInputDeviceInfo device)
+ {
+ if (IsOpenPinballDevice(device)) return false;
+ var name = device?.Name ?? string.Empty;
+ return name.StartsWith("mjrnet Pinscape Controller", StringComparison.OrdinalIgnoreCase)
+ || name.Equals("Pinscape Controller", StringComparison.OrdinalIgnoreCase)
+ || name.Equals("PinscapePico", StringComparison.OrdinalIgnoreCase)
+ || name.Equals("Pinscape Pico", StringComparison.OrdinalIgnoreCase)
+ || name.Equals("mjrnet PinscapePico", StringComparison.OrdinalIgnoreCase)
+ || name.Equals("mjrgh PinscapePico", StringComparison.OrdinalIgnoreCase);
+ }
+
+ /// Maps a recognized gamepad's standardized left stick to intent nudging.
+ public static bool TryCreateGamepadSensor(NativeInputDeviceInfo device, out CabinetNudgeSensorSettings sensor)
+ {
+ sensor = null;
+ if (device == null || !device.IsConnected
+ || !TryFindUsage(device, GamepadUsagePage, 0, out var x)
+ || !TryFindUsage(device, GamepadUsagePage, 1, out var y)) return false;
+ sensor = new CabinetNudgeSensorSettings {
+ type = CabinetNudgeSensorSettings.TypeGamepad,
+ x = Mapping(device, x, SensorMappingKind.Position, 1f),
+ y = Mapping(device, y, SensorMappingKind.Position, 1f)
+ };
+ return true;
+ }
+
+ /// Checks the active mappings when offering another device or collection.
+ public static bool IsMappedToDevice(NudgeSensorConfig sensor, string deviceId)
+ {
+ bool Matches(SensorMapping mapping) => mapping != null && mapping.IsMapped && mapping.DeviceId == deviceId;
+ return sensor.Type == NudgeSensorType.GamepadIntent
+ ? Matches(sensor.X) || Matches(sensor.Y)
+ : Matches(sensor.AccelerationX) || Matches(sensor.AccelerationY) || Matches(sensor.VelocityX) || Matches(sensor.VelocityY);
+ }
+
+ ///
+ /// Proposes the standard Pinscape joystick layout. Velocity must be explicitly
+ /// selected after enabling it in firmware; an RX/RY axis alone does not identify its meaning.
+ ///
+ public static bool TryCreatePinscapeSensor(NativeInputDeviceInfo device, bool velocity,
+ out CabinetNudgeSensorSettings sensor)
+ {
+ sensor = null;
+ if (device == null || !device.IsConnected || !IsPinscape(device)
+ || !TryFindUsage(device, velocity ? 0x33 : 0x30, out var x)
+ || !TryFindUsage(device, velocity ? 0x34 : 0x31, out var y)) {
+ return false;
+ }
+ sensor = CreateSensor(device, x, y, velocity, PinscapeVelocityScale);
+ return true;
+ }
+
+ public static bool TryCreateCabinetPreset(NativeInputDeviceInfo device, bool velocity,
+ out CabinetNudgeSensorSettings sensor)
+ {
+ return IsOpenPinballDevice(device)
+ ? TryCreateOpenPinballSensor(device, velocity, out sensor)
+ : TryCreatePinscapeSensor(device, velocity, out sensor);
+ }
+
+ private static bool TryCreateOpenPinballSensor(NativeInputDeviceInfo device, bool velocity,
+ out CabinetNudgeSensorSettings sensor)
+ {
+ sensor = null;
+ if (!device.IsConnected) return false;
+ var kind = velocity ? NativeInputApi.AxisKind.Velocity : NativeInputApi.AxisKind.Acceleration;
+ var firstId = velocity ? 2 : 0;
+ NativeInputAxisInfo x = default;
+ NativeInputAxisInfo y = default;
+ foreach (var axis in device.Axes) {
+ if (axis.UsagePage != OpdUsagePage || axis.Usage != OpdUsage || axis.Kind != kind) continue;
+ if (axis.AxisId == firstId) x = axis;
+ if (axis.AxisId == firstId + 1) y = axis;
+ }
+ if (x.UsagePage != OpdUsagePage || y.UsagePage != OpdUsagePage) return false;
+ sensor = CreateSensor(device, x, y, velocity, PinscapePicoVelocityScale);
+ return true;
+ }
+
+ private static CabinetNudgeSensorSettings CreateSensor(NativeInputDeviceInfo device, NativeInputAxisInfo x,
+ NativeInputAxisInfo y, bool velocity, float velocityScale)
+ {
+ var kind = velocity ? SensorMappingKind.Velocity : SensorMappingKind.Acceleration;
+ var scale = velocity ? velocityScale : Gravity;
+ var sensor = new CabinetNudgeSensorSettings { type = CabinetNudgeSensorSettings.TypeCabinetDirect };
+ if (velocity) {
+ sensor.velX = Mapping(device, x, kind, scale);
+ sensor.velY = Mapping(device, y, kind, scale);
+ } else {
+ sensor.accX = Mapping(device, x, kind, scale);
+ sensor.accY = Mapping(device, y, kind, scale);
+ }
+ return sensor;
+ }
+
+ /// Auto-maps OPD, recognized Pinscape layouts or explicitly typed X/Y accelerometer axes.
+ public static bool TryCreateCabinetSensor(NativeInputDeviceInfo device, out CabinetNudgeSensorSettings sensor)
+ {
+ if (TryCreateCabinetPreset(device, false, out sensor)) {
+ return true;
+ }
+ if (device == null || !device.IsConnected
+ || !TryFindUsage(device, 0x30, out var x) || x.Kind != NativeInputApi.AxisKind.Acceleration
+ || !TryFindUsage(device, 0x31, out var y) || y.Kind != NativeInputApi.AxisKind.Acceleration) {
+ return false;
+ }
+ sensor = new CabinetNudgeSensorSettings {
+ type = CabinetNudgeSensorSettings.TypeCabinetDirect,
+ accX = Mapping(device, x, SensorMappingKind.Acceleration, Gravity),
+ accY = Mapping(device, y, SensorMappingKind.Acceleration, Gravity)
+ };
+ return true;
+ }
+
+ public static bool TryFindAxis(IReadOnlyList devices, SensorMapping mapping,
+ out NativeInputAxisInfo axis)
+ {
+ if (devices != null && mapping != null) {
+ foreach (var device in devices) {
+ if (device == null || !device.IsConnected || device.Id != mapping.DeviceId || device.Axes == null) {
+ continue;
+ }
+ foreach (var candidate in device.Axes) {
+ if (candidate.AxisId == mapping.AxisId) {
+ axis = candidate;
+ return true;
+ }
+ }
+ }
+ }
+ axis = default;
+ return false;
+ }
+
+ private static bool TryFindUsage(NativeInputDeviceInfo device, int usage, out NativeInputAxisInfo axis)
+ => TryFindUsage(device, 1, usage, out axis);
+
+ private static bool TryFindUsage(NativeInputDeviceInfo device, int page, int usage, out NativeInputAxisInfo axis)
+ {
+ if (device.Axes != null) {
+ foreach (var candidate in device.Axes) {
+ if (candidate.UsagePage == page && candidate.Usage == usage) {
+ axis = candidate;
+ return true;
+ }
+ }
+ }
+ axis = default;
+ return false;
+ }
+
+ private static string Mapping(NativeInputDeviceInfo device, NativeInputAxisInfo axis, SensorMappingKind kind, float scale)
+ {
+ return new SensorMapping {
+ DeviceId = device.Id, AxisId = axis.AxisId, Kind = kind, Scale = scale,
+ DeadZone = kind == SensorMappingKind.Velocity ? 0f : 0.02f
+ }.ToString();
+ }
+ }
+
+ ///
+ /// Collects fresh rest samples for a set of mapping copies. Call Sample for about
+ /// one second, then TryComplete. Failure leaves all centers intact.
+ ///
+ public sealed class NudgeSensorCalibration
+ {
+ private sealed class Channel
+ {
+ public SensorMapping Mapping;
+ public long Timestamp;
+ public long FirstTimestamp;
+ public int Count;
+ public double Sum;
+ public float Min = float.PositiveInfinity;
+ public float Max = float.NegativeInfinity;
+ }
+
+ private readonly List _channels = new();
+ private bool _unavailable;
+
+ public NudgeSensorCalibration(IReadOnlyList sensors, IReadOnlyList devices)
+ {
+ foreach (var sensor in sensors) {
+ if (sensor.Type == NudgeSensorType.GamepadIntent) {
+ Add(sensor.X, devices);
+ Add(sensor.Y, devices);
+ } else {
+ Add(sensor.AccelerationX, devices);
+ Add(sensor.AccelerationY, devices);
+ Add(sensor.VelocityX, devices);
+ Add(sensor.VelocityY, devices);
+ }
+ }
+ }
+
+ private void Add(SensorMapping mapping, IReadOnlyList devices)
+ {
+ if (mapping == null || !mapping.IsMapped) {
+ return;
+ }
+ var present = NudgeSensorSetup.TryFindAxis(devices, mapping, out var axis);
+ _unavailable |= !present;
+ _channels.Add(new Channel { Mapping = mapping, Timestamp = present ? axis.TimestampUsec : 0 });
+ }
+
+ public void Sample(IReadOnlyList devices)
+ {
+ foreach (var channel in _channels) {
+ if (!NudgeSensorSetup.TryFindAxis(devices, channel.Mapping, out var axis)) {
+ _unavailable = true;
+ continue;
+ }
+ if (axis.TimestampUsec <= channel.Timestamp || float.IsNaN(axis.RawValue) || float.IsInfinity(axis.RawValue)) {
+ continue;
+ }
+ channel.Timestamp = axis.TimestampUsec;
+ if (channel.Count == 0) channel.FirstTimestamp = axis.TimestampUsec;
+ channel.Count++;
+ channel.Sum += axis.RawValue;
+ channel.Min = math.min(channel.Min, axis.RawValue);
+ channel.Max = math.max(channel.Max, axis.RawValue);
+ }
+ }
+
+ public bool TryComplete(out string message)
+ {
+ if (_channels.Count == 0 || _unavailable) {
+ message = "Calibration needs connected devices for every mapped channel.";
+ return false;
+ }
+ foreach (var channel in _channels) {
+ if (channel.Count < 8 || channel.Timestamp - channel.FirstTimestamp < 500000) {
+ message = "Not enough fresh input samples. Check the device and try again.";
+ return false;
+ }
+ if (channel.Max - channel.Min > 0.04f) {
+ message = "Input moved too much. Keep the cabinet still and try again.";
+ return false;
+ }
+ }
+ foreach (var channel in _channels) {
+ channel.Mapping.RawCenter = (float)(channel.Sum / channel.Count);
+ }
+ message = $"Calibrated {_channels.Count} nudge channels at rest.";
+ return true;
+ }
+ }
+}
diff --git a/VisualPinball.Unity/VisualPinball.Unity/Input/NudgeSensorSetup.cs.meta b/VisualPinball.Unity/VisualPinball.Unity/Input/NudgeSensorSetup.cs.meta
new file mode 100644
index 0000000000..256c8e32e2
--- /dev/null
+++ b/VisualPinball.Unity/VisualPinball.Unity/Input/NudgeSensorSetup.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 375d6f50ad0f8bd4eadc63b8cd3bb154
\ No newline at end of file
diff --git a/VisualPinball.Unity/VisualPinball.Unity/Physics/Cabinet/NudgeState.cs b/VisualPinball.Unity/VisualPinball.Unity/Physics/Cabinet/NudgeState.cs
index d213da9adb..4e480ff400 100644
--- a/VisualPinball.Unity/VisualPinball.Unity/Physics/Cabinet/NudgeState.cs
+++ b/VisualPinball.Unity/VisualPinball.Unity/Physics/Cabinet/NudgeState.cs
@@ -47,6 +47,9 @@ internal readonly struct NudgeSensorSampleCommand
public readonly NudgeSensorChannel Channel;
public readonly float Value;
public readonly ulong TimestampUsec;
+ public readonly bool IsConfiguration;
+ public readonly bool Enabled;
+ public readonly NudgeSensorRuntimeConfig Configuration;
///
/// Creates a timestamped sensor sample for the configured sensor slot.
@@ -57,6 +60,20 @@ public NudgeSensorSampleCommand(int sensorIndex, NudgeSensorChannel channel, flo
Channel = channel;
Value = value;
TimestampUsec = timestampUsec;
+ IsConfiguration = false;
+ Enabled = false;
+ Configuration = default;
+ }
+
+ public NudgeSensorSampleCommand(int sensorIndex, NudgeSensorRuntimeConfig configuration, bool enabled)
+ {
+ SensorIndex = sensorIndex;
+ Configuration = configuration;
+ Enabled = enabled;
+ IsConfiguration = true;
+ Channel = default;
+ Value = 0f;
+ TimestampUsec = 0;
}
}
@@ -133,7 +150,7 @@ public void ConfigureSensors(int count)
///
/// Rebuilds one analog sensor slot from serialized/player configuration.
///
- public void ConfigureSensor(int index, NudgeSensorRuntimeConfig config)
+ public void ConfigureSensor(int index, NudgeSensorRuntimeConfig config, bool enabled = true)
{
if ((uint)index >= MaxSensors) {
return;
@@ -142,6 +159,9 @@ public void ConfigureSensor(int index, NudgeSensorRuntimeConfig config)
config.CabinetMassKg = math.clamp(config.CabinetMassKg <= 0f ? 113f : config.CabinetMassKg, 0f, 200f);
config.MountRotation = NudgeSensorMountTransform.NormalizeRotation(config.MountRotation);
ConfigureSensorState(index, config);
+ if (!enabled) {
+ DisableSensor(index);
+ }
if (index >= SensorCount) {
SensorCount = index + 1;
}
diff --git a/VisualPinball.Unity/VisualPinball.Unity/Physics/Cabinet/PlumbState.cs b/VisualPinball.Unity/VisualPinball.Unity/Physics/Cabinet/PlumbState.cs
index 99534bc43b..ed144a06cc 100644
--- a/VisualPinball.Unity/VisualPinball.Unity/Physics/Cabinet/PlumbState.cs
+++ b/VisualPinball.Unity/VisualPinball.Unity/Physics/Cabinet/PlumbState.cs
@@ -31,6 +31,13 @@ namespace VisualPinball.Unity
///
public struct PlumbState
{
+ public const float DefaultDamping = 0.2f;
+ public const float MinDamping = 0f;
+ public const float MaxDamping = 2f;
+ public const float DefaultThresholdAngle = 4f;
+ public const float MinThresholdAngle = 0.15f;
+ public const float MaxThresholdAngle = 15f;
+
private const float Gravity = 9.80665f;
private const float DefaultPoleLength = 0.10f;
private const float DampingCoef0 = 1.25f;
@@ -69,7 +76,7 @@ public bool TiltHigh
public PlumbState(bool enabled, float damping, float tiltThresholdDeg)
{
PoleLength = DefaultPoleLength;
- TiltThresholdRad = math.radians(math.clamp(tiltThresholdDeg, 0.5f, 4f));
+ TiltThresholdRad = math.radians(ClampThresholdAngle(tiltThresholdDeg));
Position = new float3(0f, 0f, -DefaultPoleLength);
AngularVelocity = float3.zero;
TiltIndex = 0;
@@ -78,8 +85,8 @@ public PlumbState(bool enabled, float damping, float tiltThresholdDeg)
PendingTiltStates = default;
_enabled = enabled ? (byte)1 : (byte)0;
_tiltHigh = 0;
- _angularDamping0 = DampingCoef0 * math.clamp(damping, 0f, 2f);
- _angularDamping1 = DampingCoef1 * math.clamp(damping, 0f, 2f);
+ _angularDamping0 = DampingCoef0 * ClampDamping(damping);
+ _angularDamping1 = DampingCoef1 * ClampDamping(damping);
_cabinetAccelerationScale = 1f;
}
@@ -91,21 +98,26 @@ public void Configure(bool enabled, float damping, float tiltThresholdDeg)
// Runtime reconfiguration must not teleport the pendulum or lose the
// script-visible state (the reference setters preserve it too).
_enabled = enabled ? (byte)1 : (byte)0;
- TiltThresholdRad = math.radians(math.clamp(tiltThresholdDeg, 0.5f, 4f));
- _angularDamping0 = DampingCoef0 * math.clamp(damping, 0f, 2f);
- _angularDamping1 = DampingCoef1 * math.clamp(damping, 0f, 2f);
-
- // If the tilt switch is currently closed and the plumb no longer steps
- // (disabled) or the threshold moved past the bob, emit a release edge so
- // the consumer side doesn't stay stuck on "tilted".
- if (TiltHigh && !enabled) {
- TiltHigh = false;
- if (PendingTiltStates.Length < PendingTiltStates.Capacity) {
+ TiltThresholdRad = math.radians(ClampThresholdAngle(tiltThresholdDeg));
+ _angularDamping0 = DampingCoef0 * ClampDamping(damping);
+ _angularDamping1 = DampingCoef1 * ClampDamping(damping);
+
+ if (!enabled) {
+ // Discard transitions from the old mode before simulation can resume.
+ PendingTiltStates.Clear();
+ if (TiltHigh) {
+ TiltHigh = false;
PendingTiltStates.Add(0);
}
}
}
+ internal static float ClampDamping(float value) =>
+ math.isfinite(value) ? math.clamp(value, MinDamping, MaxDamping) : DefaultDamping;
+
+ internal static float ClampThresholdAngle(float value) =>
+ math.isfinite(value) ? math.clamp(value, MinThresholdAngle, MaxThresholdAngle) : DefaultThresholdAngle;
+
///
/// Integrates the plumb bob one millisecond in the accelerating cabinet
/// reference frame.
diff --git a/VisualPinball.Unity/VisualPinball.Unity/Simulation/NativeInputApi.cs b/VisualPinball.Unity/VisualPinball.Unity/Simulation/NativeInputApi.cs
index ca9b55e249..102d22975e 100644
--- a/VisualPinball.Unity/VisualPinball.Unity/Simulation/NativeInputApi.cs
+++ b/VisualPinball.Unity/VisualPinball.Unity/Simulation/NativeInputApi.cs
@@ -6,6 +6,7 @@
using System;
using System.Runtime.InteropServices;
+using System.Text;
using AOT;
namespace VisualPinball.Unity.Simulation
@@ -36,6 +37,7 @@ public static class NativeInputApi
/// Maximum UTF-8 bytes in an axis display name.
public const int AxisNameSize = 32;
+ public const int ButtonNameSize = 32;
#region Enums
@@ -207,6 +209,83 @@ public struct InputBinding
private int _padding;
}
+ [StructLayout(LayoutKind.Sequential, Pack = 4)]
+ public struct InputButtonBinding
+ {
+ public int Action;
+ public int ButtonId;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = DeviceIdSize)]
+ private byte[] _deviceId;
+
+ public string DeviceId => DecodeUtf8(_deviceId);
+
+ public static bool TryCreate(InputAction action, int buttonId, string deviceId, out InputButtonBinding binding)
+ {
+ binding = default;
+ if (buttonId < 0 || !TryEncodeDeviceId(deviceId, out var bytes)) return false;
+ binding = new InputButtonBinding { Action = (int)action, ButtonId = buttonId, _deviceId = bytes };
+ return true;
+ }
+ }
+
+ public enum InputControlKind { Button, AxisAbove, AxisBelow }
+
+ [StructLayout(LayoutKind.Sequential, Pack = 4)]
+ public struct InputControlBinding
+ {
+ public int Action;
+ public int Group;
+ public InputControlKind Kind;
+ public int ControlId;
+ public float Threshold;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = DeviceIdSize)]
+ private byte[] _deviceId;
+
+ public string DeviceId => DecodeUtf8(_deviceId);
+
+ public static bool TryCreate(InputAction action, int group, InputControlKind kind, int controlId,
+ float threshold, string deviceId, out InputControlBinding binding)
+ {
+ binding = default;
+ var validDirection = kind switch {
+ InputControlKind.Button => true,
+ InputControlKind.AxisAbove => threshold > 0f,
+ InputControlKind.AxisBelow => threshold < 0f,
+ _ => false
+ };
+ if (group < 0 || controlId < 0 || !validDirection
+ || !float.IsFinite(threshold) || threshold is < -1f or > 1f || !TryEncodeDeviceId(deviceId, out var bytes)) return false;
+ binding = new InputControlBinding {
+ Action = (int)action, Group = group, Kind = kind, ControlId = controlId, Threshold = threshold, _deviceId = bytes
+ };
+ return true;
+ }
+ }
+
+ private static bool TryEncodeDeviceId(string deviceId, out byte[] bytes)
+ {
+ bytes = null;
+ if (string.IsNullOrEmpty(deviceId) || deviceId.IndexOf('\0') >= 0
+ || Encoding.UTF8.GetByteCount(deviceId) >= DeviceIdSize) return false;
+ bytes = new byte[DeviceIdSize];
+ Encoding.UTF8.GetBytes(deviceId, 0, deviceId.Length, bytes, 0);
+ return true;
+ }
+
+ [StructLayout(LayoutKind.Sequential, Pack = 4)]
+ public struct InputButtonInfo
+ {
+ public int ButtonId;
+ public int IsPressed;
+
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = ButtonNameSize)]
+ private byte[] _name;
+
+ public string Name => DecodeUtf8(_name);
+ }
+
///
/// Native device metadata returned by enumeration.
///
@@ -306,6 +385,9 @@ private static string DecodeUtf8(byte[] bytes)
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void VpeInputSetBindings(InputBinding[] bindings, int count);
+ [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
+ internal static extern void VpeInputSetGameplayInputEnabled(int enabled);
+
///
/// Starts native polling and dispatches events through the supplied callback.
///
@@ -330,6 +412,21 @@ private static string DecodeUtf8(byte[] bytes)
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
public static extern int VpeInputListDeviceAxes(int deviceIndex, [Out] InputAxisInfo[] axes, int maxAxes);
+ [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
+ public static extern int VpeInputListDeviceButtons(int deviceIndex, [Out] InputButtonInfo[] buttons, int maxButtons);
+
+ [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
+ public static extern void VpeInputSetButtonBindings([In] InputButtonBinding[] bindings, int count);
+
+ [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
+ public static extern void VpeInputSetControlBindings([In] InputControlBinding[] controls, int count);
+
+ [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
+ public static extern void VpeInputStartControlCapture(int mode);
+
+ [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
+ public static extern int VpeInputReadControlCapture([Out] InputControlBinding[] controls, int maxControls);
+
///
/// Returns the native high-resolution timestamp in microseconds.
///
diff --git a/VisualPinball.Unity/VisualPinball.Unity/Simulation/NativeInputManager.cs b/VisualPinball.Unity/VisualPinball.Unity/Simulation/NativeInputManager.cs
index 091561b935..62f9e3da95 100644
--- a/VisualPinball.Unity/VisualPinball.Unity/Simulation/NativeInputManager.cs
+++ b/VisualPinball.Unity/VisualPinball.Unity/Simulation/NativeInputManager.cs
@@ -6,6 +6,7 @@
using System;
using System.Collections.Generic;
+using System.Linq;
using System.Diagnostics;
using System.Threading;
using AOT;
@@ -37,6 +38,7 @@ public class NativeInputManager : IDisposable
private volatile SimulationThread _simulationThread;
private bool _initialized = false;
+ private bool _hasNativeGameplayGate;
private bool _polling = false;
private int _pollIntervalUs = 0;
private const double PerfSampleWindowSeconds = 0.25;
@@ -57,6 +59,9 @@ public class NativeInputManager : IDisposable
// StartPolling sends these to the native layer instead of the built-in defaults. Static so it
// survives the per-table singleton churn (Dispose nulls _instance).
private static volatile List _configuredBindings;
+ private static volatile NativeInputApi.InputControlBinding[] _configuredControlBindings = Array.Empty();
+ private bool _hasNativeButtons;
+ private bool _hasNativeControlBindings;
// Set from the main thread (Application.isFocused). When the app window isn't focused, native input
// is dropped so background key presses (e.g. typing in another app) don't reach the game.
@@ -159,6 +164,24 @@ public bool Initialize()
}
_initialized = true;
+ try {
+ NativeInputApi.VpeInputSetGameplayInputEnabled(_appFocused && !_gamePaused ? 1 : 0);
+ _hasNativeGameplayGate = true;
+ } catch (EntryPointNotFoundException) {
+ // Older plugins and other platforms still use the managed focus gate.
+ }
+ try {
+ NativeInputApi.VpeInputListDeviceButtons(-1, null, 0);
+ _hasNativeButtons = true;
+ } catch (EntryPointNotFoundException) {
+ _hasNativeButtons = false;
+ }
+ try {
+ NativeInputApi.VpeInputReadControlCapture(null, 0);
+ _hasNativeControlBindings = true;
+ } catch (EntryPointNotFoundException) {
+ _hasNativeControlBindings = false;
+ }
Logger.Info($"{LogPrefix} [NativeInputManager] Initialized");
// Setup default bindings
@@ -208,6 +231,64 @@ public static List ConfiguredBindings
set => _configuredBindings = value;
}
+ /// Applies controller bindings to current and future polling sessions.
+ public static void ConfigureButtonBindings(IReadOnlyList bindings)
+ {
+ var controls = new List();
+ for (var i = 0; i < (bindings?.Count ?? 0); i++) {
+ var binding = bindings[i];
+ if (NativeInputApi.InputControlBinding.TryCreate((NativeInputApi.InputAction)binding.Action, i,
+ NativeInputApi.InputControlKind.Button, binding.ButtonId, 0f, binding.DeviceId, out var control)) {
+ controls.Add(control);
+ }
+ }
+ ConfigureControlBindings(controls);
+ }
+
+ public static void ConfigureControlBindings(IReadOnlyList controls)
+ {
+ _configuredControlBindings = controls?.ToArray() ?? Array.Empty();
+ TryGetExistingInstance()?.SendControlBindings();
+ }
+
+ public bool SupportsControllerButtons => _hasNativeButtons;
+ public bool SupportsControlBindings => _hasNativeControlBindings;
+
+ private void SendControlBindings()
+ {
+ if (!_initialized || !_hasNativeButtons) return;
+ var controls = _configuredControlBindings;
+ if (_hasNativeControlBindings) {
+ NativeInputApi.VpeInputSetControlBindings(controls, controls.Length);
+ return;
+ }
+ // Older plugins can still handle standalone digital bindings.
+ var buttons = new List();
+ foreach (var group in controls.GroupBy(control => (control.Action, control.Group))) {
+ if (group.Count() != 1) continue;
+ var control = group.First();
+ if (control.Kind == NativeInputApi.InputControlKind.Button
+ && NativeInputApi.InputButtonBinding.TryCreate((NativeInputApi.InputAction)control.Action,
+ control.ControlId, control.DeviceId, out var button)) buttons.Add(button);
+ }
+ NativeInputApi.VpeInputSetButtonBindings(buttons.ToArray(), buttons.Count);
+ }
+
+ public bool StartControlCapture(bool combo)
+ {
+ if (!_polling || !_hasNativeControlBindings) return false;
+ NativeInputApi.VpeInputStartControlCapture(combo ? 2 : 1);
+ return true;
+ }
+
+ public int ReadControlCapture(NativeInputApi.InputControlBinding[] controls) =>
+ _polling && _hasNativeControlBindings ? NativeInputApi.VpeInputReadControlCapture(controls, controls.Length) : 0;
+
+ public void CancelControlCapture()
+ {
+ if (_hasNativeControlBindings) NativeInputApi.VpeInputStartControlCapture(0);
+ }
+
///
/// Whether the app window currently has focus. The host sets this each frame from
/// Application.isFocused; native input events are dropped while it is false.
@@ -215,7 +296,12 @@ public static List ConfiguredBindings
public static bool AppFocused
{
get => _appFocused;
- set => _appFocused = value;
+ set {
+ if (_appFocused == value) return;
+ if (!value) _instance?.SetNativeGameplayInput(false);
+ _appFocused = value;
+ if (value) _instance?.SetNativeGameplayInput(!_gamePaused);
+ }
}
///
@@ -225,7 +311,17 @@ public static bool AppFocused
public static bool GamePaused
{
get => _gamePaused;
- set => _gamePaused = value;
+ set {
+ if (_gamePaused == value) return;
+ if (value) _instance?.SetNativeGameplayInput(false);
+ _gamePaused = value;
+ if (!value) _instance?.SetNativeGameplayInput(_appFocused);
+ }
+ }
+
+ private void SetNativeGameplayInput(bool enabled)
+ {
+ if (_hasNativeGameplayGate) NativeInputApi.VpeInputSetGameplayInputEnabled(enabled ? 1 : 0);
}
///
@@ -317,6 +413,18 @@ public IReadOnlyList ListDeviceAxes(int deviceIndex)
return result;
}
+ /// Reads the latest button snapshot without polling hardware from the caller.
+ public IReadOnlyList ListDeviceButtons(int deviceIndex)
+ {
+ if (!_initialized || !_hasNativeButtons) return Array.Empty();
+ var count = NativeInputApi.VpeInputListDeviceButtons(deviceIndex, null, 0);
+ if (count <= 0) return Array.Empty();
+ var buttons = new NativeInputApi.InputButtonInfo[count];
+ var available = NativeInputApi.VpeInputListDeviceButtons(deviceIndex, buttons, buttons.Length);
+ if (available < buttons.Length) Array.Resize(ref buttons, available);
+ return buttons;
+ }
+
///
/// Starts native input polling and sends the current action bindings to the
/// native layer.
@@ -347,6 +455,7 @@ public bool StartPolling(int pollIntervalUs = 500)
var configured = _configuredBindings;
var toSend = configured != null && configured.Count > 0 ? configured.ToArray() : _bindings.ToArray();
NativeInputApi.VpeInputSetBindings(toSend, toSend.Length);
+ SendControlBindings();
Logger.Debug("{Prefix:l} [NativeInputManager] Sent {Count} bindings ({Kind:l})", LogPrefix, toSend.Length, configured != null && configured.Count > 0 ? "custom" : "default");
// Create callback delegate (keep reference to prevent GC)
@@ -366,8 +475,8 @@ public bool StartPolling(int pollIntervalUs = 500)
Logger.Info($"{LogPrefix} [NativeInputManager] Started polling at {pollIntervalUs}us interval ({1000000 / pollIntervalUs} Hz)");
// The native side switched to its polling device enumeration; refresh the
- // index-to-device-id cache so axis events resolve against the right snapshot.
- ListDevices();
+ // cache and notify sensor consumers about the devices that actually opened.
+ OnNativeDevicesChanged();
return true;
}
@@ -561,6 +670,9 @@ public void Dispose()
{
NativeInputApi.VpeInputShutdown();
_initialized = false;
+ _hasNativeGameplayGate = false;
+ _hasNativeButtons = false;
+ _hasNativeControlBindings = false;
}
_instance = null;
diff --git a/VisualPinball.Unity/VisualPinball.Unity/Simulation/SimulationThread.cs b/VisualPinball.Unity/VisualPinball.Unity/Simulation/SimulationThread.cs
index 2045d18953..84f84e66f9 100644
--- a/VisualPinball.Unity/VisualPinball.Unity/Simulation/SimulationThread.cs
+++ b/VisualPinball.Unity/VisualPinball.Unity/Simulation/SimulationThread.cs
@@ -257,8 +257,8 @@ public void Stop()
/// Thread: Main thread only (sets volatile flag).
public void Pause()
{
- _paused = true;
NativeInputManager.GamePaused = true; // input stops at the source while paused
+ _paused = true;
}
///
@@ -313,6 +313,19 @@ public ref readonly SimulationState.Snapshot GetSharedState()
/// only when that component exists and is enabled by player settings.
///
public Action MainThreadTiltDispatcher { get; set; }
+ private sealed class TiltDispatchers
+ {
+ public readonly Action Physical;
+ public readonly Action Simulated;
+
+ public TiltDispatchers(Action physical, Action simulated)
+ {
+ Physical = physical;
+ Simulated = simulated;
+ }
+ }
+
+ private volatile TiltDispatchers _tiltDispatchers;
public Action MainThreadInputObserver { get; set; }
private readonly System.Collections.Concurrent.ConcurrentQueue<(int Action, bool Pressed, int Generation)> _inputNotifications = new();
private int _inputNotificationGeneration;
@@ -356,13 +369,20 @@ internal void ResetInputNotifications(bool? enabled = null)
///
/// When true, native cabinet Tilt input is routed to
/// instead of directly to any
- /// input-action switch mapping. This is used for real cabinet plumb bobs.
+ /// input-action switch mapping when no tilt-bob component route is set.
///
public bool DispatchPhysicalTiltInputToMainThread { get; set; }
- private readonly Queue _mainThreadTiltStates = new();
+ private readonly Queue<(Action Dispatch, bool Pressed)> _mainThreadTiltStates = new();
private readonly object _mainThreadTiltLock = new();
+ internal void SetTiltBobDispatchers(Action physical, Action simulated)
+ {
+ lock (_mainThreadTiltLock) {
+ _tiltDispatchers = physical != null || simulated != null ? new TiltDispatchers(physical, simulated) : null;
+ }
+ }
+
///
/// Flush any queued main-thread input dispatches.
///
@@ -387,21 +407,21 @@ public void FlushMainThreadInputDispatch()
}
while (true) {
- bool tiltState;
+ (Action Dispatch, bool Pressed) tiltState;
lock (_mainThreadTiltLock) {
if (_mainThreadTiltStates.Count == 0) {
break;
}
tiltState = _mainThreadTiltStates.Dequeue();
}
- MainThreadTiltDispatcher?.Invoke(tiltState);
+ tiltState.Dispatch(tiltState.Pressed);
}
}
- private void QueueMainThreadTiltState(bool tiltState)
+ private void QueueMainThreadTiltState(Action dispatch, bool pressed)
{
lock (_mainThreadTiltLock) {
- _mainThreadTiltStates.Enqueue(tiltState);
+ _mainThreadTiltStates.Enqueue((dispatch, pressed));
}
}
@@ -751,12 +771,15 @@ private void ProcessInputEvents()
InputLatencyTracker.RecordInputPolled((NativeInputApi.InputAction)actionIndex, isPressed, evt.TimestampUsec);
- if (actionIndex == (int)NativeInputApi.InputAction.Tilt
- && DispatchPhysicalTiltInputToMainThread
- && MainThreadTiltDispatcher != null) {
- QueueMainThreadTiltState(isPressed);
- _inputEventsProcessed++;
- continue;
+ if (actionIndex == (int)NativeInputApi.InputAction.Tilt) {
+ var dispatcher = _tiltDispatchers?.Physical;
+ if (dispatcher != null) {
+ QueueMainThreadTiltState(dispatcher, isPressed);
+ } else if (DispatchPhysicalTiltInputToMainThread && MainThreadTiltDispatcher is { } legacyDispatcher) {
+ QueueMainThreadTiltState(legacyDispatcher, isPressed);
+ _inputEventsProcessed++;
+ continue;
+ }
}
// Only forward to GLE once it's ready (or at least has started)
@@ -1246,18 +1269,16 @@ private void UpdatePhysics()
///
private void ProcessPlumbTiltEvents()
{
- if (MainThreadTiltDispatcher == null || DispatchPhysicalTiltInputToMainThread) {
- return;
- }
-
- _pendingPlumbTiltEvents.Clear();
- _physicsEngine.DrainPlumbTiltEvents(_pendingPlumbTiltEvents);
- if (_pendingPlumbTiltEvents.Count == 0) {
- return;
- }
-
- for (var i = 0; i < _pendingPlumbTiltEvents.Count; i++) {
- QueueMainThreadTiltState(_pendingPlumbTiltEvents[i]);
+ lock (_mainThreadTiltLock) {
+ var routes = _tiltDispatchers;
+ var dispatcher = routes != null ? routes.Simulated
+ : DispatchPhysicalTiltInputToMainThread ? null : MainThreadTiltDispatcher;
+ if (dispatcher == null) return;
+ _pendingPlumbTiltEvents.Clear();
+ _physicsEngine.DrainPlumbTiltEvents(_pendingPlumbTiltEvents);
+ foreach (var pressed in _pendingPlumbTiltEvents) {
+ _mainThreadTiltStates.Enqueue((dispatcher, pressed));
+ }
}
}
diff --git a/VisualPinball.Unity/VisualPinball.Unity/Simulation/SimulationThreadComponent.cs b/VisualPinball.Unity/VisualPinball.Unity/Simulation/SimulationThreadComponent.cs
index 1560427c99..5712107ece 100644
--- a/VisualPinball.Unity/VisualPinball.Unity/Simulation/SimulationThreadComponent.cs
+++ b/VisualPinball.Unity/VisualPinball.Unity/Simulation/SimulationThreadComponent.cs
@@ -86,6 +86,7 @@ public CabinetNudgeSensorSettings ToCabinetSettings()
/// center.
///
/// The number of mappings whose raw center was updated.
+ [Obsolete("Use NudgeSensorCalibration to collect fresh rest samples. This method captures a single snapshot.")]
public int CalibrateRawCenters(IReadOnlyList devices)
{
var count = 0;
@@ -111,23 +112,6 @@ public void ResetRawCenters()
ResetRawCenter(ref VelocityY);
}
- ///
- /// Builds a serialized mapping from a native device/axis pair.
- ///
- internal static string BuildMapping(NativeInputDeviceInfo device, NativeInputAxisInfo axis,
- SensorMappingKind kind, float scale, float rawCenter)
- {
- return new SensorMapping {
- DeviceId = device.Id,
- AxisId = axis.AxisId,
- Kind = kind,
- DeadZone = 0.02f,
- Scale = scale,
- Limit = 1f,
- RawCenter = rawCenter
- }.ToString();
- }
-
///
/// Updates one serialized mapping with the current raw axis center.
///
@@ -421,8 +405,10 @@ public void StartSimulation()
: null);
if (player != null) {
_simulationThread.MainThreadInputObserver = player.NotifyCabinetInputAction;
- _simulationThread.SetInputSwitchMappings(player.SwitchMapping
- .Where(m => m.Source == SwitchSource.InputSystem && !string.IsNullOrEmpty(m.InputAction))
+ var mappings = player.SwitchMapping;
+ _simulationThread.SetInputSwitchMappings(mappings
+ .Where(m => m.Source == SwitchSource.InputSystem && !string.IsNullOrEmpty(m.InputAction)
+ && !TiltBobComponent.OwnsTiltInputDestination(m, mappings))
.Select(m => new InputSwitchMapping(m.InputAction, m.Id, m.IsNormallyClosed))
.ToArray());
}
@@ -611,14 +597,13 @@ internal void ConfigureTiltBobRouting(TiltBobComponent tiltBob = null)
}
tiltBob ??= FindTiltBobComponent();
- if (tiltBob != null && (tiltBob.UsesSimulatedPlumb || tiltBob.UsesPhysicalTiltInput)) {
- _simulationThread.MainThreadTiltDispatcher = tiltBob.QueueTiltStateFromSimulationThread;
- _simulationThread.DispatchPhysicalTiltInputToMainThread = tiltBob.UsesPhysicalTiltInput;
+ if (tiltBob?.HasRegisteredSwitch != true) {
+ _simulationThread.SetTiltBobDispatchers(null, null);
return;
}
-
- _simulationThread.MainThreadTiltDispatcher = null;
- _simulationThread.DispatchPhysicalTiltInputToMainThread = false;
+ _simulationThread.SetTiltBobDispatchers(
+ tiltBob.UsesPhysicalTiltInput ? tiltBob.SetPhysicalTilt : null,
+ tiltBob.CreateSimulatedTiltDispatcher());
}
private TiltBobComponent FindTiltBobComponent()
@@ -707,6 +692,7 @@ public void ApplyNudgeSensorSettings()
/// not report exactly zero, while the physics-side gain calibrator continues
/// to learn velocity/acceleration scale from motion.
///
+ [Obsolete("Use NudgeSensorCalibration to collect fresh rest samples. This method captures a single snapshot.")]
public int CalibrateNudgeSensorCenters()
{
var devices = ListNudgeInputDevices();
@@ -747,47 +733,37 @@ public int ResetNudgeSensorCenters()
/// Attempts to map the first connected cabinet-style device to acceleration
/// X/Y channels.
///
- ///
- /// The heuristic prefers HID X/Y accelerometer usages, then falls back to
- /// named X/Y axes, and finally any two non-Z acceleration axes. This keeps
- /// one-click setup useful for KL25Z/Pinscape boards without hard-coding a
- /// vendor-specific device name.
- ///
public bool TryAutoConfigureFirstCabinetSensor(out string message)
{
var devices = ListNudgeInputDevices();
- for (var i = 0; i < devices.Count; i++) {
- var device = devices[i];
- if (!device.IsConnected || device.Axes == null) {
+ foreach (var device in devices.OrderByDescending(NudgeSensorSetup.IsOpenPinballDevice)) {
+ if (!NudgeSensorSetup.TryCreateCabinetSensor(device, out var sensor)) {
continue;
}
- if (TryPickAxisPair(device, out var xAxis, out var yAxis)) {
- NudgeSensors ??= new List();
- var existingSensor = NudgeSensors.Count == 0 ? null : NudgeSensors[0];
- var sensor = new SimulationThreadNudgeSensorConfig {
- Type = NudgeSensorType.CabinetDirect,
- Strength = 1f,
- CabinetMassKg = 113f,
- MountRotation = existingSensor?.MountRotation ?? NudgeSensorMountRotation.Rotation0,
- MountMirror = existingSensor?.MountMirror ?? false,
- AccelerationX = SimulationThreadNudgeSensorConfig.BuildMapping(device, xAxis,
- SensorMappingKind.Acceleration, 9.81f, xAxis.RawValue),
- AccelerationY = SimulationThreadNudgeSensorConfig.BuildMapping(device, yAxis,
- SensorMappingKind.Acceleration, 9.81f, yAxis.RawValue)
- };
- if (NudgeSensors.Count == 0) {
- NudgeSensors.Add(sensor);
- } else {
- NudgeSensors[0] = sensor;
+ NudgeSensors ??= new List();
+ if (NudgeSensors.Count > 0) {
+ var existing = NudgeSensors[0];
+ if (NudgeSensorSetup.IsOpenPinballDevice(device) && existing != null) {
+ var mappings = existing.ToEngineConfig();
+ if (devices.Any(joystick => NudgeSensorSetup.IsPinscape(joystick)
+ && NudgeSensorSetup.IsMappedToDevice(mappings, joystick.Id))) {
+ message = "A Pinscape joystick is already mapped. Select the OPD preset to switch interfaces.";
+ return false;
+ }
}
- ApplyNudgeSensorSettings();
- var deviceName = string.IsNullOrEmpty(device.Name) ? device.Id : device.Name;
- message = $"Mapped {deviceName} axes {AxisName(xAxis)}/{AxisName(yAxis)}.";
- return true;
+ sensor.mountRotation = (int)(existing?.MountRotation ?? NudgeSensorMountRotation.Rotation0);
+ sensor.mountMirror = existing?.MountMirror ?? false;
+ sensor.strength = existing?.Strength ?? 1f;
+ sensor.cabinetMassKg = existing?.CabinetMassKg ?? 113f;
+ NudgeSensors[0] = sensor.ToSimulationThreadConfig();
+ } else {
+ NudgeSensors.Add(sensor.ToSimulationThreadConfig());
}
+ ApplyNudgeSensorSettings();
+ message = $"Mapped {device.Name} acceleration X/Y. Check range and calibrate at rest.";
+ return true;
}
-
- message = "No connected input device with two usable axes was found.";
+ message = "No recognized cabinet sensor found. Map generic joystick axes manually.";
return false;
}
@@ -896,99 +872,6 @@ private void LogStatistics(in SimulationState.Snapshot state)
private static long TimestampUsec => VpeClock.NowUsec;
- ///
- /// Picks a likely X/Y axis pair from one native device.
- ///
- private static bool TryPickAxisPair(NativeInputDeviceInfo device, out NativeInputAxisInfo xAxis,
- out NativeInputAxisInfo yAxis)
- {
- xAxis = default;
- yAxis = default;
- if (TryFindAxis(device, "X", 0x30, NativeInputApi.AxisKind.Acceleration, out xAxis) &&
- TryFindAxis(device, "Y", 0x31, NativeInputApi.AxisKind.Acceleration, out yAxis) &&
- xAxis.AxisId != yAxis.AxisId) {
- return true;
- }
-
- var xSet = TryFindAxis(device, "X", 0x30, null, out xAxis);
- var ySet = TryFindAxis(device, "Y", 0x31, null, out yAxis);
- if (xSet && ySet && xAxis.AxisId != yAxis.AxisId) {
- return true;
- }
-
- for (var i = 0; i < device.Axes.Count; i++) {
- var axis = device.Axes[i];
- if (axis.Kind != NativeInputApi.AxisKind.Acceleration || IsNamedAxis(axis, "Z", 0x32)) {
- continue;
- }
- if ((xSet && axis.AxisId == xAxis.AxisId) || (ySet && axis.AxisId == yAxis.AxisId)) {
- continue;
- }
- if (!xSet) {
- xAxis = axis;
- xSet = true;
- } else {
- yAxis = axis;
- ySet = true;
- break;
- }
- }
-
- return xSet && ySet && xAxis.AxisId != yAxis.AxisId;
- }
-
- ///
- /// Finds an axis by HID usage or display name, optionally constrained by
- /// reported axis kind.
- ///
- private static bool TryFindAxis(NativeInputDeviceInfo device, string axisName, int usage,
- NativeInputApi.AxisKind? kind, out NativeInputAxisInfo axis)
- {
- if (device.Axes != null) {
- for (var i = 0; i < device.Axes.Count; i++) {
- var candidate = device.Axes[i];
- if (kind.HasValue && candidate.Kind != kind.Value) {
- continue;
- }
- if (IsNamedAxis(candidate, axisName, usage)) {
- axis = candidate;
- return true;
- }
- }
- }
- axis = default;
- return false;
- }
-
- ///
- /// Checks whether a native axis looks like the requested X/Y/Z axis.
- ///
- private static bool IsNamedAxis(NativeInputAxisInfo axis, string axisName, int usage)
- {
- if (axis.Usage == usage) {
- return true;
- }
-
- var name = axis.Name;
- if (string.IsNullOrEmpty(name)) {
- return false;
- }
- if (string.Equals(name, axisName, StringComparison.OrdinalIgnoreCase)) {
- return true;
- }
- return name.EndsWith(" " + axisName, StringComparison.OrdinalIgnoreCase)
- || name.EndsWith("-" + axisName, StringComparison.OrdinalIgnoreCase)
- || name.EndsWith("_" + axisName, StringComparison.OrdinalIgnoreCase);
- }
-
- ///
- /// Returns a human-readable axis label for inspector messages.
- ///
- private static string AxisName(NativeInputAxisInfo axis)
- {
- return string.IsNullOrEmpty(axis.Name) ? $"Axis {axis.AxisId}" : axis.Name;
- }
-
///
/// Updates smoothed simulation speed diagnostics for the inspector.
///
diff --git a/VisualPinball.Unity/VisualPinball.Unity/VPT/TiltBob/TiltBobComponent.cs b/VisualPinball.Unity/VisualPinball.Unity/VPT/TiltBob/TiltBobComponent.cs
index 9a0f8f2d12..7a2dda5b69 100644
--- a/VisualPinball.Unity/VisualPinball.Unity/VPT/TiltBob/TiltBobComponent.cs
+++ b/VisualPinball.Unity/VisualPinball.Unity/VPT/TiltBob/TiltBobComponent.cs
@@ -30,8 +30,8 @@ namespace VisualPinball.Unity
///
/// The component is the table author's routing point: map the game logic's
/// tilt switch to this device if the table should have a tilt bob. The
- /// player's cabinet settings decide whether the signal comes from the physics
- /// plumb-bob simulation or from a real physical cabinet switch.
+ /// physical cabinet switch always participates. The player can also enable
+ /// the physics plumb-bob simulation.
///
[DisallowMultipleComponent]
[PackAs("TiltBob")]
@@ -40,16 +40,14 @@ namespace VisualPinball.Unity
public sealed class TiltBobComponent : MonoBehaviour, ISwitchDeviceComponent, IPackable
{
public const string SwitchItem = "tilt_bob_switch";
- public const float DefaultDamping = 1f;
- public const float MinDamping = 0f;
- public const float MaxDamping = 2f;
- public const float DefaultThresholdAngle = 2f;
- public const float MinThresholdAngle = 0.5f;
- public const float MaxThresholdAngle = 4f;
-
- private readonly Queue _queuedTiltStates = new();
+ public const float DefaultDamping = PlumbState.DefaultDamping;
+ public const float MinDamping = PlumbState.MinDamping;
+ public const float MaxDamping = PlumbState.MaxDamping;
+ public const float DefaultThresholdAngle = PlumbState.DefaultThresholdAngle;
+ public const float MinThresholdAngle = PlumbState.MinThresholdAngle;
+ public const float MaxThresholdAngle = PlumbState.MaxThresholdAngle;
+
private readonly List _pendingSimulatedTiltStates = new(8);
- private readonly object _queuedTiltLock = new();
[Tooltip("Mechanical plumb-bob damping scale. Higher values calm the bob faster after a nudge.")]
[Range(MinDamping, MaxDamping)]
@@ -67,6 +65,10 @@ public sealed class TiltBobComponent : MonoBehaviour, ISwitchDeviceComponent, IP
[NonSerialized] private TiltBobMode _mode = TiltBobMode.Simulated;
[NonSerialized] private bool _enabled = true;
[NonSerialized] private bool _settingsApplied;
+ private (float Damping, float Threshold)? _playerTuning;
+ private bool _physicalTiltPressed;
+ private bool _simulatedTiltPressed;
+ private int _plumbDispatchGeneration;
public IEnumerable AvailableSwitches => new[] {
new GamelogicEngineSwitch(SwitchItem) { Description = "Tilt Bob" }
@@ -78,7 +80,19 @@ public sealed class TiltBobComponent : MonoBehaviour, ISwitchDeviceComponent, IP
public TiltBobMode Mode => _mode;
public bool UsesSimulatedPlumb => _enabled && _mode == TiltBobMode.Simulated;
- public bool UsesPhysicalTiltInput => _enabled && _mode == TiltBobMode.Physical;
+ public bool UsesPhysicalTiltInput => _enabled;
+ internal bool HasRegisteredSwitch => _api != null;
+
+ internal static bool OwnsTiltInputDestination(SwitchMapping mapping, IReadOnlyList mappings)
+ {
+ if (InputManager.GetCanonicalActionName(mapping.InputAction) != InputConstants.ActionTilt) return false;
+ foreach (var candidate in mappings) {
+ if (candidate.Id == mapping.Id && candidate.Source == SwitchSource.Playfield
+ && candidate.Device is TiltBobComponent bob && bob && bob.HasRegisteredSwitch
+ && candidate.DeviceItem == SwitchItem) return true;
+ }
+ return false;
+ }
public static TiltBobComponent FindFor(PhysicsEngine physicsEngine)
{
@@ -86,7 +100,7 @@ public static TiltBobComponent FindFor(PhysicsEngine physicsEngine)
return null;
}
- var table = physicsEngine.GetComponentInParent();
+ var table = physicsEngine.GetComponentInParent(true);
if (table) {
return table.GetComponentInChildren(true);
}
@@ -102,6 +116,7 @@ public static void ApplySettings(PhysicsEngine physicsEngine, CabinetPlumbSettin
var tiltBob = FindFor(physicsEngine);
if (tiltBob != null) {
+ tiltBob._physicsEngine = physicsEngine;
tiltBob.ApplySettings(settings);
return;
}
@@ -119,30 +134,47 @@ public static void ApplySettings(PhysicsEngine physicsEngine, CabinetPlumbSettin
public void UnpackReferences(byte[] bytes, Transform root, PackagedRefs refs, PackagedFiles files) { }
+ internal CabinetPlumbSettings CaptureSettings() => new() {
+ mode = _mode,
+ overrideTuning = _playerTuning.HasValue,
+ damping = _playerTuning?.Damping ?? PlumbDamping,
+ thresholdDeg = _playerTuning?.Threshold ?? PlumbThresholdAngle
+ };
+
public void ApplySettings(CabinetPlumbSettings settings)
{
settings ??= new CabinetPlumbSettings();
settings.Normalize();
+ var wasSimulated = UsesSimulatedPlumb;
_enabled = settings.enabled;
_mode = settings.mode;
+ _playerTuning = settings.overrideTuning ? (settings.damping, settings.thresholdDeg) : null;
_settingsApplied = true;
-
+ if (wasSimulated != UsesSimulatedPlumb) {
+ _plumbDispatchGeneration++;
+ _simulatedTiltPressed = false;
+ }
ConfigurePhysicsPlumb();
ConfigureSimulationThreadRouting();
+ UpdateSwitch();
}
- internal void QueueTiltStateFromSimulationThread(bool enabled)
+ internal Action CreateSimulatedTiltDispatcher()
{
- lock (_queuedTiltLock) {
- _queuedTiltStates.Enqueue(enabled);
- }
+ if (!UsesSimulatedPlumb) return null;
+ // An edge already queued by the simulation thread belongs to the
+ // mode in effect when it was drained, even after re-enabling.
+ var generation = _plumbDispatchGeneration;
+ return tilted => {
+ if (generation == _plumbDispatchGeneration) SetSimulatedTilt(tilted);
+ };
}
private void Awake()
{
- _player = GetComponentInParent();
- _physicsEngine = GetComponentInParent();
+ _player = GetComponentInParent(true);
+ _physicsEngine ??= FindPhysicsEngine();
if (_player != null && _physicsEngine != null) {
_api = new TiltBobApi(gameObject, _player, _physicsEngine);
_player.Register(_api, this);
@@ -159,8 +191,6 @@ private void Start()
private void Update()
{
- FlushQueuedTiltStates();
-
if (!UsesSimulatedPlumb || !_physicsEngine || _physicsEngine.UsesExternalTiming) {
return;
}
@@ -168,17 +198,18 @@ private void Update()
_pendingSimulatedTiltStates.Clear();
_physicsEngine.DrainPlumbTiltEvents(_pendingSimulatedTiltStates);
foreach (var tilted in _pendingSimulatedTiltStates) {
- SetSwitch(tilted);
+ SetSimulatedTilt(tilted);
}
}
private void OnDestroy()
{
_enabled = false;
+ _plumbDispatchGeneration++;
if (_player != null) {
_player.CabinetInputActionChanged -= OnCabinetInputActionChanged;
}
- _physicsEngine?.ConfigurePlumb(false, DefaultDamping, DefaultThresholdAngle);
+ if (_physicsEngine) _physicsEngine.ConfigurePlumb(false, DefaultDamping, DefaultThresholdAngle);
ConfigureSimulationThreadRouting();
}
@@ -192,46 +223,50 @@ private void OnValidate()
internal void NormalizeSettings()
{
- PlumbDamping = Mathf.Clamp(PlumbDamping, MinDamping, MaxDamping);
- PlumbThresholdAngle = Mathf.Clamp(PlumbThresholdAngle, MinThresholdAngle, MaxThresholdAngle);
+ PlumbDamping = PlumbState.ClampDamping(PlumbDamping);
+ PlumbThresholdAngle = PlumbState.ClampThresholdAngle(PlumbThresholdAngle);
}
private void OnCabinetInputActionChanged(string actionName, bool isPressed)
{
- if (UsesPhysicalTiltInput && actionName == InputConstants.ActionTilt) {
- SetSwitch(isPressed);
+ if (actionName == InputConstants.ActionTilt) {
+ SetPhysicalTilt(isPressed);
}
}
- private void FlushQueuedTiltStates()
+ internal void SetPhysicalTilt(bool tilted)
{
- while (true) {
- bool tilted;
- lock (_queuedTiltLock) {
- if (_queuedTiltStates.Count == 0) {
- return;
- }
- tilted = _queuedTiltStates.Dequeue();
- }
- SetSwitch(tilted);
- }
+ if (!UsesPhysicalTiltInput) return;
+ _physicalTiltPressed = tilted;
+ UpdateSwitch();
}
- private void SetSwitch(bool enabled)
+ private void SetSimulatedTilt(bool tilted)
{
- if (!_enabled) {
- return;
- }
- _api?.SetSwitch(enabled);
+ if (!UsesSimulatedPlumb) return;
+ _simulatedTiltPressed = tilted;
+ UpdateSwitch();
+ }
+
+ private void UpdateSwitch()
+ {
+ var tilted = _physicalTiltPressed || _simulatedTiltPressed;
+ if (_api != null && _api.IsSwitchEnabled != tilted) _api.SetSwitch(tilted);
}
private void ConfigurePhysicsPlumb()
{
NormalizeSettings();
- _physicsEngine ??= GetComponentInParent();
- _physicsEngine?.ConfigurePlumb(UsesSimulatedPlumb, PlumbDamping, PlumbThresholdAngle);
+ _physicsEngine ??= FindPhysicsEngine();
+ _physicsEngine?.ConfigurePlumb(UsesSimulatedPlumb,
+ _playerTuning?.Damping ?? PlumbDamping, _playerTuning?.Threshold ?? PlumbThresholdAngle);
}
+ private PhysicsEngine FindPhysicsEngine() =>
+ GetComponentInParent(true)
+ ?? GetComponentInParent(true)?.GetComponentInChildren(true)
+ ?? GetComponentInChildren(true);
+
private void ConfigureSimulationThreadRouting()
{
var simulationThread = _physicsEngine != null
diff --git a/VisualPinball.Unity/VisualPinball.Unity/VPT/TiltBob/TiltBobMode.cs b/VisualPinball.Unity/VisualPinball.Unity/VPT/TiltBob/TiltBobMode.cs
index 2753c6e127..2ee30013c4 100644
--- a/VisualPinball.Unity/VisualPinball.Unity/VPT/TiltBob/TiltBobMode.cs
+++ b/VisualPinball.Unity/VisualPinball.Unity/VPT/TiltBob/TiltBobMode.cs
@@ -17,19 +17,18 @@
namespace VisualPinball.Unity
{
///
- /// Selects where a table's tilt-bob switch signal comes from.
+ /// Selects whether to simulate a plumb bob alongside physical Tilt input.
///
public enum TiltBobMode
{
///
- /// Use the physics engine's simulated plumb-bob edges generated from
- /// cabinet acceleration.
+ /// Combine physical Tilt with simulated plumb-bob edges from cabinet
+ /// acceleration.
///
Simulated = 0,
///
- /// Use the player's physical cabinet tilt input, typically a real plumb bob
- /// wired into the cabinet controller.
+ /// Use physical cabinet Tilt without the simulated plumb bob.
///
Physical = 1
}