acdream/tests/AcDream.App.Tests/Input/MouseLookControllerTests.cs
Erik a7529a975a test(app): serialize the classes sharing camera/render process globals (#252)
A full Release App run failed once at Issue181WallPressEquilibriumTests
.Diagnostic_WallPressedCamera_EyeWanderAndViewerCellStability. It passed in
isolation and did not recur across five further whole-suite runs, and the diff
under test touched only the world texture-creation stack -- nothing in camera,
visibility or physics. A cross-class parallelism race was the only plausible
mechanism, not a regression.

Ten App test classes share three process-global mutable statics, and xUnit runs
distinct test classes in parallel by default:

  - CameraDiagnostics: AlignToSlope, CollideCamera, TranslationStiffness,
    RotationStiffness, UseRetailChaseCamera. These are not merely written, they
    are written AWAY from their defaults -- RetailChaseCameraTests sets
    AlignToSlope and CollideCamera to false, and three classes set
    UseRetailChaseCamera to false -- while RetailChaseCamera.Update,
    CameraController.Active, CameraFrameController, WorldRenderFrameBuilder and
    MouseLookController read them.
  - RenderingDiagnostics.ProbeFlapEnabled, written by CornerFloodReplayTests
    and Issue181WallPressEquilibriumTests.
  - System.Console.Out, redirected by those same two classes to capture probe
    output.

Every one of these classes already saved and restored in try/finally. That is
correct within a class and remains necessary, but it was never sufficient. A
finally bounds a mutation in TIME along its own thread; it cannot stop another
class from reading the static inside that window. Worse, two overlapping
save/restore pairs can interleave so the second restore writes back the FIRST
one's temporary value, leaving the global permanently wrong for the rest of the
run. The Console.Out case is the sharpest instance: an interleaved restore can
install a DISPOSED StringWriter as the process-wide Console.Out, which then
throws in unrelated tests. Serializing the sharers is what makes each class's
existing finally sufficient.

The fix is a marker CollectionDefinition applied to the ten sharing classes,
following the WorldEnvironmentControllerCollection precedent. No collection
fixture: several members are [Theory] cases that need different knob values per
case, so a fixture cannot own the save/restore without rewriting every member's
internals, and it would not help the read side at all. Because every member
references the same compile-time const for the collection name, the grouping
cannot silently drift via a typo.

Membership is deliberately narrow. It covers the eight writers plus two classes
that drive production code which READS a knob another member moves off its
default (HouseExitWalkReplayTests and CameraFrameControllerTests both run
RetailChaseCamera.Update and assert on the resulting eye). Classes that merely
construct a CameraController without a retail chase camera are NOT members --
their reads fall through the null branch and are insensitive.

No production code changed; no assertion was weakened, and no retry, sleep or
tolerance was added.

Verification. Base commit f6275f45 measured empirically at 3,763 passed / 3
skipped. Post-fix: 136 whole-suite Release runs. Every failure observed was in
the pre-existing zero-allocation family tracked as #250 (an Expected 0 / Actual
N bytes assertion), and none was in any collection member. A matched 55-run
baseline at f6275f45 reproduced that same family, confirming it predates this
change. Serialization cost is inside run-to-run noise: the suite is ~3 s of a
~4.5 s wall-clock dotnet test, and the ten serialized classes are a small
fraction of it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-28 18:46:43 +02:00

310 lines
9.9 KiB
C#

using System.Numerics;
using AcDream.App.Input;
using AcDream.App.Net;
using AcDream.App.Rendering;
using AcDream.Core.Net;
using AcDream.Core.Physics;
using AcDream.Core.Rendering;
using AcDream.UI.Abstractions.Input;
using Silk.NET.Input;
namespace AcDream.App.Tests.Input;
[Collection(AcDream.App.Tests.Rendering.CameraDiagnosticsCollection.Name)]
public sealed class MouseLookControllerTests
{
[Fact]
public void InstantMouseLookRequiresPlayerChaseAndInWorldState()
{
Harness harness = CreateHarness();
Assert.True(harness.Owner.HandlePointerAction(
InputAction.CameraInstantMouseLook,
ActivationType.Press));
Assert.False(harness.Owner.Active);
harness.Mode.IsPlayerMode = true;
harness.EnterChase();
harness.Player.State = PlayerState.PortalSpace;
harness.Owner.HandlePointerAction(
InputAction.CameraInstantMouseLook,
ActivationType.Press);
Assert.False(harness.Owner.Active);
harness.Player.State = PlayerState.InWorld;
harness.Owner.HandlePointerAction(
InputAction.CameraInstantMouseLook,
ActivationType.Press);
Assert.True(harness.Owner.Active);
Assert.Equal(1, harness.Cursor.HideCount);
}
[Fact]
public void ReleaseEndsMouseLookAndRestoresCursorExactlyOnce()
{
Harness harness = CreateActiveHarness();
harness.Owner.HandlePointerAction(
InputAction.CameraInstantMouseLook,
ActivationType.Release);
harness.Owner.HandlePointerAction(
InputAction.CameraInstantMouseLook,
ActivationType.Release);
Assert.False(harness.Owner.Active);
Assert.Equal(1, harness.Cursor.RestoreCount);
Assert.False(harness.Player.EndMouseLook(new MovementInput()));
}
[Fact]
public void UiCaptureTransitionEndsActiveMouseLook()
{
Harness harness = CreateActiveHarness();
harness.Mouse.WantCaptureMouse = true;
harness.Owner.Tick();
Assert.False(harness.Owner.Active);
Assert.Equal(1, harness.Cursor.RestoreCount);
Assert.False(harness.Player.EndMouseLook(new MovementInput()));
}
[Fact]
public void SessionResetRestoresCaptureAndClearsRmbOrbitWithoutWireSend()
{
Harness harness = CreateActiveHarness();
harness.Owner.HandlePointerAction(
InputAction.AcdreamRmbOrbitHold,
ActivationType.Press);
Assert.True(harness.Chase.RmbOrbitHeld);
harness.Owner.ResetSession();
Assert.False(harness.Owner.Active);
Assert.False(harness.Chase.RmbOrbitHeld);
Assert.Equal(1, harness.Cursor.RestoreCount);
Assert.Null(harness.Session.CurrentSession);
}
[Fact]
public void SixRawSamplesCrossRetailExtentGateAndSubmitTurnMotion()
{
Harness harness = CreateActiveHarness();
for (int i = 0; i < 6; i++)
{
harness.Clock.NowSeconds += 0.01f;
harness.Owner.QueueRawDelta(2f, 0f);
harness.Owner.Tick();
}
MovementResult result = harness.Player.Update(
PhysicsBody.MinQuantum + 0.001f,
new MovementInput());
Assert.NotNull(result.TurnCommand);
}
[Fact]
public void StrictIdleBoundaryStopsMouseDriftOnlyAfterPointTwoSeconds()
{
bool previousRetailCamera = CameraDiagnostics.UseRetailChaseCamera;
CameraDiagnostics.UseRetailChaseCamera = false;
try
{
Harness harness = CreateActiveHarness();
for (int i = 0; i < 6; i++)
{
harness.Clock.NowSeconds += 0.01f;
harness.Owner.QueueRawDelta(2f, 0f);
harness.Owner.Tick();
}
MovementResult turning = harness.Player.Update(
PhysicsBody.MinQuantum + 0.001f,
new MovementInput(Run: true));
Assert.NotNull(turning.TurnCommand);
float boundary = harness.Clock.NowSeconds
+ MouseLookState.IdleZeroDelaySeconds;
harness.Clock.NowSeconds = boundary;
harness.Owner.Tick();
MovementResult held = harness.Player.Update(
PhysicsBody.MinQuantum + 0.001f,
new MovementInput(Run: true));
Assert.NotNull(held.TurnCommand);
harness.Clock.NowSeconds = boundary + 0.0001f;
harness.Owner.Tick();
MovementResult stopped = harness.Player.Update(
PhysicsBody.MinQuantum + 0.001f,
new MovementInput(Run: true));
Assert.Null(stopped.TurnCommand);
}
finally
{
CameraDiagnostics.UseRetailChaseCamera = previousRetailCamera;
}
}
[Fact]
public void LifecycleExitAlsoClearsRmbOrbitLatch()
{
Harness harness = CreateActiveHarness();
harness.Owner.HandlePointerAction(
InputAction.AcdreamRmbOrbitHold,
ActivationType.Press);
Assert.True(harness.Chase.RmbOrbitHeld);
harness.Owner.EndForLifecycle();
Assert.False(harness.Owner.Active);
Assert.False(harness.Chase.RmbOrbitHeld);
Assert.False(harness.Player.EndMouseLook(new MovementInput()));
}
[Fact]
public void RmbOrbitLatchOnlyEngagesInPlayerChaseMode()
{
Harness harness = CreateHarness();
harness.Owner.HandlePointerAction(
InputAction.AcdreamRmbOrbitHold,
ActivationType.Press);
Assert.False(harness.Chase.RmbOrbitHeld);
harness.Mode.IsPlayerMode = true;
harness.EnterChase();
harness.Owner.HandlePointerAction(
InputAction.AcdreamRmbOrbitHold,
ActivationType.Press);
Assert.True(harness.Chase.RmbOrbitHeld);
harness.Owner.HandlePointerAction(
InputAction.AcdreamRmbOrbitHold,
ActivationType.Release);
Assert.False(harness.Chase.RmbOrbitHeld);
}
private static Harness CreateActiveHarness()
{
Harness harness = CreateHarness();
harness.Mode.IsPlayerMode = true;
harness.EnterChase();
harness.Owner.HandlePointerAction(
InputAction.CameraInstantMouseLook,
ActivationType.Press);
Assert.True(harness.Owner.Active);
return harness;
}
private static Harness CreateHarness()
{
PlayerMovementController player = CreatePlayer();
var mode = new LocalPlayerModeState();
var slot = new RuntimeLocalPlayerMovementState { Controller = player };
var camera = new CameraController(new OrbitCamera(), new FlyCamera());
var chase = new ChaseCameraInputState();
var mouse = new FakeMouse();
var pointer = new PointerPositionState { X = 320f, Y = 240f };
var movement = new FixedMovementInputSource();
var cursor = new FakeCursor();
var clock = new FakeClock();
var session = new NullSessionSource();
var outbound = new LocalPlayerOutboundController(
static (_, _, _, _, _, _) => { });
var owner = new MouseLookController(
mouse,
pointer,
mode,
slot,
camera,
chase,
movement,
outbound,
session,
cursor,
clock);
return new Harness(owner, mode, player, camera, chase, mouse, cursor, clock, session);
}
private static PlayerMovementController CreatePlayer()
{
var engine = new PhysicsEngine();
var heights = new byte[81];
Array.Fill(heights, (byte)50);
var heightTable = new float[256];
for (int i = 0; i < heightTable.Length; i++)
heightTable[i] = i;
engine.AddLandblock(
0xA9B4FFFFu,
new TerrainSurface(heights, heightTable),
Array.Empty<CellSurface>(),
Array.Empty<PortalPlane>(),
worldOffsetX: 0f,
worldOffsetY: 0f);
var controller = new PlayerMovementController(engine);
controller.SetPosition(new Vector3(96f, 96f, 50f), 0x0001u);
return controller;
}
private sealed record Harness(
MouseLookController Owner,
LocalPlayerModeState Mode,
PlayerMovementController Player,
CameraController Camera,
ChaseCameraInputState Chase,
FakeMouse Mouse,
FakeCursor Cursor,
FakeClock Clock,
NullSessionSource Session)
{
public void EnterChase() =>
Camera.EnterChaseMode(new ChaseCamera(), new RetailChaseCamera());
}
private sealed class FixedMovementInputSource : IMovementInputSource
{
public MovementInput Capture() => new(Run: true);
}
private sealed class FakeClock : IInputMonotonicClock
{
public float NowSeconds { get; set; }
}
private sealed class FakeCursor : IMouseLookCursor
{
public int HideCount { get; private set; }
public int RestoreCount { get; private set; }
public bool HasSavedMode { get; private set; }
public void Hide()
{
HideCount++;
HasSavedMode = true;
}
public void Restore()
{
RestoreCount++;
HasSavedMode = false;
}
}
private sealed class NullSessionSource : ILiveWorldSessionSource
{
public WorldSession? CurrentSession => null;
}
private sealed class FakeMouse : IMouseSource
{
#pragma warning disable CS0067
public event Action<MouseButton, ModifierMask>? MouseDown;
public event Action<MouseButton, ModifierMask>? MouseUp;
public event Action<float, float>? MouseMove;
public event Action<float>? Scroll;
#pragma warning restore CS0067
public bool WantCaptureMouse { get; set; }
public bool WantCaptureKeyboard { get; set; }
public bool IsHeld(MouseButton button) => false;
}
}