using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using jeanf.EventSystem;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
namespace jeanf.universalplayer.tests
{
///
/// Sitting on chairs, all modes. M&K/gamepad: sit teleports to the anchor, locks
/// locomotion, lowers the camera and folds the placeholder body; moving stands you
/// back up; exit restores everything. VR: teleport + root lowered so the real head
/// lands at the seat's eye height.
///
public class SittingTests
{
private GameObject _floor;
private GameObject _player;
private GameObject _chair;
private CharacterController _controller;
private PlayerMovement _movement;
private SitController _sit;
private Seat _seat;
private Transform _cameraOffset;
private bool _prevIgnoreDefaultCollision;
[UnitySetUp]
public IEnumerator SetUp()
{
_prevIgnoreDefaultCollision = Physics.GetIgnoreLayerCollision(0, 0);
Physics.IgnoreLayerCollision(0, 0, false);
BroadcastControlsStatus.controlScheme = BroadcastControlsStatus.ControlScheme.KeyboardMouse;
ResetFadeMaskToNoFadeMaskDefault();
_floor = GameObject.CreatePrimitive(PrimitiveType.Cube);
_floor.transform.localScale = new Vector3(30f, 1f, 30f);
_floor.transform.position = new Vector3(0f, -0.5f, 0f);
_player = new GameObject("Player");
_player.SetActive(false);
_player.transform.position = new Vector3(0f, 1.1f, 0f);
_controller = _player.AddComponent();
_movement = _player.AddComponent();
SetField(_movement, "controller", _controller);
SetField(_movement, "speed", 4f);
SetField(_movement, "speedChangeRate", 8f);
_cameraOffset = new GameObject("CameraOffset").transform;
_cameraOffset.SetParent(_player.transform);
_cameraOffset.localPosition = new Vector3(0f, 1.65f, 0f);
_sit = _player.AddComponent();
SetField(_sit, "playerMovement", _movement);
SetField(_sit, "controller", _controller);
SetField(_sit, "playerRoot", _player.transform);
SetField(_sit, "cameraOffset", _cameraOffset);
SetField(_sit, "exitOnMoveInput", false);
_chair = new GameObject("Chair");
_chair.transform.SetPositionAndRotation(new Vector3(3f, 0.5f, 2f), Quaternion.Euler(0f, 90f, 0f));
_chair.AddComponent(); // a real chair is aimable/grabbable; also keeps Seat.Awake quiet
_seat = _chair.AddComponent();
_player.SetActive(true);
for (var i = 0; i < 10; i++) yield return null;
}
[UnityTearDown]
public IEnumerator TearDown()
{
Physics.IgnoreLayerCollision(0, 0, _prevIgnoreDefaultCollision);
BroadcastControlsStatus.controlScheme = BroadcastControlsStatus.ControlScheme.KeyboardMouse;
Object.Destroy(_player);
Object.Destroy(_chair);
Object.Destroy(_floor);
PlayerEvents.RaiseSitInputSuppressed(false);
PlayerEvents.RaiseAllowPlayerExit(true);
yield return null;
}
private static void SetField(object target, string field, object value)
{
var info = target.GetType().GetField(field, BindingFlags.Instance | BindingFlags.NonPublic);
Assert.That(info, Is.Not.Null, $"Field '{field}' not found on {target.GetType().Name} — was it renamed? Update SittingTests alongside the refactor.");
info.SetValue(target, value);
}
///
/// FadeMask keeps its state in statics that survive across fixtures in one play
/// session: the fade/no-peeking tests leave the screen 'Clear', while this rig
/// depends on the documented no-FadeMask default — 'Loading' (ScreenFaded == true),
/// which makes every fade-gated placement instant.
///
private static void ResetFadeMaskToNoFadeMaskDefault()
{
var stateField = typeof(FadeMask).GetField("_requestedState", BindingFlags.NonPublic | BindingFlags.Static);
Assert.That(stateField, Is.Not.Null,
"FadeMask._requestedState not found — it was renamed; update SittingTests alongside the refactor.");
stateField.SetValue(null, System.Enum.ToObject(stateField.FieldType, 0)); // VisualState.Loading
typeof(FadeMask).GetField("_lastRaisedFade", BindingFlags.NonPublic | BindingFlags.Static)
?.SetValue(null, true);
}
/// Waits until a running sit/stand glide has fully applied its end state.
private IEnumerator WaitForGlide()
{
yield return new WaitUntil(() => !_sit.IsTransitioning);
}
[UnityTest]
public IEnumerator Sit_TeleportsToSeat_SetsCameraHeight_LocksMovement_AndExitRestores()
{
var preSitPosition = _player.transform.position;
_seat.ToggleSit();
yield return WaitForGlide(); // desktop sit is a short glide (sitTransitionSeconds)
Assert.That(Vector3.Distance(_player.transform.position, _chair.transform.position), Is.LessThan(0.01f),
"Sitting did not move the player to the seat anchor.");
Assert.That(_cameraOffset.localPosition.y, Is.EqualTo(0.7f).Within(0.001f),
"Camera did not drop to the seated eye height (eyeHeightAboveSeat).");
Assert.That(_controller.enabled, Is.False, "CharacterController stayed enabled while seated — gravity/collisions will fight the seat.");
Assert.That(_sit.IsSeated, Is.True);
// Locked: movement input must not move a seated player.
_movement.SetMoveValue(Vector2.up);
_movement.SetIsMoving(true);
yield return new WaitForSeconds(0.3f);
Assert.That(Vector3.Distance(_player.transform.position, _chair.transform.position), Is.LessThan(0.01f),
"A seated player moved when movement input was pressed — LocomotionLocked is not respected.");
_movement.SetIsMoving(false);
_movement.SetMoveValue(Vector2.zero);
_seat.ToggleSit();
yield return WaitForGlide(); // standing up glides too (standTransitionSeconds)
Assert.That(_sit.IsSeated, Is.False);
Assert.That(_cameraOffset.localPosition.y, Is.EqualTo(1.65f).Within(0.001f),
"Camera height was not restored after standing up.");
Assert.That(Vector3.Distance(_player.transform.position, preSitPosition), Is.LessThan(0.05f),
"Player did not return to the pre-sit position (no exitAnchor was set).");
Assert.That(_controller.enabled, Is.True, "CharacterController was not re-enabled after standing up.");
}
[UnityTest]
public IEnumerator MoveInput_StandsThePlayerBackUp()
{
SetField(_sit, "exitOnMoveInput", true);
_seat.ToggleSit();
yield return WaitForGlide(); // the sit glide outlasts the exit grace period
yield return new WaitForSeconds(0.05f);
Assert.That(_sit.IsSeated, Is.True);
_movement.SetMoveValue(Vector2.up);
_movement.SetIsMoving(true);
yield return new WaitForSeconds(0.2f);
Assert.That(_sit.IsSeated, Is.False, "Pressing a move input did not stand the player up.");
_movement.SetIsMoving(false);
_movement.SetMoveValue(Vector2.zero);
}
[UnityTest]
public IEnumerator PlaceholderBody_FoldsIntoSitPose_AndUnfoldsOnExit()
{
var bodyNode = new GameObject("Body");
bodyNode.transform.SetParent(_player.transform, false);
bodyNode.SetActive(false);
var body = bodyNode.AddComponent();
SetField(body, "playerMovement", _movement);
SetField(body, "cameraOffset", _cameraOffset);
SetField(_sit, "body", body);
bodyNode.SetActive(true);
yield return null;
var hipL = bodyNode.transform.Find("PlaceholderBody/Hip_L");
Assert.That(hipL, Is.Not.Null);
_seat.ToggleSit();
yield return new WaitForSeconds(1f);
Assert.That(Quaternion.Angle(hipL.localRotation, Quaternion.identity), Is.GreaterThan(60f),
"Placeholder legs did not fold forward into the sit pose.");
var placeholderRoot = bodyNode.transform.Find("PlaceholderBody");
Assert.That(placeholderRoot.localPosition.y, Is.LessThan(-0.4f),
"Placeholder body did not sink so its hips meet the seat.");
_seat.ToggleSit();
yield return new WaitForSeconds(1f);
Assert.That(Quaternion.Angle(hipL.localRotation, Quaternion.identity), Is.LessThan(5f),
"Placeholder legs did not unfold after standing up.");
}
[UnityTest]
public IEnumerator XrMode_LowersTheRoot_SoTheRealHeadLandsAtSeatEyeHeight()
{
// A tracked camera: in XR the HMD height comes from the device, so the sit
// logic must offset the ROOT, not the camera.
var camGo = new GameObject("MainCamera") { tag = "MainCamera" };
camGo.AddComponent();
camGo.transform.SetParent(_cameraOffset, false);
BroadcastControlsStatus.controlScheme = BroadcastControlsStatus.ControlScheme.XR;
SetField(_sit, "vrTransitionSeconds", 0f); // this test checks the geometry, not the glide
yield return null;
var cameraHeightAboveRoot = camGo.transform.position.y - _player.transform.position.y;
var preSitPosition = _player.transform.position;
_seat.ToggleSit();
yield return null;
var expectedRootY = _chair.transform.position.y + 0.7f - cameraHeightAboveRoot;
Assert.That(_player.transform.position.y, Is.EqualTo(expectedRootY).Within(0.02f),
"In XR the root must be lowered so the user's real head ends up at the seat's eye height.");
Assert.That(camGo.transform.position.y, Is.EqualTo(_chair.transform.position.y + 0.7f).Within(0.02f),
"The head did not land at seat height + eyeHeightAboveSeat.");
_seat.ToggleSit();
yield return null;
Assert.That(Vector3.Distance(_player.transform.position, preSitPosition), Is.LessThan(0.05f),
"Exiting the seat in XR did not restore the pre-sit position.");
Object.Destroy(camGo);
}
// The classic Seat and the ECS seat proxy both feed SitController through SeatData.
// If GetSeatData stops mapping the anchors, both worlds break — lock it down.
[Test]
public void Seat_GetSeatData_RoundTripsAnchors()
{
var sitAnchor = new GameObject("Sit").transform;
sitAnchor.SetParent(_chair.transform, false);
sitAnchor.SetPositionAndRotation(new Vector3(3f, 0.4f, 2f), Quaternion.Euler(0f, 45f, 0f));
var exitAnchor = new GameObject("Exit").transform;
exitAnchor.SetParent(_chair.transform, false);
exitAnchor.SetPositionAndRotation(new Vector3(4f, 0f, 2f), Quaternion.Euler(0f, 120f, 0f));
var handAnchor = new GameObject("Hand").transform;
handAnchor.SetParent(_chair.transform, false);
handAnchor.position = new Vector3(3.2f, 0.6f, 2.1f);
SetField(_seat, "sitAnchor", sitAnchor);
SetField(_seat, "exitAnchor", exitAnchor);
SetField(_seat, "eyeHeightAboveSeat", 0.65f);
SetField(_seat, "handSupportAnchor", handAnchor);
var data = _seat.GetSeatData();
Assert.That(Vector3.Distance(data.SitPosition, sitAnchor.position), Is.LessThan(0.001f), "SitPosition");
Assert.That(data.SitFacingYaw, Is.EqualTo(45f).Within(0.01f), "SitFacingYaw");
Assert.That(data.EyeHeightAboveSeat, Is.EqualTo(0.65f).Within(0.001f), "EyeHeightAboveSeat");
Assert.That(data.HasExit, Is.True, "HasExit");
Assert.That(Vector3.Distance(data.ExitPosition, exitAnchor.position), Is.LessThan(0.001f), "ExitPosition");
Assert.That(data.ExitFacingYaw, Is.EqualTo(120f).Within(0.01f), "ExitFacingYaw");
Assert.That(data.HasHandSupport, Is.True, "HasHandSupport");
Assert.That(Vector3.Distance(data.HandSupportWorldPos, handAnchor.position), Is.LessThan(0.001f), "HandSupportWorldPos");
}
// Sitting must never spin the long way round: the body slerp + free-look unwind must
// combine into the shortest turn to the seat, whatever the (unbounded) accumulated yaw.
[Test]
public void ShortestBlendLookYaw_MakesCombinedTurnTakeShortestPath()
{
AssertShortest(0f, 170f, -170f); // body +170 while look reads -170 → naive 340, shortest -20
AssertShortest(0f, 0f, 280f); // seat faces the body; a 280° stored look → shortest -80
AssertShortest(30f, 200f, 765f); // multi-turn accumulation (720 + 45)
AssertShortest(-90f, 90f, -350f);
}
private static void AssertShortest(float startYaw, float seatYaw, float lookYaw)
{
var blended = SitController.ShortestBlendLookYaw(startYaw, seatYaw, lookYaw);
// No pop: same camera orientation as the raw look (equal mod 360).
Assert.That(Mathf.DeltaAngle(lookYaw, blended), Is.EqualTo(0f).Within(0.01f),
$"blended look changed the orientation (start {startYaw}, seat {seatYaw}, look {lookYaw}).");
// Combined view turn = body slerp (rootDelta) + look unwind (-blended); it must equal the
// shortest view delta and never exceed 180°.
var combined = Mathf.DeltaAngle(startYaw, seatYaw) - blended;
var shortest = Mathf.DeltaAngle(startYaw + lookYaw, seatYaw);
Assert.That(Mathf.DeltaAngle(combined, shortest), Is.EqualTo(0f).Within(0.01f),
$"combined turn is not the shortest path (start {startYaw}, seat {seatYaw}, look {lookYaw}).");
Assert.That(Mathf.Abs(combined), Is.LessThanOrEqualTo(180.01f),
$"combined turn goes the long way (start {startYaw}, seat {seatYaw}, look {lookYaw}).");
}
// The entity-world path: SitController driven by a raw SeatData with NO Seat GameObject —
// exactly what the baked-seat proxy does. Proves sit/stand work without a live Seat.
[UnityTest]
public IEnumerator SitOn_WithRawSeatData_SitsAndExits()
{
var preSit = _player.transform.position;
var sitPos = new Vector3(3f, 0.5f, 2f);
var data = new SeatData(
seatId: 123, name: "RawSeat",
sitPosition: sitPos, sitFacingYaw: 90f,
eyeHeightAboveSeat: 0.7f,
hasExit: false, exitPosition: Vector3.zero, exitFacingYaw: 0f,
hasHandSupport: false, handSupportWorldPos: Vector3.zero, handSupportWorldRot: Quaternion.identity);
_sit.SitOn(data, true); // instant: teleport, no glide
yield return null;
Assert.That(_sit.IsSeated, Is.True, "SitOn(SeatData) did not seat the player.");
Assert.That(Vector3.Distance(_player.transform.position, sitPos), Is.LessThan(0.01f),
"SitOn(SeatData) did not teleport to the sit position.");
Assert.That(_cameraOffset.localPosition.y, Is.EqualTo(0.7f).Within(0.001f),
"SitOn(SeatData) did not set the seated eye height.");
_sit.Exit(true);
yield return null;
Assert.That(_sit.IsSeated, Is.False, "Exit did not stand the player up.");
Assert.That(Vector3.Distance(_player.transform.position, preSit), Is.LessThan(0.05f),
"Exit did not restore the pre-sit position (no exitAnchor was set).");
}
// ---- VR stand-up: left stick held past standUpHoldSeconds (v1.6.0) ----
// In VR the seat interactable is SIT-ONLY; standing is exclusively the left stick,
// debounced two ways: a fresh push is required (a stick already held when sitting
// down must be released first) and the push must be HELD for standUpHoldSeconds.
private void EnterXrSeated(out float holdSeconds)
{
holdSeconds = 0.2f;
SetField(_sit, "standUpHoldSeconds", holdSeconds);
SetField(_sit, "exitGraceSeconds", 0.15f);
SetField(_sit, "vrTransitionSeconds", 0f); // glide off: stick tests need deterministic timing
BroadcastControlsStatus.controlScheme = BroadcastControlsStatus.ControlScheme.XR;
_seat.SitOnly();
Assert.That(_sit.IsSeated, Is.True, "SitOnly did not seat the player in XR mode.");
}
[UnityTest]
public IEnumerator VrStick_HeldPastThreshold_StandsUp()
{
EnterXrSeated(out var holdSeconds);
yield return new WaitForSeconds(0.3f); // past the exit grace, stick released -> armed
_movement.SetIsMoving(true);
yield return new WaitForSeconds(holdSeconds * 0.4f);
Assert.That(_sit.IsSeated, Is.True,
"The player stood up BEFORE the stick was held for standUpHoldSeconds — the hold debounce is gone.");
yield return new WaitForSeconds(holdSeconds * 1.5f);
Assert.That(_sit.IsSeated, Is.False,
"Holding the left stick past standUpHoldSeconds did not stand the player up in VR.");
_movement.SetIsMoving(false);
}
[UnityTest]
public IEnumerator VrStick_ShortFlick_DoesNotStand()
{
EnterXrSeated(out var holdSeconds);
yield return new WaitForSeconds(0.3f);
_movement.SetIsMoving(true);
yield return new WaitForSeconds(holdSeconds * 0.4f); // released before the threshold
_movement.SetIsMoving(false);
yield return new WaitForSeconds(holdSeconds * 2f);
Assert.That(_sit.IsSeated, Is.True,
"A short stick flick (released before standUpHoldSeconds) stood the player up — it must not.");
}
[UnityTest]
public IEnumerator VrStick_HeldThroughSit_NeedsAFreshPush()
{
// Walked INTO the chair holding the stick: that same hold must never pop the player
// back up — the stick has to be released and pushed again.
_movement.SetIsMoving(true);
EnterXrSeated(out var holdSeconds);
yield return new WaitForSeconds(0.3f + holdSeconds * 2f);
Assert.That(_sit.IsSeated, Is.True,
"A stick held from BEFORE sitting down stood the player up — the fresh-push debounce is gone.");
_movement.SetIsMoving(false); // release -> re-arm
yield return null;
_movement.SetIsMoving(true); // fresh push
yield return new WaitForSeconds(holdSeconds * 1.5f);
Assert.That(_sit.IsSeated, Is.False,
"After releasing and re-pushing the stick, the player must stand up.");
_movement.SetIsMoving(false);
}
// The completed hold is narrated on the LEFT controller: growing "charge" pulses
// while the stick is held, then one full-strength burst when the player stands.
[UnityTest]
public IEnumerator VrStick_HapticCharge_GrowsThenBursts()
{
var pulses = new List<(string hand, float amplitude, float duration)>();
HandVibration.VibrateHandDelegate recorder = (hand, amplitude, duration) => pulses.Add((hand, amplitude, duration));
HandVibration.VibrateHand += recorder;
try
{
EnterXrSeated(out var holdSeconds);
yield return new WaitForSeconds(0.3f); // past the grace, stick released -> armed
_movement.SetIsMoving(true);
yield return new WaitForSeconds(holdSeconds * 1.5f);
_movement.SetIsMoving(false);
Assert.That(_sit.IsSeated, Is.False, "Sanity: the held stick must stand the player up.");
Assert.That(pulses.Count, Is.GreaterThanOrEqualTo(3),
"The stand-up hold must emit charge pulses while the stick is held.");
Assert.That(pulses.TrueForAll(p => p.hand == "Left"), Is.True,
"Stand-up haptics must go to the LEFT controller — that stick does the standing.");
Assert.That(pulses[pulses.Count - 1].amplitude, Is.EqualTo(1f).Within(0.001f),
"Completing the hold must end on the full-strength burst (standUpBurstAmplitude).");
Assert.That(pulses[0].amplitude, Is.LessThan(pulses[pulses.Count - 2].amplitude),
"The charge must GROW: the first pulse must be weaker than the last one before the burst.");
}
finally
{
HandVibration.VibrateHand -= recorder;
}
}
// A released stick means silence: a short flick must not leave haptics running
// (each pulse is ~ChargePulseSeconds long, so no explicit stop call is needed —
// but no NEW pulses may arrive after the release).
[UnityTest]
public IEnumerator VrStick_ReleaseDuringCharge_StopsThePulses()
{
var pulses = new List<(string hand, float amplitude, float duration)>();
HandVibration.VibrateHandDelegate recorder = (hand, amplitude, duration) => pulses.Add((hand, amplitude, duration));
HandVibration.VibrateHand += recorder;
try
{
EnterXrSeated(out var holdSeconds);
yield return new WaitForSeconds(0.3f);
_movement.SetIsMoving(true);
yield return new WaitForSeconds(holdSeconds * 0.4f);
_movement.SetIsMoving(false); // released before the threshold
var pulsesAtRelease = pulses.Count;
yield return new WaitForSeconds(holdSeconds);
Assert.That(_sit.IsSeated, Is.True, "Sanity: a short flick must not stand the player up.");
Assert.That(pulses.Count, Is.EqualTo(pulsesAtRelease),
"Charge pulses kept firing after the stick was released — haptics must fall silent on a cancel.");
}
finally
{
HandVibration.VibrateHand -= recorder;
}
}
// ---- VR trigger-to-sit: aim a hand at the chair, pull the trigger (v1.8.0) ----
// The old path subscribed to "XRI LeftHand/Activate" on playerInput.actions — but that
// is PlayerInput's PRIVATE CLONE of the asset and PlayerInput only enables its FPS map,
// so the action never fired. The trigger is now polled at device level (probe seam) and
// the pressing hand's aim is raycast for a seat.
[UnityTest]
public IEnumerator VrTrigger_AimedAtSeat_Sits()
{
SetField(_sit, "vrTransitionSeconds", 0f);
BroadcastControlsStatus.controlScheme = BroadcastControlsStatus.ControlScheme.XR;
var triggerValue = 0f;
_sit.TriggerProbe = hand => hand == HandType.Right ? triggerValue : 0f;
// Hand half a meter to the chair's left, aiming straight at it.
_sit.AimProbe = hand => new Ray(_chair.transform.position + new Vector3(-1.5f, 0f, 0f), Vector3.right);
yield return null; // one polled frame with the trigger released (rising-edge baseline)
triggerValue = 1f;
yield return null;
yield return null;
Assert.That(_sit.IsSeated, Is.True,
"Pulling the trigger while the hand aims at a seat must sit the player (ray + trigger, not just grab).");
}
[UnityTest]
public IEnumerator VrTrigger_AimedAway_DoesNotSit()
{
SetField(_sit, "vrTransitionSeconds", 0f);
BroadcastControlsStatus.controlScheme = BroadcastControlsStatus.ControlScheme.XR;
var triggerValue = 0f;
_sit.TriggerProbe = hand => hand == HandType.Right ? triggerValue : 0f;
_sit.AimProbe = hand => new Ray(_chair.transform.position + new Vector3(-1.5f, 0f, 0f), Vector3.left);
yield return null;
triggerValue = 1f;
yield return null;
yield return null;
Assert.That(_sit.IsSeated, Is.False,
"A trigger pull with no seat under the hand's aim must not sit the player.");
}
// ---- VR glide: sitting/standing moves the root over vrTransitionSeconds (v1.8.0) ----
[UnityTest]
public IEnumerator VrSit_GlidesToTheSeat_InsteadOfTeleporting()
{
SetField(_sit, "vrTransitionSeconds", 0.4f);
BroadcastControlsStatus.controlScheme = BroadcastControlsStatus.ControlScheme.XR;
var start = _player.transform.position;
_seat.SitOnly();
// The glide's first step runs synchronously at s=0 — the root must still be at
// the start, proving this is a glide and not the old hard teleport.
Assert.That(_sit.IsSeated, Is.True, "SitOnly must seat the player immediately (state), even while gliding.");
Assert.That(Vector3.Distance(_player.transform.position, start), Is.LessThan(0.001f),
"The root teleported on the same frame — the VR sit must GLIDE when vrTransitionSeconds > 0.");
yield return new WaitForSeconds(1f);
var horizontal = _player.transform.position - _chair.transform.position;
horizontal.y = 0f;
Assert.That(horizontal.magnitude, Is.LessThan(0.01f),
"The glide did not arrive at the seat anchor.");
_sit.Exit();
Assert.That(_controller.enabled, Is.False,
"The CharacterController must stay disabled until the stand-up glide completes.");
yield return new WaitForSeconds(1f);
Assert.That(Vector3.Distance(_player.transform.position, start), Is.LessThan(0.05f),
"The stand-up glide did not return to the pre-sit position (no exitAnchor was set).");
Assert.That(_controller.enabled, Is.True,
"The CharacterController was not re-enabled after the stand-up glide.");
}
// A teleport lands the player somewhere else entirely — by definition they are
// standing there. The seated state must be released IN PLACE: standing up later
// must never slide them back in front of the chair they teleported away from.
[UnityTest]
public IEnumerator Teleport_WhileSeated_ReleasesTheSeat_WithoutSlidingBack()
{
_seat.ToggleSit();
yield return WaitForGlide();
Assert.That(_sit.IsSeated, Is.True, "Sanity: the player must be seated before the teleport.");
var destination = new GameObject("TeleportDestination").transform;
destination.SetPositionAndRotation(new Vector3(20f, 1.1f, -7f), Quaternion.identity);
_player.transform.SetPositionAndRotation(destination.position, destination.rotation);
PlayerEvents.RaisePlayerTeleported(new TeleportInformation(
_player.transform, destination, true, null, false, false)); // what TeleportOnEvent raises after moving the player
yield return null;
Assert.That(_sit.IsSeated, Is.False,
"A teleported player is standing by definition — the seated state was not released.");
Assert.That(_controller.enabled, Is.True,
"The CharacterController must come back when a teleport releases the seat.");
Assert.That(_cameraOffset.localPosition.y, Is.EqualTo(1.65f).Within(0.001f),
"The standing camera height must be restored when a teleport releases the seat.");
Assert.That(Vector3.Distance(_player.transform.position, destination.position), Is.LessThan(0.05f),
"Releasing the seat after a teleport must NOT move the player back toward the chair.");
// A stand-up arriving later must be a no-op — this was the reported bug:
// sit → teleport → stand slid the player back in front of the chair.
_sit.Exit();
yield return null;
Assert.That(Vector3.Distance(_player.transform.position, destination.position), Is.LessThan(0.05f),
"Standing up after a teleport slid the player back to the chair.");
Object.Destroy(destination.gameObject);
}
// Scenario placement: enabling a SitPlayerOnEnable must put the player in its seat.
// With no FadeMask in the scene ScreenFaded defaults to true (loading state), so the
// fade-gated path places instantly — exactly the scenario-load situation it exists for.
[UnityTest]
public IEnumerator SitPlayerOnEnable_SeatsThePlayer_OnItsSeat()
{
var trigger = new GameObject("ForceSit");
trigger.SetActive(false);
var force = trigger.AddComponent();
SetField(force, "seat", _seat);
trigger.SetActive(true);
for (var i = 0; i < 5; i++) yield return null;
Assert.That(_sit.IsSeated, Is.True, "Enabling SitPlayerOnEnable did not seat the player.");
Assert.That(_sit.CurrentSeatId, Is.EqualTo(_seat.GetSeatData().SeatId),
"The player was seated, but not on the seat referenced by SitPlayerOnEnable.");
Assert.That(Vector3.Distance(_player.transform.position, _chair.transform.position), Is.LessThan(0.01f),
"Screen-faded placement must be instant — the player is not at the seat anchor.");
Object.Destroy(trigger);
_sit.Exit(true);
yield return null;
}
// ---- Seat Id targeting: SeatRegistry + SitPlayerOnEnable by id (both worlds) ----
private void GiveChairSeatId(int id)
{
// Registration happens in Seat.OnEnable, so the id must be set across a re-enable.
_chair.SetActive(false);
SetField(_seat, "seatId", id);
_chair.SetActive(true);
}
[Test]
public void SeatRegistry_ResolvesById_AndForgetsDisabledSeats()
{
GiveChairSeatId(777);
Assert.That(SeatRegistry.TryGetSeatData(777, out var data), Is.True,
"A live Seat with a Seat Id must be resolvable through the SeatRegistry.");
Assert.That(data.SeatId, Is.EqualTo(777), "The resolved SeatData must carry the authored id.");
Assert.That(Vector3.Distance(data.SitPosition, _chair.transform.position), Is.LessThan(0.001f),
"The resolved SeatData does not point at the seat's sit anchor.");
_chair.SetActive(false);
Assert.That(SeatRegistry.TryGetSeatData(777, out _), Is.False,
"A disabled Seat must unregister — resolving its id would seat the player on a dead chair.");
_chair.SetActive(true);
}
// The exact cross-scene / SubScene scenario shape: the trigger holds NO direct seat
// reference, only the authored id, and resolves through the registry.
[UnityTest]
public IEnumerator SitPlayerOnEnable_BySeatId_SeatsThePlayer()
{
GiveChairSeatId(778);
var trigger = new GameObject("ForceSitById");
trigger.SetActive(false);
var force = trigger.AddComponent();
SetField(force, "seatId", 778); // no Seat reference on purpose
trigger.SetActive(true);
for (var i = 0; i < 5; i++) yield return null;
Assert.That(_sit.IsSeated, Is.True, "SitPlayerOnEnable (by Seat Id) did not seat the player.");
Assert.That(_sit.CurrentSeatId, Is.EqualTo(778),
"The player was seated, but not on the seat with the targeted id.");
Object.Destroy(trigger);
_sit.Exit(true);
yield return null;
}
// The bridge-proxy path for a SitPlayerOnEnable BAKED into a SubScene: the MonoBehaviour
// is stripped there, so SeatDataBridge spawns a proxy GO hosting the component with the
// seat pre-resolved from the entity world (ConfigureResolved) — this is that flow minus
// the ECS query, which needs a baked world.
[UnityTest]
public IEnumerator SitPlayerOnEnable_PreResolved_SeatsThePlayer()
{
var data = new SeatData(
seatId: 900, name: "BakedSeat", sitPosition: new Vector3(5f, 0.5f, -3f), sitFacingYaw: 180f,
eyeHeightAboveSeat: 0.7f, hasExit: false, exitPosition: Vector3.zero, exitFacingYaw: 0f,
hasHandSupport: false, handSupportWorldPos: Vector3.zero, handSupportWorldRot: Quaternion.identity);
var proxy = new GameObject("ForceSitProxy");
proxy.SetActive(false);
var force = proxy.AddComponent();
force.ConfigureResolved(data, fadeToBlack: true, holdBlack: 0f);
proxy.SetActive(true);
for (var i = 0; i < 5; i++) yield return null;
Assert.That(_sit.IsSeated, Is.True, "A pre-resolved SitPlayerOnEnable (bridge proxy) did not seat the player.");
Assert.That(_sit.CurrentSeatId, Is.EqualTo(900), "The player is not on the pre-resolved seat.");
Assert.That(Vector3.Distance(_player.transform.position, data.SitPosition), Is.LessThan(0.01f),
"The player was not placed at the pre-resolved sit position.");
Object.Destroy(proxy);
_sit.Exit(true);
yield return null;
}
[UnityTest]
public IEnumerator RequestSit_SwapsSeats_AndNoOpsOnSameSeat()
{
SeatData Raw(int id, Vector3 pos) => new SeatData(
seatId: id, name: $"Raw{id}", sitPosition: pos, sitFacingYaw: 0f, eyeHeightAboveSeat: 0.7f,
hasExit: false, exitPosition: Vector3.zero, exitFacingYaw: 0f,
hasHandSupport: false, handSupportWorldPos: Vector3.zero, handSupportWorldRot: Quaternion.identity);
var seatA = Raw(41, new Vector3(2f, 0.5f, 0f));
var seatB = Raw(42, new Vector3(-2f, 0.5f, 4f));
_sit.RequestSit(seatA); // no FadeMask in the rig -> ScreenFaded defaults true -> instant
yield return null;
Assert.That(_sit.CurrentSeatId, Is.EqualTo(41), "RequestSit did not seat the player.");
_sit.RequestSit(seatA); // same seat: must be a no-op, not a stand-up
yield return null;
Assert.That(_sit.IsSeated, Is.True, "RequestSit on the CURRENT seat must be a no-op.");
_sit.RequestSit(seatB); // different seat: silent swap
yield return null;
Assert.That(_sit.CurrentSeatId, Is.EqualTo(42), "RequestSit did not swap to the other seat.");
Assert.That(Vector3.Distance(_player.transform.position, seatB.SitPosition), Is.LessThan(0.01f),
"The swap did not move the player to the new seat.");
_sit.Exit(true);
yield return null;
}
[UnityTest]
public IEnumerator SeatInteractable_IsSitOnly_WhileSeated()
{
EnterXrSeated(out _);
var seatedPosition = _player.transform.position;
// Grabbing/triggering the chair again must NOT stand the player up (no toggle).
_seat.SitOnly();
_sit.SitOn(_seat);
yield return null;
Assert.That(_sit.IsSeated, Is.True,
"Selecting the seat while seated stood the player up — the interactable must be sit-only.");
Assert.That(Vector3.Distance(_player.transform.position, seatedPosition), Is.LessThan(0.001f),
"A repeated select while seated moved the player.");
}
// ---- Asymmetric input (v1.20.0): Interact sits only; Jump / VR stick stands ----
[UnityTest]
public IEnumerator SeatedInteract_DoesNotStand()
{
_seat.ToggleSit();
yield return WaitForGlide();
Assert.That(_sit.IsSeated, Is.True, "Sanity: the player must be seated.");
_sit.HandleInteract();
yield return null;
Assert.That(_sit.IsSeated, Is.True,
"Interact while seated stood the player up — Interact must sit only (Jump / VR stick stand).");
}
[UnityTest]
public IEnumerator Jump_WhileSeated_StandsUp()
{
SetField(_sit, "exitGraceSeconds", 0f);
_seat.ToggleSit();
yield return WaitForGlide();
Assert.That(_sit.IsSeated, Is.True, "Sanity: the player must be seated.");
_sit.HandleJump();
yield return WaitForGlide();
Assert.That(_sit.IsSeated, Is.False,
"Jump while seated did not stand the player up.");
}
[UnityTest]
public IEnumerator OccupiedSeat_IsRefused_AndRaisesInvalidAction()
{
var signaled = false;
System.Action onInvalid = () => signaled = true;
PlayerEvents.InvalidActionSignaled += onInvalid;
try
{
_seat.SetOccupied(true);
_sit.SitOn(_seat);
yield return null;
Assert.That(_sit.IsSeated, Is.False,
"SitOn accepted an occupied seat — player sit must refuse occupancy.");
Assert.That(signaled, Is.True,
"Refusing an occupied seat must raise PlayerEvents.RaiseInvalidAction().");
}
finally
{
PlayerEvents.InvalidActionSignaled -= onInvalid;
_seat.SetOccupied(false);
}
}
[UnityTest]
public IEnumerator OccupiedSeat_ScenarioForceSit_StillSits()
{
_seat.SetOccupied(true);
_sit.SitOn(_seat, true, true); // scenario force, including silent swap onto an occupied seat
yield return null;
Assert.That(_sit.IsSeated, Is.True,
"Scenario SitOn(..., force: true) must still seat the player on an occupied chair.");
_sit.Exit(true);
yield return null;
}
[UnityTest]
public IEnumerator InputLock_SuppressesJumpExit_ButScenarioExitStillWorks()
{
SetField(_sit, "exitGraceSeconds", 0f);
_seat.ToggleSit();
yield return WaitForGlide();
Assert.That(_sit.IsSeated, Is.True, "Sanity: the player must be seated.");
PlayerEvents.RaiseSitInputSuppressed(true);
_sit.HandleJump();
_sit.HandleInteract();
yield return null;
Assert.That(_sit.IsSeated, Is.True,
"Jump/Interact while SitInputSuppressed stood the player up — the iPad/UI lock must skip player Exit.");
_sit.Exit(true); // scenario / cinematic stand is not gated
yield return null;
Assert.That(_sit.IsSeated, Is.False,
"Direct Exit() must still stand the player while input is suppressed (scenario sit/stand).");
PlayerEvents.RaiseSitInputSuppressed(false);
}
[UnityTest]
public IEnumerator AllowPlayerExitFalse_SuppressesJump_UntilUnlocked()
{
SetField(_sit, "exitGraceSeconds", 0f);
_seat.ToggleSit();
yield return WaitForGlide();
PlayerEvents.RaiseAllowPlayerExit(false);
_sit.HandleJump();
yield return null;
Assert.That(_sit.IsSeated, Is.True,
"Jump while AllowPlayerExit is false stood the player up — the cinematic lock must skip player Exit.");
PlayerEvents.RaiseAllowPlayerExit(true);
_sit.HandleJump();
yield return WaitForGlide();
Assert.That(_sit.IsSeated, Is.False,
"Jump after unlocking AllowPlayerExit must stand the player up.");
}
}
}