A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Statecraft.Game.Map;
using UnityEditor;
using UnityEngine;
using UnityEngine.InputSystem;
/// <summary>Base for every fixture that enables the Camera map of the shared Assets/InputSystem_Actions.inputactions asset
/// (#1903). The asset is one object for the whole editor session and keeps its resolved state across the Input System's
/// save, reset and restore, so a fixture could enable the map against controls of devices it does not have (an
/// IndexOutOfRangeException inside the Input System) or against another fixture's recycled device indices. Each fixture
/// therefore starts with the asset's state dropped (code outside these fixtures, such as the editor's own input system,
/// can have resolved it) and ends the same way. NUnit runs this SetUp after InputTestFixture's (the fixture's own input
/// system is in place) and this TearDown before it (the fixture's devices still exist).</summary>
public abstract class SharedCameraActionsFixture : InputTestFixture
{
static void DropTheResolvedState()
{
var actions = AssetDatabase.LoadAssetAtPath<InputActionAsset>("Assets/InputSystem_Actions.inputactions");
Assert.IsNotNull(actions, "the shipped input asset must exist");
actions.Disable();
// Dispose drops the state all the maps share, so the next enable resolves from scratch against the live devices.
foreach (var map in actions.actionMaps) map.Dispose();
}
[SetUp] public void StartWithoutResolvedCameraActions() => DropTheResolvedState();
[TearDown] public void EndWithoutResolvedCameraActions() => DropTheResolvedState();
}
public class CameraInputTests
{
static CameraRig NewRig()
{
var go = new GameObject("RigTest", typeof(Camera));
var rig = go.AddComponent<CameraRig>();
rig.LookAt = new Vector3(500000, 0, 500000); rig.Distance = 100000f;
return rig;
}
/// <summary>A map far larger than the view, so the input tests below never meet the view clamp (issue #174), which
/// the edge tests further down check on a map the size of the real one.</summary>
static readonly Rect Map = new Rect(0, 0, 1000000, 1000000);
/// <summary>The real terrain's size (heightmap.json: 161.5 x 431.2 km).</summary>
static readonly Rect RealMap = new Rect(0, 0, 161529f, 431223f);
[Test]
public void TheCameraActionMapIsInTheProjectWideAsset()
{
var asset = AssetDatabase.LoadAssetAtPath<InputActionAsset>("Assets/InputSystem_Actions.inputactions");
var map = asset.FindActionMap("Camera", true);
foreach (var name in new[] { "Pan", "DragPan", "Zoom", "ZoomKeys", "Orbit" }) Assert.IsNotNull(map.FindAction(name), name);
Assert.AreEqual(8, map.FindAction("Pan").bindings.Count(b => b.isPartOfComposite && b.path.StartsWith("<Keyboard>/")));
// Two OneModifier composites since #998: the right button and the left one, each over <Mouse>/delta. Naming the
// modifiers says more than the count, and catches a composite losing its button rather than only its arity.
Assert.AreEqual(6, map.FindAction("DragPan").bindings.Count);
CollectionAssert.AreEquivalent(new[] { "<Mouse>/rightButton", "<Mouse>/leftButton" },
map.FindAction("DragPan").bindings.Where(b => b.name == "modifier").Select(b => b.path).ToArray());
CollectionAssert.AreEquivalent(new[] { "<Mouse>/delta", "<Mouse>/delta" },
map.FindAction("DragPan").bindings.Where(b => b.name == "binding").Select(b => b.path).ToArray());
Assert.AreEqual(1, map.FindAction("Zoom").bindings.Count);
// a11y B1a: = and -, and the numpad's + and -, as two 1D composites; the wheel's Zoom keeps its one binding.
CollectionAssert.AreEquivalent(new[] { "<Keyboard>/equals", "<Keyboard>/minus", "<Keyboard>/numpadPlus", "<Keyboard>/numpadMinus" },
map.FindAction("ZoomKeys").bindings.Where(b => b.isPartOfComposite).Select(b => b.path).ToArray());
CollectionAssert.AreEquivalent(new[] { "<Keyboard>/equals", "<Keyboard>/numpadPlus" }, // positive = in, as the wheel
map.FindAction("ZoomKeys").bindings.Where(b => b.isPartOfComposite && b.name == "positive").Select(b => b.path).ToArray());
Assert.AreEqual(3, map.FindAction("Orbit").bindings.Count);
var added = new System.Collections.Generic.List<InputDevice>();
if (Keyboard.current == null) added.Add(InputSystem.AddDevice<Keyboard>());
if (Mouse.current == null) added.Add(InputSystem.AddDevice<Mouse>());
try
{
foreach (var a in map.actions)
foreach (var b in a.bindings.Where(b => !b.isComposite))
{
using var found = InputSystem.FindControls(b.path);
Assert.Greater(found.Count, 0, a.name + " " + b.path + " resolves to no control");
}
}
finally { foreach (var d in added) InputSystem.RemoveDevice(d); }
Assert.IsNotNull(asset.FindActionMap("UI", true).FindAction("Click"), "UI Toolkit needs the UI map's actions");
}
[Test]
public void APinchZoomsByTheFingersDistanceAtTheTouchpadRate()
{
// the fingers spread 100 px in one frame: one notch in (PixelsPerNotch, the touchpad's rate)
Assert.AreEqual(1f, CameraController.PinchNotches(new Vector2(0, 0), Vector2.zero, new Vector2(200, 0), new Vector2(100, 0)), 1e-4);
// they close 100 px: one notch out
Assert.AreEqual(-1f, CameraController.PinchNotches(new Vector2(0, 0), Vector2.zero, new Vector2(100, 0), new Vector2(-100, 0)), 1e-4);
// both fingers still (or moving together, the distance unchanged): no zoom
Assert.AreEqual(0f, CameraController.PinchNotches(new Vector2(0, 0), Vector2.zero, new Vector2(100, 0), Vector2.zero), 1e-4);
Assert.AreEqual(0f, CameraController.PinchNotches(new Vector2(50, 0), new Vector2(10, 0), new Vector2(160, 0), new Vector2(10, 0)), 1e-4);
}
[Test]
public void PanMovesTheLookAtNorthAtYawZero()
{
var rig = NewRig();
try
{
CameraController.Step(rig, new CameraInput { Pan = Vector2.up }, 0.5f, Map);
Assert.AreEqual(500000f, rig.LookAt.x, 1e-2);
Assert.AreEqual(500000f + 0.4f * 100000f, rig.LookAt.z, 1e-1); // 0.8 distances per second for half a second
}
finally { Object.DestroyImmediate(rig.gameObject); }
}
[Test]
public void ZoomIsClampedAndOrbitTurnsTheView()
{
var rig = NewRig();
try
{
for (int i = 0; i < 100; i++) CameraController.Step(rig, new CameraInput { Zoom = 3 }, 0.016f, Map);
Assert.AreEqual(CameraController.MinDistance, rig.Distance, 1e-3);
CameraController.Step(rig, new CameraInput { Orbit = 1 }, 0.5f, Map);
Assert.AreEqual(30f, rig.Yaw, 1e-3);
Assert.AreEqual(30f, rig.transform.eulerAngles.y, 1e-3);
CameraController.Step(rig, new CameraInput { Pan = Vector2.left }, 1000f, Map);
// Clamped so the view's west edge is the map's (issue #174), not the look-at point.
Assert.AreEqual(Map.xMin, rig.LookAt.x + CameraController.ViewFootprint(rig).xMin, 1f);
}
finally { Object.DestroyImmediate(rig.gameObject); }
}
[Test]
public void PointerInputIsIgnoredOverTheUi()
{
var rig = NewRig();
try
{
var before = (rig.LookAt, rig.Distance, rig.Yaw);
CameraController.Step(rig, new CameraInput { Zoom = 1, DragPan = Vector2.one * 50, OverUi = true, DragFromUi = true }, 1f, Map);
Assert.AreEqual(before, (rig.LookAt, rig.Distance, rig.Yaw));
CameraController.Step(rig, new CameraInput { Zoom = 1, DragPan = Vector2.one * 50 }, 1f, Map); // control: same input off the UI moves the rig
Assert.AreNotEqual(before.Distance, rig.Distance);
Assert.AreNotEqual(before.LookAt, rig.LookAt);
}
finally { Object.DestroyImmediate(rig.gameObject); }
}
[Test]
public void KeysStillPanAndOrbitWhileThePointerIsOverTheUi()
{
var rig = NewRig();
try
{
CameraController.Step(rig, new CameraInput { Pan = Vector2.up, Orbit = 1, Zoom = 1, OverUi = true }, 0.5f, Map);
Assert.AreEqual(100000f, rig.Distance, 1e-3); // the wheel was over the UI
Assert.AreEqual(30f, rig.Yaw, 1e-3);
Assert.Greater(rig.LookAt.z, 500000f);
}
finally { Object.DestroyImmediate(rig.gameObject); }
}
/// <summary>a11y B1a: the zoom keys move the camera as keyboard pan does, also while the pointer rests over a panel,
/// at ZoomKeysPerSecond wheel notches a second held, so the closest to the farthest zoom takes about six seconds.</summary>
[Test]
public void ZoomKeysWorkOverTheUiAtSixNotchesASecond()
{
var rig = NewRig();
try
{
CameraController.Step(rig, new CameraInput { KeyZoom = 1, OverUi = true }, 1f, Map);
Assert.AreEqual(100000f * Mathf.Pow(1f - CameraController.ZoomPerStep, CameraController.ZoomKeysPerSecond), rig.Distance, 1f);
CameraController.Step(rig, new CameraInput { KeyZoom = -1, OverUi = true }, 1f, Map);
Assert.AreEqual(100000f, rig.Distance, 1f, "a second out undoes a second in");
Assert.AreEqual(6f, CameraController.ZoomKeysPerSecond, "the plan's rate (B1a option 1)");
}
finally { Object.DestroyImmediate(rig.gameObject); }
}
[Test]
public void ZoomKeysTwoHalfStepsEqualOneFullStep()
{
var a = NewRig(); var b = NewRig();
try
{
var inp = new CameraInput { KeyZoom = 1 };
CameraController.Step(a, inp, 0.1f, Map);
CameraController.Step(b, inp, 0.05f, Map); CameraController.Step(b, inp, 0.05f, Map);
Assert.AreEqual(a.Distance, b.Distance, 1e-1);
Assert.Less(a.Distance, 100000f);
}
finally { Object.DestroyImmediate(a.gameObject); Object.DestroyImmediate(b.gameObject); }
}
/// <summary>a11y B1a: only an unmodified press zooms the map, so Ctrl or Cmd with + and - stays the browser's own page
/// zoom (and Alt combinations stay the system's). Shift is allowed: + is Shift and = on a US keyboard.</summary>
[Test]
public void ZoomKeysCountOnlyWithoutCtrlAltOrCmd()
{
var c = NewController(out var go);
try
{
Assert.AreEqual(1f, c.Gather(Vector2.zero, Vector2.zero, 0, 0, false, null, 1f, false).KeyZoom);
Assert.AreEqual(-1f, c.Gather(Vector2.zero, Vector2.zero, 0, 0, false, null, -1f, false).KeyZoom);
Assert.AreEqual(0f, c.Gather(Vector2.zero, Vector2.zero, 0, 0, false, null, 1f, true).KeyZoom);
Assert.AreEqual(1f, c.Gather(Vector2.zero, Vector2.zero, 0, 0, false, null, 2f, false).KeyZoom, "both composites held count once");
Assert.AreEqual(0f, c.Gather(Vector2.zero, Vector2.zero, 0, 0, false, null).KeyZoom, "no keys, no key zoom");
}
finally { Object.DestroyImmediate(go); }
}
/// <summary>The modifier read Update feeds Gather: each of Ctrl, Alt and Cmd on either side counts, Shift does not.</summary>
[Test]
public void CtrlAltAndCmdAreModifiersAndShiftIsNot()
{
var keyboard = InputSystem.AddDevice<Keyboard>();
try
{
Assert.IsFalse(CameraController.ModifierHeld(null));
foreach (var (key, want) in new[] { (Key.None, false), (Key.LeftShift, false), (Key.RightShift, false),
(Key.LeftCtrl, true), (Key.RightCtrl, true), (Key.LeftAlt, true), (Key.RightAlt, true), (Key.LeftMeta, true), (Key.RightMeta, true) })
{
var state = key == Key.None ? new UnityEngine.InputSystem.LowLevel.KeyboardState(Key.Equals)
: new UnityEngine.InputSystem.LowLevel.KeyboardState(key, Key.Equals);
InputSystem.QueueStateEvent(keyboard, state); InputSystem.Update();
Assert.IsTrue(keyboard.equalsKey.isPressed, key + ": precondition, = is down");
Assert.AreEqual(want, CameraController.ModifierHeld(keyboard), key.ToString());
}
}
finally { InputSystem.RemoveDevice(keyboard); }
}
[Test]
public void MaxDistanceClampsAndYawWraps()
{
var rig = NewRig();
try
{
for (int i = 0; i < 200; i++) CameraController.Step(rig, new CameraInput { Zoom = -3 }, 0.016f, Map);
Assert.AreEqual(CameraController.MaxDistance, rig.Distance, 1e-3);
rig.Yaw = 350f;
CameraController.Step(rig, new CameraInput { Orbit = 1 }, 0.5f, Map); // +30
Assert.AreEqual(20f, rig.Yaw, 1e-3);
}
finally { Object.DestroyImmediate(rig.gameObject); }
}
[Test]
public void PanFollowsTheYaw()
{
var rig = NewRig();
try
{
rig.Yaw = 90f; // looking east: forward is +x
CameraController.Step(rig, new CameraInput { Pan = Vector2.up }, 0.5f, Map);
Assert.AreEqual(500000f + 0.4f * 100000f, rig.LookAt.x, 1f);
Assert.AreEqual(500000f, rig.LookAt.z, 1f);
}
finally { Object.DestroyImmediate(rig.gameObject); }
}
[Test]
public void TwoHalfStepsEqualOneFullStep()
{
var a = NewRig(); var b = NewRig();
try
{
var inp = new CameraInput { Pan = new Vector2(1, 1), Orbit = 1, Zoom = 0 };
a.Yaw = b.Yaw = 0;
CameraController.Step(a, inp, 0.1f, Map);
CameraController.Step(b, inp, 0.05f, Map); CameraController.Step(b, inp, 0.05f, Map);
Assert.AreEqual(a.Yaw, b.Yaw, 1e-3);
// the pan direction turns with the yaw between the half steps (3 degrees here: yaw updates before pan), so allow 0.5% of the distance
Assert.AreEqual(a.LookAt.x, b.LookAt.x, 500f);
Assert.AreEqual(a.LookAt.z, b.LookAt.z, 500f);
}
finally { Object.DestroyImmediate(a.gameObject); Object.DestroyImmediate(b.gameObject); }
}
[Test]
public void PanAloneIsFrameRateIndependent()
{
var a = NewRig(); var b = NewRig();
try
{
var inp = new CameraInput { Pan = new Vector2(1, 1) };
CameraController.Step(a, inp, 0.1f, Map);
CameraController.Step(b, inp, 0.05f, Map); CameraController.Step(b, inp, 0.05f, Map);
Assert.AreEqual(a.LookAt.x, b.LookAt.x, 1f);
Assert.AreEqual(a.LookAt.z, b.LookAt.z, 1f);
}
finally { Object.DestroyImmediate(a.gameObject); Object.DestroyImmediate(b.gameObject); }
}
[Test]
public void AStalledFrameMovesNoMoreThanTheCap()
{
var a = NewRig(); var b = NewRig();
try
{
var inp = new CameraInput { Pan = Vector2.up, Orbit = 1 };
CameraController.Step(a, inp, CameraController.ClampDt(5f), Map);
CameraController.Step(b, inp, CameraController.MaxFrameSeconds, Map);
Assert.AreEqual(b.LookAt, a.LookAt);
Assert.AreEqual(b.Yaw, a.Yaw, 1e-4);
}
finally { Object.DestroyImmediate(a.gameObject); Object.DestroyImmediate(b.gameObject); }
}
/// <summary>The view's ground on the map at the rig's current pose: [look-at + footprint] inside the map, within tol.</summary>
static void AssertViewOnMap(CameraRig rig, Rect map, string what, float tol = 1f)
{
var f = CameraController.ViewFootprint(rig);
Assert.GreaterOrEqual(rig.LookAt.x + f.xMin, map.xMin - tol, what + ": west");
Assert.LessOrEqual(rig.LookAt.x + f.xMax, map.xMax + tol, what + ": east");
Assert.GreaterOrEqual(rig.LookAt.z + f.yMin, map.yMin - tol, what + ": south");
Assert.LessOrEqual(rig.LookAt.z + f.yMax, map.yMax + tol, what + ": north");
}
/// <summary>Issue #174: panning past a corner at gameplay zoom stops where the view's edges meet the map's, at every
/// yaw and with the top bar's inset, so nothing past the map's edge (since #36 the frame) shows. (The look-at clamp alone left 3/4 of the view on it.)</summary>
[Test]
public void PanningPastACornerKeepsTheViewOnTheMap()
{
var rig = NewRig();
try
{
var cam = rig.GetComponent<Camera>(); cam.aspect = 16f / 9f; cam.fieldOfView = CameraRig.Fov; // the game's view (Init is not run here)
foreach (var d in new[] { CameraController.MinDistance, 30000f, 60000f })
foreach (var yaw in new[] { 0f, 45f, 90f, 200f })
foreach (var inset in new[] { 0f, 0.1f })
foreach (var dir in new[] { new Vector2(1, 1), new Vector2(-1, 1), new Vector2(1, -1), new Vector2(-1, -1) })
{
rig.LookAt = new Vector3(RealMap.center.x, 0, RealMap.center.y); rig.Distance = d; rig.Yaw = yaw; rig.TopInset = inset;
var what = $"{d / 1000f} km, yaw {yaw}, inset {inset}, pan {dir}";
for (int i = 0; i < 120; i++) CameraController.Step(rig, new CameraInput { Pan = dir }, 0.5f, RealMap);
AssertViewOnMap(rig, RealMap, what);
// and it got there: the view touches the map's edge on at least one side
var f = CameraController.ViewFootprint(rig);
float gap = Mathf.Min(Mathf.Abs(rig.LookAt.x + f.xMin - RealMap.xMin), Mathf.Abs(rig.LookAt.x + f.xMax - RealMap.xMax),
Mathf.Abs(rig.LookAt.z + f.yMin - RealMap.yMin), Mathf.Abs(rig.LookAt.z + f.yMax - RealMap.yMax));
Assert.Less(gap, 1f, what + ": the pan reached the edge");
}
}
finally { Object.DestroyImmediate(rig.gameObject); }
}
/// <summary>Issue #174: where the view is wider than the map (the overview), it is centred on the map on that axis, and
/// zooming out at the edge moves the view smoothly rather than jumping (the clamp narrows to the centre continuously).</summary>
[Test]
public void AViewWiderThanTheMapIsCentredAndZoomingOutNeverJumps()
{
var rig = NewRig();
try
{
var cam = rig.GetComponent<Camera>(); cam.aspect = 16f / 9f; cam.fieldOfView = CameraRig.Fov; // the game's view (Init is not run here)
rig.LookAt = new Vector3(RealMap.xMax, 0, RealMap.center.y); rig.Distance = CameraController.MinDistance; rig.Yaw = 0;
CameraController.Step(rig, new CameraInput { Pan = Vector2.right }, 10f, RealMap);
float worst = 0f;
while (rig.Distance < CameraController.MaxDistance - 1f)
{
var before = rig.LookAt;
CameraController.Step(rig, new CameraInput { Zoom = -0.2f, Pan = Vector2.right }, 0.016f, RealMap);
// a frame's pan alone moves 0.8 * 0.016 distances; the clamp may add the view's growth, a few % of it
worst = Mathf.Max(worst, (rig.LookAt - before).magnitude / rig.Distance);
if (CameraController.ViewFootprint(rig).width <= RealMap.width)
AssertViewOnMap(rig, RealMap, $"{rig.Distance / 1000f:0} km");
}
Assert.Less(worst, 0.05f, "no jump while zooming out at the edge");
var f = CameraController.ViewFootprint(rig);
Assert.Greater(f.width, RealMap.width, "at the overview the view is wider than the map");
Assert.AreEqual(RealMap.center.x, rig.LookAt.x + f.center.x, 1f, "so it is centred on the map");
}
finally { Object.DestroyImmediate(rig.gameObject); }
}
/// <summary>Issue #1062 (player report): at the distance the game opens at (Map.unity's camera rig; MapScene.Build keeps
/// it), a 16:9 view (1280x720, 1920x1080) is narrower than the map, so the arrow keys and a right-drag pan it east and
/// west from the first frame, with or without the top bar's inset; panning on still stops where #174 stops it.</summary>
[Test]
public void AtTheOpeningZoomTheMapPansLeftAndRight()
{
UnityEditor.SceneManagement.EditorSceneManager.OpenScene("Assets/Map.unity", UnityEditor.SceneManagement.OpenSceneMode.Single);
float opening = Camera.main.GetComponent<CameraRig>().Distance;
UnityEditor.SceneManagement.EditorSceneManager.NewScene(UnityEditor.SceneManagement.NewSceneSetup.EmptyScene,
UnityEditor.SceneManagement.NewSceneMode.Single);
var rig = new GameObject("RigTest", typeof(Camera)).AddComponent<CameraRig>();
try
{
// A rig MapScene adds itself (a camera without one) opens there too.
Assert.AreEqual(opening, rig.Distance, "the rig's default is the scene's opening distance");
var cam = rig.GetComponent<Camera>(); cam.aspect = 16f / 9f; cam.fieldOfView = CameraRig.Fov; // the game's view (Init is not run here)
foreach (var inset in new[] { 0f, 0.1f })
foreach (var (input, east) in new[]
{
(new CameraInput { Pan = Vector2.right }, 0.08f), (new CameraInput { Pan = Vector2.left }, -0.08f), // 0.8 distances a second for 0.1 s
(new CameraInput { DragPan = new Vector2(-50f, 0f) }, 0.06f), (new CameraInput { DragPan = new Vector2(50f, 0f) }, -0.06f),
})
{
var what = $"inset {inset}, pan {input.Pan}, drag {input.DragPan}";
rig.LookAt = new Vector3(RealMap.center.x, 0, RealMap.center.y); rig.Distance = opening; rig.Yaw = 0; rig.TopInset = inset;
CameraController.Step(rig, default, 0f, RealMap);
float x = rig.LookAt.x;
CameraController.Step(rig, input, 0.1f, RealMap);
Assert.AreEqual(x + east * opening, rig.LookAt.x, 1f, what + ": the view moves sideways");
for (int i = 0; i < 40; i++) CameraController.Step(rig, input, 0.1f, RealMap);
AssertViewOnMap(rig, RealMap, what + ", panned on");
}
}
finally { Object.DestroyImmediate(rig.gameObject); }
}
/// <summary>The owner, 3 November 2026: "Open at ~30 km, like the promo". The opening zoom is about 30 km, close enough
/// for the building models (TownModelLayer.CloseAt), clear of the 30 km edge where RoadVehicles and the collection
/// layers switch (so the first frame does not depend on rounding), and under the minimap's whole-map zoom
/// (CameraController.MaxDistance, where the view is wider than the map: AViewWiderThanTheMapIsCentredAndZoomingOutNeverJumps).</summary>
[Test]
public void TheGameOpensAtAbout30KmWithTheBuildingModels()
{
float start = CameraRig.StartDistance;
Assert.That(start, Is.InRange(25000f, 35000f), "about 30 km (owner, 3 November 2026)");
Assert.IsTrue(Statecraft.Game.Map.Kits.TownModelLayer.CloseAt(start, null), "the building models draw at the opening");
Assert.GreaterOrEqual(start, Statecraft.Game.Map.Routes.RoadVehicles.CloseEnterM + 1000f, "1 km beyond the road vehicles' enter edge");
Assert.GreaterOrEqual(start, Statecraft.Game.Map.Collection.ProductionResidency.Approved().Units.ViewEnterM + 1000f,
"1 km beyond the collection layers' enter edge");
Assert.Less(start, CameraController.MaxDistance, "the whole-map zoom is farther out");
}
/// <summary>Issue #174: over low ground the look-at point stays on y = 0 (the approved framing); over ground high enough
/// to come within MinClearanceShare of the camera, it is lifted just enough, and dropped again on the way back down.</summary>
[Test]
public void TheCameraIsLiftedOnlyOverHighGround()
{
var rig = NewRig();
try
{
rig.Distance = CameraController.MinDistance;
float height = rig.Distance * Mathf.Sin(CameraRig.Pitch * Mathf.Deg2Rad);
float groundY = 0f;
System.Func<Vector2, float> ground = _ => groundY;
foreach (var g in new[] { 0f, 0.5f, 0.79f, 0.9f, 1.3f, 0.3f })
{
groundY = g * height;
CameraController.Step(rig, new CameraInput(), 0f, Map, ground);
float clearance = rig.transform.position.y - groundY;
if (g <= 1f - CameraController.MinClearanceShare)
Assert.AreEqual(0f, rig.LookAt.y, 1e-3, $"ground at {g} of the camera's height: no lift");
else
Assert.AreEqual(CameraController.MinClearanceShare * height, clearance, 1f, $"ground at {g}: lifted to the least clearance");
}
}
finally { Object.DestroyImmediate(rig.gameObject); }
}
/// <summary>Review B-I1: with the ground's top given, the near side of the view is bounded by the corner rays' hits on
/// that plane, not by the point below the camera: at 60 km, pushed to the south edge, the camera may stand behind the
/// edge, and the strip kept off screen is a few km (it was 19-20 km). With the camera below the top plane (the hero
/// zoom over high ground) the point below the camera is the bound.</summary>
[Test]
public void TheNearSideIsBoundedByTheGroundsTopNotTheCamera()
{
var rig = NewRig();
try
{
var cam = rig.GetComponent<Camera>(); cam.aspect = 16f / 9f; cam.fieldOfView = CameraRig.Fov;
const float top = 8400f; // about the real terrain's highest point (2367 m + 427 m, at 3x)
float back = Mathf.Cos(CameraRig.Pitch * Mathf.Deg2Rad); // the camera is this many distances behind the look-at point
rig.LookAt = new Vector3(RealMap.center.x, 0, RealMap.center.y); rig.Distance = 60000f; rig.Yaw = 0; rig.TopInset = 0;
for (int i = 0; i < 60; i++) CameraController.Step(rig, new CameraInput { Pan = Vector2.down }, 0.5f, RealMap, _ => 0f, top);
var f = CameraController.ViewFootprint(rig, top);
Assert.AreEqual(RealMap.yMin, rig.LookAt.z + f.yMin, 1f, "the view's near side at the south edge");
Assert.Less(rig.LookAt.z, back * rig.Distance - 10000f, "the camera stands behind the edge: the edge rows stay reachable");
var flat = CameraController.ViewFootprint(rig);
Assert.Less(flat.yMin - f.yMin, 5000f, "the high-ground margin at 60 km is a few km");
Assert.Greater(flat.yMin - f.yMin, 1000f, "and it is there");
rig.Distance = CameraController.MinDistance; rig.ApplyProjection(); // camera 4.6 km up, below the 8.4 km plane
Assert.AreEqual(-back * rig.Distance, CameraController.ViewFootprint(rig, top).yMin, 1f, "the point below the camera bounds it");
}
finally { Object.DestroyImmediate(rig.gameObject); }
}
/// <summary>A rig without a camera keeps the old rule: the look-at point itself stays on the map.</summary>
[Test]
public void ARigWithoutACameraClampsTheLookAtPoint()
{
var go = new GameObject("BareRig");
try
{
var rig = go.AddComponent<CameraRig>(); rig.LookAt = new Vector3(100, 0, 100); rig.Distance = 6000f;
Assert.AreEqual(Rect.zero, CameraController.ViewFootprint(rig));
CameraController.Step(rig, new CameraInput { Pan = Vector2.left }, 10f, RealMap);
Assert.AreEqual(0f, rig.LookAt.x, 1e-3);
}
finally { Object.DestroyImmediate(go); }
}
static CameraController NewController(out GameObject go)
{
go = new GameObject("CtlTest", typeof(Camera));
var c = go.AddComponent<CameraController>();
c.IsOverUi = p => p.x < 100; // the panel is the left strip
return c;
}
[Test]
public void NoPointerMeansNotOverTheUi()
{
var c = NewController(out var go);
try
{
bool probed = false; c.IsOverUi = _ => { probed = true; return true; };
var inp = c.Gather(Vector2.zero, Vector2.zero, 120f, 0, false, null);
Assert.IsFalse(inp.OverUi); Assert.IsFalse(probed);
}
finally { Object.DestroyImmediate(go); }
}
[Test]
public void ADragStartedOverTheMapKeepsPanningOverAPanel()
{
var c = NewController(out var go);
try
{
c.Gather(Vector2.zero, Vector2.zero, 0, 0, true, new Vector2(500, 0));
var inp = c.Gather(Vector2.zero, Vector2.one, 120f, 0, true, new Vector2(50, 0)); // now over the panel
Assert.IsFalse(inp.DragFromUi); Assert.IsTrue(inp.OverUi); // wheel is still the UI's
}
finally { Object.DestroyImmediate(go); }
}
[Test]
public void ADragStartedOverTheUiNeverPansTheMap()
{
var c = NewController(out var go);
try
{
c.Gather(Vector2.zero, Vector2.zero, 0, 0, true, new Vector2(50, 0));
var inp = c.Gather(Vector2.zero, Vector2.one, 0, 0, true, new Vector2(500, 0)); // moved onto the map
Assert.IsTrue(inp.DragFromUi);
c.Gather(Vector2.zero, Vector2.zero, 0, 0, false, new Vector2(500, 0)); // released
Assert.IsFalse(c.Gather(Vector2.zero, Vector2.zero, 0, 0, true, new Vector2(500, 0)).DragFromUi);
}
finally { Object.DestroyImmediate(go); }
}
// Task 24 (carry 3), measured in headed Chrome on the WebGL build: the Input System's default scroll behaviour
// (UniformAcrossAllPlatforms) already gives 1 per wheel notch (Chrome's 100 px notch arrived as 1.0, a 300 px burst
// as 3.0), so one notch must zoom by ZoomPerStep (10%), not by a /120 of it.
[Test]
public void OneWheelNotchZoomsByOneStep()
{
Assert.AreEqual(UnityEngine.InputSystem.InputSettings.ScrollDeltaBehavior.UniformAcrossAllPlatforms,
UnityEngine.InputSystem.InputSystem.settings.scrollDeltaBehavior, "the scroll range this controller assumes");
var c = NewController(out var go);
try
{
Assert.AreEqual(1f, c.Gather(Vector2.zero, Vector2.zero, 1f, 0, false, null).Zoom);
Assert.AreEqual(-1f, c.Gather(Vector2.zero, Vector2.zero, -1f, 0, false, null).Zoom);
Assert.AreEqual(3f, c.Gather(Vector2.zero, Vector2.zero, 7f, 0, false, null).Zoom, "bursts are clamped");
var rig = go.GetComponent<CameraRig>();
rig.Distance = 120000f;
CameraController.Step(rig, c.Gather(Vector2.zero, Vector2.zero, 1f, 0, false, null), 0.016f, Map);
Assert.AreEqual(108000f, rig.Distance, 1f);
}
finally { Object.DestroyImmediate(go); }
}
/// <summary>Issue #43 (T45): in WebGL the zoom counts the browser's wheel events itself. Unity's player took the smallest
/// delta seen since load as one notch, so one 0.5 px touchpad event made every later frame zoom the clamped 27%. A
/// mouse notch is still one step: 100 px, three lines, one page, or a macOS mouse tick (4.000244140625 px).</summary>
[Test]
public void AMouseNotchIsOneStepInEveryMode()
{
Assert.AreEqual(1f, CameraController.WheelEventNotches(-100f, CameraController.WheelPixels), 1e-5, "100 px up");
Assert.AreEqual(-1f, CameraController.WheelEventNotches(100f, CameraController.WheelPixels), 1e-5, "100 px down");
Assert.AreEqual(1f, CameraController.WheelEventNotches(-3f, CameraController.WheelLines), 1e-5, "3 lines");
Assert.AreEqual(1f, CameraController.WheelEventNotches(-1f, CameraController.WheelPages), 1e-5, "1 page");
Assert.AreEqual(1f, CameraController.WheelEventNotches(-4.000244140625f, CameraController.WheelPixels), 1e-5, "macOS tick");
Assert.AreEqual(-1f, CameraController.WheelEventNotches(8.00048828125f, CameraController.WheelPixels), 1e-5,
"an accelerated macOS tick (two ticks' worth) is still one notch");
Assert.AreEqual(1f, CameraController.WheelEventNotches(-13 * 4.000244140625f, CameraController.WheelPixels), 1e-5,
"a fast-spun macOS tick above the threshold is one notch");
foreach (var mode in new[] { CameraController.WheelPixels, CameraController.WheelLines, CameraController.WheelPages })
Assert.AreEqual(float.PositiveInfinity, 1f / CameraController.WheelEventNotches(0f, mode), $"0 in mode {mode} is +0, not -0");
}
/// <summary>#528 review: one discrete pixel notch is one step whatever its size. Chrome's synthetic 100 px notch
/// arrives as 200 px, and display scaling or page zoom gives 80, 120, 125 or 150 px; every pixel event of
/// MouseNotchMinPixels (50) or more is exactly one notch in its direction (DOM deltaY below zero = in = positive).</summary>
[Test]
public void APixelNotchIsOneStepWhateverItsSize()
{
foreach (var px in new[] { 50f, 80f, 100f, 120f, 125f, 150f, 200f, 360f })
{
Assert.AreEqual(1f, CameraController.WheelEventNotches(-px, CameraController.WheelPixels), 1e-6, $"-{px} px is one notch in");
Assert.AreEqual(-1f, CameraController.WheelEventNotches(px, CameraController.WheelPixels), 1e-6, $"+{px} px is one notch out");
}
Assert.AreEqual(CameraController.MouseNotchMinPixels, 50f, "the threshold these cases assume");
Assert.AreEqual(1f, CameraController.WheelEventNotches(-50f, CameraController.WheelPixels), 1e-6, "at the threshold: a notch");
Assert.AreEqual(0.4999f, CameraController.WheelEventNotches(-49.99f, CameraController.WheelPixels), 1e-5, "just below: proportional");
Assert.AreEqual(-0.49f, CameraController.WheelEventNotches(49f, CameraController.WheelPixels), 1e-6);
Assert.AreEqual(2f, CameraController.WheelEventNotches(-6f, CameraController.WheelLines), 1e-6, "lines stay as they were: 6 are 2 notches");
var rig = NewRig();
try
{
rig.Distance = 120000f;
CameraController.Step(rig, new CameraInput { Zoom = CameraController.WheelNotches(new[] { -200f }, new[] { 0 }, 1) }, 0.016f, Map);
Assert.AreEqual(108000f, rig.Distance, 1f, "Chrome's synthetic 200 px notch zooms 10%");
}
finally { Object.DestroyImmediate(rig.gameObject); }
}
/// <summary>#528 review: a fast trackpad flick can send events of 50 to 100 px, which MouseNotchMinPixels counts as a
/// whole notch each, up to twice their length. The over-count is bounded per frame by Gather's clamp: one 60 px event
/// is one notch (proportional would be 0.6), and five in one frame are five notches, clamped to three (27%).</summary>
[Test]
public void A60PxFlickEventIsOneNotchAndAFrameOfThemIsClampedToThree()
{
Assert.AreEqual(1f, CameraController.WheelEventNotches(-60f, CameraController.WheelPixels), 1e-6, "one 60 px event");
var frame = new[] { -60f, -60f, -60f, -60f, -60f };
Assert.AreEqual(5f, CameraController.WheelNotches(frame, new int[frame.Length], frame.Length), 1e-6, "before the clamp");
var c = NewController(out var go);
try
{
var inp = c.Gather(Vector2.zero, Vector2.zero, CameraController.WheelNotches(frame, new int[frame.Length], frame.Length), 0, false,
new Vector2(500, 0));
Assert.AreEqual(3f, inp.Zoom, 1e-6, "clamped to three notches a frame");
var rig = go.GetComponent<CameraRig>();
rig.Distance = 120000f;
CameraController.Step(rig, inp, 0.016f, Map);
Assert.AreEqual(120000f * 0.729f, rig.Distance, 1f, "27.1% in that frame, no more");
}
finally { Object.DestroyImmediate(go); }
}
[Test]
public void TouchpadPixelsZoomInProportionAndNothingIsLearned()
{
Assert.AreEqual(0.005f, CameraController.WheelEventNotches(-0.5f, CameraController.WheelPixels), 1e-6);
Assert.AreEqual(0.04f, CameraController.WheelEventNotches(-4f, CameraController.WheelPixels), 1e-6, "4 px is not a tick");
Assert.AreEqual(0.07f, CameraController.WheelEventNotches(-7f, CameraController.WheelPixels), 1e-6);
// A swipe of many small deltas, then a mouse notch: the swipe zooms by its length, and the notch is still one step.
var swipe = new float[] { -0.5f, -1, -2, -4, -6, -8, -8, -8, -6.2f, -4.8f, -3.1f, -1.4f, -0.6f };
var modes = new int[swipe.Length];
Assert.AreEqual(-swipe.Sum() / 100f, CameraController.WheelNotches(swipe, modes, swipe.Length), 1e-5);
Assert.AreEqual(1f, CameraController.WheelNotches(new[] { -100f }, new[] { 0 }, 1), 1e-5);
Assert.AreEqual(1f, CameraController.WheelNotches(new[] { -3f }, new[] { CameraController.WheelLines }, 1), 1e-5);
Assert.AreEqual(0.4f, CameraController.WheelNotches(new[] { -40f, -100f }, new[] { 0, 0 }, 1), 1e-5, "only count events");
// The swipe the browser runs use (tools/headed.py pad_swipe: a ramp, a hold, momentum decaying 12% an event).
var pad = new List<float> { -0.5f, -1, -2, -4, -6, -8, -8, -8, -8, -8 };
for (int k = 1; 8 * Mathf.Pow(0.88f, k) >= 0.5f; k++) pad.Add(-(float)System.Math.Round(8 * System.Math.Pow(0.88, k), 2));
Assert.AreEqual(31, pad.Count);
Assert.AreEqual(1.082f, CameraController.WheelNotches(pad.ToArray(), new int[pad.Count], pad.Count), 1e-3, "108.2 px is 1.08 notches");
}
[Test]
public void ATouchpadSwipeZoomsSmoothlyAndStaysOffPanels()
{
var c = NewController(out var go);
try
{
var rig = go.GetComponent<CameraRig>();
rig.Distance = 120000f;
foreach (var px in new[] { 0.5f, 2f, 8f, 8f, 4f, 1f }) // one frame's events each
{
var before = rig.Distance;
var notches = CameraController.WheelNotches(new[] { -px }, new[] { 0 }, 1);
CameraController.Step(rig, c.Gather(Vector2.zero, Vector2.zero, notches, 0, false, new Vector2(500, 0)), 0.016f, Map);
Assert.AreEqual(before * Mathf.Pow(0.9f, px / 100f), rig.Distance, 1f, $"{px} px");
}
var held = rig.Distance;
var swipe = new[] { -0.5f, -2f, -8f, -8f, -4f, -1f, -100f }; // a swipe and a mouse notch, over the panel
var overPanel = CameraController.WheelNotches(swipe, new int[swipe.Length], swipe.Length);
Assert.Greater(overPanel, 1f);
CameraController.Step(rig, c.Gather(Vector2.zero, Vector2.zero, overPanel, 0, false, new Vector2(50, 0)), 0.016f, Map);
Assert.AreEqual(held, rig.Distance, 1e-3, "no zoom over a panel");
}
finally { Object.DestroyImmediate(go); }
}
/// <summary>Task 24 review M3: zooming in then out by the same notches returns to the same distance.</summary>
[Test]
public void ZoomingInThenOutReturnsToTheStart()
{
var c = NewController(out var go);
try
{
var rig = go.GetComponent<CameraRig>();
foreach (var notches in new[] { 1f, 3f, 0.5f })
{
rig.Distance = 120000f;
CameraController.Step(rig, c.Gather(Vector2.zero, Vector2.zero, notches, 0, false, null), 0.016f, Map);
CameraController.Step(rig, c.Gather(Vector2.zero, Vector2.zero, -notches, 0, false, null), 0.016f, Map);
Assert.AreEqual(120000f, rig.Distance, 1f, $"{notches} notches in, then out");
}
rig.Distance = 120000f;
CameraController.Step(rig, c.Gather(Vector2.zero, Vector2.zero, -1f, 0, false, null), 0.016f, Map);
Assert.AreEqual(120000f / 0.9f, rig.Distance, 1f, "one notch out undoes one notch in (10%)");
}
finally { Object.DestroyImmediate(go); }
}
}
/// <summary>The zoom keys through Unity's own input path (#890, owner's ask): a virtual keyboard from the Input System's
/// test fixture, the project-wide Camera actions, and CameraController's frame (Tick, which Update calls), so a key that
/// stops being read or a modifier that stops being passed on goes red. Edit mode sends no Awake/OnEnable/OnDisable, so
/// the test sends them.</summary>
public class CameraZoomKeysThroughTheInputSystemTests : SharedCameraActionsFixture
{
static void Send(CameraController c, string message) =>
typeof(CameraController).GetMethod(message, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
.Invoke(c, null);
[Test]
public void HeldZoomKeysMoveTheCameraAndCtrlStopsThem()
{
InputSystem.actions = AssetDatabase.LoadAssetAtPath<InputActionAsset>("Assets/InputSystem_Actions.inputactions");
var keyboard = InputSystem.AddDevice<Keyboard>();
var go = new GameObject("KeyZoomTest", typeof(Camera));
var rig = go.AddComponent<CameraRig>();
rig.LookAt = new Vector3(500000, 0, 500000); rig.Distance = 100000f;
var c = go.AddComponent<CameraController>();
c.Bounds = new Rect(0, 0, 1000000, 1000000); // far larger than the view: no view clamp here
Send(c, "Awake"); Send(c, "OnEnable");
try
{
float AfterOneSecond(float from) => from * Mathf.Pow(1f - CameraController.ZoomPerStep, CameraController.ZoomKeysPerSecond);
Press(keyboard.equalsKey);
for (int i = 0; i < 10; i++) c.Tick(0.1f);
Assert.AreEqual(AfterOneSecond(100000f), rig.Distance, 1f, "= held for a second: six notches in");
Press(keyboard.leftCtrlKey);
var held = rig.Distance;
c.Tick(0.1f);
Assert.AreEqual(held, rig.Distance, 1e-3, "Ctrl with = is the browser's zoom, not the map's");
Release(keyboard.leftCtrlKey); Release(keyboard.equalsKey);
Press(keyboard.numpadMinusKey);
for (int i = 0; i < 10; i++) c.Tick(0.1f);
Assert.AreEqual(100000f, rig.Distance, 1f, "the numpad's - held for a second undoes it");
}
finally { Send(c, "OnDisable"); Object.DestroyImmediate(go); }
}
[Test]
public void DragOnsetDiscardsThirtyPixelsAndNeverCatchesUp()
{
var go = new GameObject("DragOnset", typeof(Camera), typeof(CameraRig));
try
{
var c = go.AddComponent<CameraController>();
c.HoldsMouseDrag = () => true;
var gesture = new CameraController.PressDrag();
gesture.Begin(Vector2.zero);
var position = Vector2.zero;
Vector2 Drag(Vector2 delta, bool down, bool held)
{
if (!down) { gesture.End(); position = Vector2.zero; return Vector2.zero; }
if (position == Vector2.zero) gesture.Begin(position);
position += delta; gesture.Move(position); return gesture.Take(held);
}
Assert.AreEqual(30f, TapPress.SlopPixels);
Assert.AreEqual(Vector2.zero, Drag(new Vector2(29, 0), true, true));
Assert.AreEqual(Vector2.zero, Drag(new Vector2(1, 0), true, true));
Assert.AreEqual(new Vector2(1, 0), Drag(new Vector2(1, 0), true, false));
Assert.AreEqual(new Vector2(-5, 2), Drag(new Vector2(-5, 2), true, false), "after onset all motion pans");
Assert.AreEqual(Vector2.zero, Drag(Vector2.zero, false, false), "no delayed release jump");
Assert.AreEqual(new Vector2(70, 0), Drag(new Vector2(100, 0), true, false), "one crossing frame");
Drag(Vector2.zero, false, false);
var diagonal = Drag(new Vector2(42, 56), true, false);
Assert.That(diagonal.x, Is.EqualTo(24f).Within(0.0001f));
Assert.That(diagonal.y, Is.EqualTo(32f).Within(0.0001f));
}
finally { Object.DestroyImmediate(go); }
}
[Test]
public void TurningInsideTheSlopOnlyPansTheCrossingSegmentsExcess()
{
var go = new GameObject("DragCorner", typeof(Camera), typeof(CameraRig));
try
{
var c = go.AddComponent<CameraController>(); c.HoldsTouchDrag = () => true;
var gesture = new CameraController.PressDrag();
var position = Vector2.zero;
Vector2 Drag(Vector2 delta, bool down, bool held)
{
if (!down) { gesture.End(); position = Vector2.zero; return Vector2.zero; }
if (position == Vector2.zero) gesture.Begin(position);
position += delta; gesture.Move(position); return gesture.Take(held);
}
Drag(new Vector2(0, 24), true, true);
// The segment reaches the radius-30 circle at (18,24): only its last 12 px pan.
var excess = Drag(new Vector2(30, 0), true, false);
Assert.That(excess.x, Is.EqualTo(12f).Within(0.0001f));
Assert.That(excess.y, Is.EqualTo(0f).Within(0.0001f));
Drag(Vector2.zero, false, false);
Drag(new Vector2(10, 0), true, true);
Assert.AreEqual(Vector2.zero, Drag(Vector2.zero, false, false), "short press drops held travel");
}
finally { Object.DestroyImmediate(go); }
}
}
// #1661 B1/S1/N1: real actions, independent of Ella's pointer fixture.
public class PressOriginCameraInputTests : SharedCameraActionsFixture
{
static void Send(Object o, string method) => o.GetType().GetMethod(method,
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.Invoke(o, null);
sealed class Rig : System.IDisposable
{
public readonly SelectThenClickMoveTests.Rig Game = new SelectThenClickMoveTests.Rig();
public readonly GameObject Go;
public readonly CameraRig View;
public readonly CameraController Camera;
public readonly MapPointer Pointer;
public readonly System.Collections.Generic.List<Vector2> Orders = new System.Collections.Generic.List<Vector2>();
public Rig()
{
InputSystem.actions = AssetDatabase.LoadAssetAtPath<InputActionAsset>("Assets/InputSystem_Actions.inputactions");
Go = new GameObject("PressOrigin", typeof(UnityEngine.Camera));
var lens = Go.GetComponent<UnityEngine.Camera>();
lens.fieldOfView = 60; lens.aspect = 16f / 9f; lens.rect = new Rect(0, 0, 1, 1);
View = Go.AddComponent<CameraRig>(); View.TopInset = 0;
View.Yaw = 0; View.LookAt = new Vector3(500000, 0, 500000); View.Distance = 100000;
Camera = Go.AddComponent<CameraController>();
Camera.Bounds = new Rect(0, 0, 1000000, 1000000);
Pointer = Go.AddComponent<MapPointer>(); Pointer.Map = Game.Map;
var game = Game;
var mover = game.Token("golani");
var target = game.Reach(game.Id(mover)).First(h => game.Layer.UnitToSelectAt(h.q, h.r) == null && !game.Info.IsCity(h.q, h.r));
game.Select(mover);
Pointer.PillHex = _ => target;
Pointer.IsOverUi = p => { Orders.Add(p); return false; };
Pointer.HexOrdered += (q, r) => Statecraft.Game.UI.GameRoot.OnHexOrdered(game.Map, game.Info, q, r);
var pointer = Pointer;
Camera.HoldsMouseDrag = () => pointer.RightTapCandidate;
Camera.HoldsTouchDrag = () => pointer.TouchTapCandidate;
Send(Camera, "Awake"); Send(Camera, "OnEnable"); Send(Pointer, "OnEnable");
}
public void Frame() { Pointer.Tick(); Camera.Tick(0.016f); }
public void Dispose() { Send(Pointer, "OnDisable"); Send(Camera, "OnDisable"); Object.DestroyImmediate(Go); Game.Dispose(); }
}
void Flick(int id, Vector2 from, Vector2 travel)
{
BeginTouch(id, from, queueEventOnly: true);
MoveTouch(id, from + travel, queueEventOnly: true);
EndTouch(id, from + travel);
}
static void PanIs(Rig rig, float pixels)
{
TestContext.WriteLine(string.Format(System.Globalization.CultureInfo.InvariantCulture,
"pan trace: excess={0} px; expected x={1}; actual x={2}; z={3}; distance={4}",
pixels, 500000 - pixels * 120, rig.View.LookAt.x, rig.View.LookAt.z, rig.View.Distance));
Assert.That(rig.View.LookAt.x, Is.EqualTo(500000 - pixels * 120).Within(0.1f));
Assert.That(rig.View.LookAt.z, Is.EqualTo(500000).Within(0.1f));
}
[TestCase(0)]
[TestCase(20)]
[TestCase(30)]
[TestCase(31)]
[TestCase(200)]
public void ACompletedFlickPansOnlyItsExcessOnce(int travel)
{
InputSystem.AddDevice<Touchscreen>();
using var rig = new Rig();
rig.Frame(); // Ella's warming frame is required to see the press edge.
var clicks = 0;
rig.Pointer.HexClicked += (_, __, ___) => clicks++;
Flick(1, new Vector2(600, 400), new Vector2(travel, 0));
rig.Frame(); PanIs(rig, Mathf.Max(0, travel - 30));
rig.Frame(); PanIs(rig, Mathf.Max(0, travel - 30));
Assert.AreEqual(travel <= 30 ? 1 : 0, rig.Orders.Count, "short presses keep their tap semantics");
Assert.AreEqual(travel <= 30 ? 1 : 0, clicks, "a touch tap selects; it does not issue a right-click order");
Assert.IsEmpty(rig.Game.Bridge.Session.Committed);
}
[Test]
public void LiftKeepsOnlyTravelNotAlreadyConsumedByADragFrame()
{
InputSystem.AddDevice<Touchscreen>();
using var rig = new Rig(); rig.Frame();
BeginTouch(1, new Vector2(600, 400)); rig.Frame();
MoveTouch(1, new Vector2(700, 400)); rig.Frame(); PanIs(rig, 70);
MoveTouch(1, new Vector2(800, 400), queueEventOnly: true);
EndTouch(1, new Vector2(800, 400));
rig.Frame(); PanIs(rig, 170);
rig.Frame(); PanIs(rig, 170);
Assert.IsEmpty(rig.Orders);
}
[TestCase(false)]
[TestCase(true)]
public void ANewShortPressCannotEraseThePreviousFlick(bool overUi)
{
InputSystem.AddDevice<Touchscreen>();
using var rig = new Rig(); rig.Frame();
rig.Camera.IsOverUi = p => overUi && p.x < 500;
rig.Pointer.IsOverUi = p => overUi && p.x < 500;
var clicks = 0;
rig.Pointer.HexClicked += (_, __, ___) => clicks++;
Flick(1, new Vector2(600, 400), new Vector2(200, 0));
BeginTouch(2, new Vector2(400, 400), queueEventOnly: true);
MoveTouch(2, new Vector2(410, 400));
rig.Frame(); PanIs(rig, 170);
EndTouch(2, new Vector2(410, 400));
rig.Frame(); rig.Frame(); PanIs(rig, 170);
Assert.AreEqual(overUi ? 0 : 1, clicks);
Assert.IsEmpty(rig.Game.Bridge.Session.Committed);
}
[TestCase(200, 340)]
[TestCase(-100, 100)]
public void TwoCompletedFlicksEachPayTheirOwnSlop(int secondTravel, int total)
{
InputSystem.AddDevice<Touchscreen>();
using var rig = new Rig(); rig.Frame();
Flick(1, new Vector2(600, 400), new Vector2(200, 0));
Flick(2, new Vector2(600, 400), new Vector2(secondTravel, 0));
rig.Frame(); PanIs(rig, total);
rig.Frame(); PanIs(rig, total);
Assert.IsEmpty(rig.Orders); Assert.IsEmpty(rig.Game.Bridge.Session.Committed);
}
[Test]
public void AUiOriginFlickCannotLeakIntoTheNextMapPress()
{
InputSystem.AddDevice<Touchscreen>();
using var rig = new Rig(); rig.Frame();
rig.Camera.IsOverUi = p => p.x < 500;
Flick(1, new Vector2(400, 400), new Vector2(200, 0));
rig.Frame(); PanIs(rig, 0);
BeginTouch(2, new Vector2(600, 400)); rig.Frame(); PanIs(rig, 0);
}
[TestCase(false)]
[TestCase(true)]
public void DisablingOrUngatedTouchDoesNotReplayACompletedFlick(bool ungated)
{
InputSystem.AddDevice<Touchscreen>();
using var rig = new Rig(); rig.Frame();
if (ungated) rig.Camera.HoldsTouchDrag = null;
Flick(1, new Vector2(600, 400), new Vector2(200, 0));
if (!ungated) { Send(rig.Camera, "OnDisable"); Send(rig.Camera, "OnEnable"); }
rig.Frame(); rig.Frame(); PanIs(rig, 0);
}
[Test]
public void RemovingTheTouchscreenDoesNotLoseOrRepeatAnApprovedFlick()
{
var screen = InputSystem.AddDevice<Touchscreen>();
using var rig = new Rig(); rig.Frame();
Flick(1, new Vector2(600, 400), new Vector2(200, 0));
InputSystem.RemoveDevice(screen);
rig.Frame(); PanIs(rig, 170);
rig.Frame(); PanIs(rig, 170);
}
void EndedPinch(bool oneUpdate, int movementStage, bool primaryFirst)
{
BeginTouch(1, new Vector2(600, 400), queueEventOnly: oneUpdate);
if (movementStage == 0) MoveTouch(1, new Vector2(800, 400), queueEventOnly: oneUpdate);
BeginTouch(2, new Vector2(900, 400), queueEventOnly: oneUpdate);
if (movementStage == 1) MoveTouch(1, new Vector2(800, 400), queueEventOnly: oneUpdate);
if (primaryFirst) EndTouch(1, new Vector2(800, 400), queueEventOnly: oneUpdate);
EndTouch(2, new Vector2(900, 400), queueEventOnly: oneUpdate);
if (!primaryFirst)
{
if (movementStage == 2) MoveTouch(1, new Vector2(800, 400), queueEventOnly: oneUpdate);
EndTouch(1, new Vector2(800, 400), queueEventOnly: oneUpdate);
}
if (oneUpdate) InputSystem.Update();
}
[TestCase(true, 0, false)]
[TestCase(true, 1, false)]
[TestCase(true, 2, false)]
[TestCase(false, 0, false)]
[TestCase(false, 1, false)]
[TestCase(false, 2, false)]
[TestCase(true, 1, true)]
[TestCase(false, 1, true)]
public void AnEndedPinchNeverBecomesALiftedPan(bool oneUpdate, int movementStage, bool primaryFirst)
{
InputSystem.AddDevice<Touchscreen>();
using var rig = new Rig(); rig.Frame();
EndedPinch(oneUpdate, movementStage, primaryFirst);
rig.Frame(); PanIs(rig, 0);
rig.Frame(); PanIs(rig, 0);
Assert.AreEqual(100000, rig.View.Distance, "an ended pair invents no pinch zoom");
Assert.IsEmpty(rig.Orders); Assert.IsEmpty(rig.Game.Bridge.Session.Committed);
}
[TestCase(false)]
[TestCase(true)]
public void APinchCannotDeleteAnUnrelatedValidFlick(bool pinchFirst)
{
InputSystem.AddDevice<Touchscreen>();
using var rig = new Rig(); rig.Frame();
if (pinchFirst) EndedPinch(false, 2, false);
Flick(3, new Vector2(600, 400), new Vector2(200, 0));
if (!pinchFirst) EndedPinch(false, 2, false);
rig.Frame(); PanIs(rig, 170);
rig.Frame(); PanIs(rig, 170);
Assert.IsEmpty(rig.Game.Bridge.Session.Committed);
}
[TestCase(0.05f)]
[TestCase(-0.05f)]
public void ATrackpadMagnifyStillZoomsWithALiftedFlick(float magnification)
{
InputSystem.AddDevice<Touchscreen>();
using var rig = new Rig(); rig.Frame();
Flick(1, new Vector2(600, 400), new Vector2(200, 0));
var pending = magnification;
rig.Camera.TrackpadMagnification = () => { var value = pending; pending = 0; return value; };
rig.Frame();
Assert.AreEqual(100000 / (1 + magnification), rig.View.Distance, 1f);
Assert.That(rig.View.LookAt.x, Is.EqualTo(500000 - 170 * 0.0012f * rig.View.Distance).Within(0.1f));
var at = rig.View.LookAt;
rig.Frame(); Assert.AreEqual(at, rig.View.LookAt);
Assert.AreEqual(100000 / (1 + magnification), rig.View.Distance, 1f);
}
[Test]
public void ASampledPinchKeepsTheRemainingFingersLivePan()
{
InputSystem.AddDevice<Touchscreen>();
using var rig = new Rig(); rig.Frame();
BeginTouch(1, new Vector2(600, 400)); rig.Frame();
MoveTouch(1, new Vector2(700, 400)); rig.Frame(); PanIs(rig, 70);
BeginTouch(2, new Vector2(900, 400)); rig.Frame(); PanIs(rig, 70);
EndTouch(2, new Vector2(900, 400)); rig.Frame(); PanIs(rig, 70);
MoveTouch(1, new Vector2(750, 400)); rig.Frame(); PanIs(rig, 120);
rig.Frame(); PanIs(rig, 120);
EndTouch(1, new Vector2(800, 400)); // a pinched press must not save even its final movement
rig.Frame(); rig.Frame(); PanIs(rig, 120);
Assert.AreEqual(100000, rig.View.Distance);
Assert.IsEmpty(rig.Orders); Assert.IsEmpty(rig.Game.Bridge.Session.Committed);
}
[Test]
public void ALiveTouchscreenPinchStillZoomsWithoutPanning()
{
InputSystem.AddDevice<Touchscreen>();
using var rig = new Rig(); rig.Frame();
BeginTouch(1, new Vector2(600, 400));
BeginTouch(2, new Vector2(900, 400)); rig.Frame();
MoveTouch(2, new Vector2(1000, 400)); rig.Frame();
PanIs(rig, 0);
Assert.AreEqual(90000, rig.View.Distance, 1f, "one hundred pixels of live pinch is one notch");
}
[Test]
public void EnableDrainsMagnifyAndANewUiPressStillBlocksZoom()
{
InputSystem.AddDevice<Touchscreen>();
using var rig = new Rig(); rig.Frame();
Send(rig.Camera, "OnDisable");
var pending = 0.05f;
rig.Camera.TrackpadMagnification = () => { var value = pending; pending = 0; return value; };
Send(rig.Camera, "OnEnable"); rig.Frame();
Assert.AreEqual(100000, rig.View.Distance);
Flick(1, new Vector2(600, 400), new Vector2(200, 0));
rig.Camera.IsOverUi = p => p.x < 500;
BeginTouch(2, new Vector2(400, 400)); pending = 0.05f;
rig.Frame(); PanIs(rig, 170);
Assert.AreEqual(100000, rig.View.Distance, "the retained pan exception must not clear OverUi");
}
[TestCase(10)]
[TestCase(31)]
public void AReleaseAndNewPressBeforeTheCameraFrameStartsANewGesture(int travel)
{
var mouse = InputSystem.AddDevice<Mouse>();
using var rig = new Rig();
Set(mouse.position, new Vector2(400, 400)); Press(mouse.rightButton);
Move(mouse.position, new Vector2(450, 400), new Vector2(50, 0)); rig.Frame();
var afterA = rig.View.LookAt;
Assert.That(afterA.x, Is.EqualTo(500000 - 20 * 120).Within(0.1f), "A has panned");
Release(mouse.rightButton);
var b = new Vector2(700, 400);
Set(mouse.position, b); Press(mouse.rightButton);
Move(mouse.position, b + new Vector2(travel, 0), new Vector2(travel, 0));
rig.Frame(); // no camera frame between A's release and B's movement
Assert.That(rig.View.LookAt.x, Is.EqualTo(afterA.x - (travel > 30 ? 120 : 0)).Within(0.1f));
Assert.AreEqual(afterA.z, rig.View.LookAt.z);
Release(mouse.rightButton); rig.Frame();
if (travel == 10)
{
CollectionAssert.AreEqual(new[] { b }, rig.Orders, "one order, at B's press position");
Assert.AreEqual(1, rig.Game.Bridge.Session.Committed.Count, "one sim command from B");
Assert.IsInstanceOf<Statecraft.Sim.Move>(rig.Game.Bridge.Session.Committed.Single());
}
else { Assert.IsEmpty(rig.Orders); Assert.IsEmpty(rig.Game.Bridge.Session.Committed); }
}
[TestCase(30)]
[TestCase(31)]
public void OnsetUsesThePressPositionDespitePrePressDeltaAndSeveralInputUpdates(int travel)
{
var mouse = InputSystem.AddDevice<Mouse>();
using var rig = new Rig();
Set(mouse.position, new Vector2(400, 400)); rig.Frame();
InputSystem.QueueStateEvent(mouse, new UnityEngine.InputSystem.LowLevel.MouseState
{ position = new Vector2(500, 400), delta = new Vector2(100, 0) });
InputSystem.QueueStateEvent(mouse, new UnityEngine.InputSystem.LowLevel.MouseState
{ position = new Vector2(500, 400), delta = new Vector2(100, 0) }
.WithButton(UnityEngine.InputSystem.LowLevel.MouseButton.Right));
InputSystem.Update(); rig.Frame(); // movement before press, in the same input update
Move(mouse.position, new Vector2(510, 400), new Vector2(10, 0));
Move(mouse.position, new Vector2(500 + travel, 400), new Vector2(travel - 10, 0));
rig.Frame(); // two InputSystem updates, one camera Tick
Assert.That(rig.View.LookAt.x, Is.EqualTo(500000 - (travel > 30 ? 120 : 0)).Within(0.1f));
Release(mouse.rightButton); rig.Frame();
Assert.That(rig.View.LookAt.x, Is.EqualTo(500000 - (travel > 30 ? 120 : 0)).Within(0.1f), "no release catch-up");
Assert.AreEqual(travel == 30 ? 1 : 0, rig.Game.Bridge.Session.Committed.Count);
}
[Test]
public void AUiOriginRemainsBlockedEvenAfterLeavingItBeforeTheCameraFrame()
{
var mouse = InputSystem.AddDevice<Mouse>();
using var rig = new Rig();
rig.Camera.IsOverUi = p => p.x < 500;
Set(mouse.position, new Vector2(400, 400)); Press(mouse.rightButton);
Move(mouse.position, new Vector2(600, 400), new Vector2(200, 0)); rig.Frame();
Assert.AreEqual(new Vector3(500000, 0, 500000), rig.View.LookAt);
Release(mouse.rightButton); rig.Frame();
Set(mouse.position, new Vector2(600, 400)); Press(mouse.rightButton);
Move(mouse.position, new Vector2(631, 400), new Vector2(31, 0)); rig.Frame();
Assert.That(rig.View.LookAt.x, Is.EqualTo(499880).Within(0.1f), "new map press clears the UI latch");
}
[TestCase(30)]
[TestCase(31)]
public void TouchOnsetAlsoUsesThePressOriginAcrossInputUpdates(int travel)
{
InputSystem.AddDevice<Touchscreen>();
using var rig = new Rig();
rig.Frame(); // warm the pointer's frame APIs, preserving Ella's still-tap rule
BeginTouch(1, new Vector2(600, 400)); rig.Frame();
MoveTouch(1, new Vector2(610, 400));
MoveTouch(1, new Vector2(600 + travel, 400)); rig.Frame();
Assert.That(rig.View.LookAt.x, Is.EqualTo(500000 - (travel > 30 ? 120 : 0)).Within(0.1f));
EndTouch(1, new Vector2(600 + travel, 400)); rig.Frame();
Assert.That(rig.View.LookAt.x, Is.EqualTo(500000 - (travel > 30 ? 120 : 0)).Within(0.1f), "no release jump");
}
[TestCase(false)]
[TestCase(true)]
public void ANullCallbackPansThatSourceImmediatelyEvenWhenTheOtherIsGated(bool touch)
{
var mouse = InputSystem.AddDevice<Mouse>();
InputSystem.AddDevice<Touchscreen>();
using var rig = new Rig();
if (touch)
{
rig.Camera.HoldsTouchDrag = null;
BeginTouch(1, new Vector2(600, 400)); rig.Frame();
MoveTouch(1, new Vector2(610, 400)); rig.Frame();
}
else
{
rig.Camera.HoldsMouseDrag = null;
Set(mouse.position, new Vector2(600, 400)); Press(mouse.rightButton); rig.Frame();
Move(mouse.position, new Vector2(610, 400), new Vector2(10, 0)); rig.Frame();
}
Assert.That(rig.View.LookAt.x, Is.EqualTo(498800).Within(0.1f), "ungated source pans all ten pixels");
}
}
/// <summary>Zoom from a pointing device through CameraController's frame (Tick, which Update calls), as the zoom keys are
/// tested above: the wheel through the Input System's test fixture and the project-wide Camera actions, and a macOS
/// trackpad pinch through the magnification the player's window received (TrackpadMagnification: TrackpadPinch.mm
/// in the macOS player, a stand-in here, since an edit-mode test cannot make a Cocoa magnify event). The owner found
/// on 27 Oct 2026 that zooming did nothing in the macOS player: the wheel, a two-finger scroll and the keys did zoom
/// there, but a pinch never reached the Input System at all.</summary>
public class CameraPointerZoomThroughTheFrameTests : SharedCameraActionsFixture
{
static void Send(Object o, string message) =>
o.GetType().GetMethod(message, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!
.Invoke(o, null);
static CameraController NewController(out CameraRig rig)
{
InputSystem.actions = AssetDatabase.LoadAssetAtPath<InputActionAsset>("Assets/InputSystem_Actions.inputactions");
var go = new GameObject("PointerZoomTest", typeof(Camera));
rig = go.AddComponent<CameraRig>();
rig.LookAt = new Vector3(500000, 0, 500000); rig.Distance = 100000f;
var c = go.AddComponent<CameraController>();
c.Bounds = new Rect(0, 0, 1000000, 1000000); // far larger than the view: no view clamp here
Send(c, "Awake"); Send(c, "OnEnable");
return c;
}
static void Dispose(CameraController c) { Send(c, "OnDisable"); Object.DestroyImmediate(c.gameObject); }
[TestCase(1f)]
[TestCase(-1f)]
public void AWheelNotchZoomsOneStepInOrOut(float notches)
{
var mouse = InputSystem.AddDevice<Mouse>();
var c = NewController(out var rig);
try
{
Set(mouse.position, new Vector2(400, 400)); c.Tick(0.016f);
Set(mouse.scroll, new Vector2(0, notches)); c.Tick(0.016f);
Assert.AreEqual(100000f * Mathf.Pow(1f - CameraController.ZoomPerStep, notches), rig.Distance, 1f,
notches > 0 ? "a notch up zooms in 10%" : "a notch down zooms out");
}
finally { Dispose(c); }
}
[TestCase(0.05f)]
[TestCase(-0.05f)]
public void ATrackpadPinchScalesTheViewByItsMagnification(float magnification)
{
InputSystem.AddDevice<Mouse>();
var c = NewController(out var rig);
try
{
var pending = magnification;
c.TrackpadMagnification = () => { var m = pending; pending = 0f; return m; };
c.Tick(0.016f);
// Fingers spread by 5% (magnification +0.05): the map shows 5% larger, so the camera is 1.05 times closer.
Assert.AreEqual(100000f / (1f + magnification), rig.Distance, 1f, "the pinch zooms as far as the fingers moved");
c.Tick(0.016f);
Assert.AreEqual(100000f / (1f + magnification), rig.Distance, 1f, "a pinch is taken once, not every frame");
}
finally { Dispose(c); }
}
[Test]
public void APinchOverTheUiIsTheUisAsTheWheelIs()
{
var mouse = InputSystem.AddDevice<Mouse>();
var c = NewController(out var rig);
try
{
c.IsOverUi = _ => true;
Set(mouse.position, new Vector2(400, 400));
c.TrackpadMagnification = () => 0.05f;
c.Tick(0.016f);
Assert.AreEqual(100000f, rig.Distance, 1e-3, "over a panel a pinch does not zoom the map");
}
finally { Dispose(c); }
}
[Test]
public void ThePinchPluginIsBuiltIntoTheMacPlayerOnly()
{
var plugin = (PluginImporter)AssetImporter.GetAtPath("Assets/Scripts/Map/TrackpadPinch.mm");
Assert.IsNotNull(plugin, "TrackpadPinch.mm is imported as a native plugin");
Assert.IsTrue(plugin.GetCompatibleWithPlatform(BuildTarget.StandaloneOSX), "the macOS player compiles it");
Assert.IsFalse(plugin.GetCompatibleWithEditor(), "the editor has no such symbol: CameraController asks only in the player");
foreach (var other in new[] { BuildTarget.StandaloneWindows64, BuildTarget.StandaloneLinux64, BuildTarget.WebGL })
Assert.IsFalse(plugin.GetCompatibleWithPlatform(other), other + " does not build AppKit code");
}
}
/// <summary>Accessibility audit L4 against B6, the camera half: while a screen is open (ScreenTakesUpDown) the Up and Down
/// arrows move between the screen's rows and do not pan; Left, Right and W still pan; with no screen open Up pans as
/// before. The owner's answer on #2340, Q27: "do the recommended for all"
/// (https://github.com/eyalgolan/statecraft-israel/issues/2340#issuecomment-6623136558). The keys go through the Input
/// System test fixture, the project-wide Camera actions and CameraController's frame, as in the zoom-keys test.</summary>
public class CameraArrowsWithAScreenOpenTests : SharedCameraActionsFixture
{
static void Send(CameraController c, string message) =>
typeof(CameraController).GetMethod(message, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
.Invoke(c, null);
[Test]
public void UpAndDownPanOnlyWithNoScreenOpenL4()
{
InputSystem.actions = AssetDatabase.LoadAssetAtPath<InputActionAsset>("Assets/InputSystem_Actions.inputactions");
var keyboard = InputSystem.AddDevice<Keyboard>();
var go = new GameObject("ArrowPanTest", typeof(Camera));
var rig = go.AddComponent<CameraRig>();
rig.Distance = 100000f;
var c = go.AddComponent<CameraController>();
c.Bounds = new Rect(0, 0, 1000000, 1000000);
var open = true;
c.ScreenTakesUpDown = () => open;
Send(c, "Awake"); Send(c, "OnEnable");
try
{
Vector3 Held(params UnityEngine.InputSystem.Controls.KeyControl[] keys)
{
rig.LookAt = new Vector3(500000, 0, 500000);
foreach (var k in keys) Press(k);
for (int i = 0; i < 5; i++) c.Tick(0.1f);
foreach (var k in keys) Release(k);
c.Tick(0.1f);
return rig.LookAt - new Vector3(500000, 0, 500000);
}
Assert.AreEqual(Vector3.zero, Held(keyboard.upArrowKey), "screen open: Up does not pan");
Assert.AreEqual(Vector3.zero, Held(keyboard.downArrowKey), "screen open: Down does not pan");
var right = Held(keyboard.rightArrowKey);
Assert.Greater(right.magnitude, 1f, "screen open: Right still pans");
Assert.AreEqual(right.x, Held(keyboard.upArrowKey, keyboard.rightArrowKey).x, 1f, "screen open: Up with Right pans as Right alone");
Assert.Greater(Held(keyboard.leftArrowKey).magnitude, 1f, "screen open: Left still pans");
var w = Held(keyboard.wKey);
Assert.Greater(w.magnitude, 1f, "screen open: W still pans");
Assert.AreEqual(w, Held(keyboard.wKey, keyboard.downArrowKey), "screen open: Down held with W leaves W's pan");
open = false;
Assert.Greater(Held(keyboard.upArrowKey).magnitude, 1f, "no screen open: Up pans (B6)");
Assert.Greater(Held(keyboard.downArrowKey).magnitude, 1f, "no screen open: Down pans (B6)");
}
finally { Send(c, "OnDisable"); Object.DestroyImmediate(go); }
}
}