Merge origin/master into eureka/aetheria-release-mods-in-tree

AetheriaStores.Open keeps both: the registry parameter and the missing-catalog refusal.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-10 13:35:39 +02:00
commit 2be1f8efa2
26 changed files with 1747 additions and 24 deletions

View file

@ -11,6 +11,8 @@
<!-- AuthoredSettings (Unity Settings.asset YAML reader), so fixtures load the shipped gameplay settings
instead of hand-copying them. -->
<ProjectReference Include="..\..\tools\AetherDb\AetherDb.csproj" />
<!-- The player build's staging rules: Unity-free, owned by Assets/Editor, compiled here so the suite can prove them. -->
<Compile Include="..\..\Assets\Editor\PlayerStaging.cs" Link="PlayerStaging.cs" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.4.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5" />

View file

@ -116,7 +116,10 @@ public sealed class AetheriaStoresTests : IDisposable
public void MissingCatalogGlobalIsLoud()
{
var empty = Path.Combine(_root, "empty.cc");
using (AetheriaStores.Open(empty, catalogWritable: true)) { }
// A catalog file that exists but lacks the global: the read-only open reaches the global check.
File.Copy(Catalog, empty);
using (var seed = AetheriaStores.Open(empty, catalogWritable: true))
Assert.True(seed.Commit(batch => batch.Remove(seed.RefOf(seed.GetGlobal<TestCatalogGlobal>()).Key)));
var error = Assert.Throws<InvalidOperationException>(() => AetheriaStores.Open(empty));
Assert.Contains("aetheria.tests.catalogglobal", error.Message);
using (AetheriaStores.Open(Catalog)) { }
@ -200,6 +203,23 @@ public sealed class AetheriaStoresTests : IDisposable
Assert.Null(record);
}
// A shipped player with no catalog must not boot into an empty game: a read-only open of a missing path throws
// naming the path, and does not create the file. A writable open still seeds an empty catalog.
[Fact]
public void AStoreRefusesAMissingCatalog()
{
var missing = Path.Combine(_root, "absent", "Aetheria.cc");
// FileNotFoundException, not the catalog-global check: that one also throws on a missing file whenever a global is registered.
var error = Assert.Throws<FileNotFoundException>(() => AetheriaStores.Open(missing));
Assert.Contains(missing, error.Message);
Assert.False(File.Exists(missing));
Assert.False(Directory.Exists(Path.GetDirectoryName(missing)));
using (var seeded = AetheriaStores.Open(missing, catalogWritable: true))
Assert.Empty(seeded.GetAll<Faction>());
}
private static string Hash(string path) => Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path)));
private static string[] SchemaNames(string path)

View file

@ -0,0 +1,101 @@
using System;
using System.IO;
using System.Linq;
using Xunit;
// A player directory's GameData is exactly the catalog, Narrative/** and (when the repo has them) Mods/**.
public sealed class PlayerStagingTests : IDisposable
{
private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-staging-" + Guid.NewGuid().ToString("N"));
private string Repo => Path.Combine(_root, "repo");
private string Player => Path.Combine(_root, "player");
private string Source(string relative) => Path.Combine(Repo, "GameData", relative);
private string Staged(string relative) => Path.Combine(Player, "GameData", relative);
public PlayerStagingTests()
{
Write(Source("Aetheria.cc"), "catalog-bytes");
Write(Source("Narrative/Main.ink"), "main");
Write(Source("Narrative/Quests/Deep/First.ink"), "first");
Write(Source("SoundbanksInfo.json"), "{}");
Write(Source("run.cc"), "a developer's run");
Write(Source("player.cc"), "a developer's settings");
Directory.CreateDirectory(Player);
}
public void Dispose() => Directory.Delete(_root, true);
[Fact]
public void StagesTheCatalogAndNarrativeFileForFile()
{
PlayerStaging.Stage(Repo, Player);
Assert.Equal("catalog-bytes", File.ReadAllText(Staged("Aetheria.cc")));
Assert.Equal("main", File.ReadAllText(Staged("Narrative/Main.ink")));
Assert.Equal("first", File.ReadAllText(Staged("Narrative/Quests/Deep/First.ink")));
}
[Fact]
public void StagesModsWhenTheRepoHasThemAndNoModsFolderWhenItDoesNot()
{
PlayerStaging.Stage(Repo, Player);
Assert.False(Directory.Exists(Staged("Mods")));
Write(Source("Mods/ship-a/ship.cc"), "ship");
Write(Source("Mods/ship-a/mesh/hull.glb"), "hull");
PlayerStaging.Stage(Repo, Player);
Assert.Equal("ship", File.ReadAllText(Staged("Mods/ship-a/ship.cc")));
Assert.Equal("hull", File.ReadAllText(Staged("Mods/ship-a/mesh/hull.glb")));
}
[Fact]
public void StagesNothingElseFromGameData()
{
PlayerStaging.Stage(Repo, Player);
var staged = Directory.GetFileSystemEntries(Path.Combine(Player, "GameData")).Select(Path.GetFileName).OrderBy(name => name).ToArray();
Assert.Equal(new[] { "Aetheria.cc", "Narrative" }, staged);
}
[Fact]
public void ReplacesWhatAnEarlierBuildLeftInGameData()
{
Write(Staged("Aetheria.cc"), "stale");
Write(Staged("run.cc"), "a played run");
Write(Staged("Mods/gone/ship.cc"), "removed mod");
PlayerStaging.Stage(Repo, Player);
Assert.Equal("catalog-bytes", File.ReadAllText(Staged("Aetheria.cc")));
Assert.False(File.Exists(Staged("run.cc")));
Assert.False(Directory.Exists(Staged("Mods")));
}
[Fact]
public void RefusesAMissingCatalogNamingItAndLeavesNoGameData()
{
File.Delete(Source("Aetheria.cc"));
var error = Assert.Throws<InvalidOperationException>(() => PlayerStaging.Stage(Repo, Player));
Assert.Contains("GameData/Aetheria.cc", error.Message);
Assert.False(Directory.Exists(Path.Combine(Player, "GameData")));
}
[Fact]
public void RefusesMissingNarrative()
{
Directory.Delete(Source("Narrative"), true);
var error = Assert.Throws<InvalidOperationException>(() => PlayerStaging.Stage(Repo, Player));
Assert.Contains("GameData/Narrative", error.Message);
}
private static void Write(string path, string text)
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
File.WriteAllText(path, text);
}
}

View file

@ -232,7 +232,7 @@ public sealed class ShipAuthoringTests
private static readonly string[] AllRoles =
{
"map-icon", "hull-collider", "shield", "tractor", "thruster-emitter", "weapon-mount", "weapon-muzzle", "radiator-mesh", "articulation"
"map-icon", "hull-collider", "shield", "tractor", "thruster-emitter", "weapon-mount", "weapon-muzzle", "radiator-mesh"
};
// The fixture with its thruster swapped for one hardpoint of the given type at mount id "mount", and no anchor for it.

View file

@ -446,7 +446,7 @@ public sealed class ShipModCatalogTests : IDisposable
{
var path = Write("nodes.glb", ShipFixture.Glb(@"{""asset"":{""version"":""2.0""},""nodes"":[
{""name"":""plain""},{""extras"":{""aetheria.id"":""a""}},{""extras"":{}},{""extras"":{""aetheria.id"":""""}},{""mesh"":0,""extras"":{""aetheria.id"":""b""}}]}"));
Assert.Equal(new Dictionary<string, (uint, bool)> { ["a"] = (1, false), ["b"] = (4, true) }, ShipModCatalog.ReadNodeIds(path));
Assert.Equal(new Dictionary<string, (uint, bool, int)> { ["a"] = (1, false, -1), ["b"] = (4, true, -1) }, ShipModCatalog.ReadNodeIds(path));
}
[Fact]
@ -610,7 +610,7 @@ public sealed class ShipModCatalogTests : IDisposable
private void WritePackage(string id, string hullName = "Skiff", string[] nodes = null, string modelAsset = "skiff.glb",
Action<ShipParts> tweak = null, string[] meshNodes = null) => ShipFixture.WritePackage(Mods, id, hullName, nodes, modelAsset, tweak, meshNodes);
private static Dictionary<string, uint> Indices(Dictionary<string, (uint Index, bool HasMesh)> nodes) =>
private static Dictionary<string, uint> Indices(Dictionary<string, (uint Index, bool HasMesh, int Parent)> nodes) =>
nodes.ToDictionary(node => node.Key, node => node.Value.Index);
private static int Occurrences(byte[] haystack, byte[] needle)

View file

@ -0,0 +1,384 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using CultMath;
using Xunit;
// The rig in the visual record: what the judge (Validate) refuses about joints and the guns that ride them, what Bind
// refuses when the GLB disagrees with the record, and what ShipModPlan.Rigs hands the assembler. The rig is
// presentation (ruling rig-is-presentation): arc stays the hardpoint's and traverse the weapon's, so the judge only
// asks that the chain could sweep the arc the hardpoint states.
public sealed class ShipRigTests : IDisposable
{
private readonly TempDirectory _directory = new TempDirectory();
public void Dispose() => _directory.Dispose();
private static readonly float[] Up = { 0f, 1f, 0f };
private static readonly float[] Right = { 1f, 0f, 0f };
private static ShipJoint Joint(string id, string parent, params (float[] Axis, float Min, float Max)[] dofs) => new ShipJoint
{
Id = id, Parent = parent,
Axes = dofs.SelectMany(dof => dof.Axis).ToArray(), Min = dofs.Select(dof => dof.Min).ToArray(), Max = dofs.Select(dof => dof.Max).ToArray()
};
private static float[] Tilted(float degrees) => new[] { MathF.Sin(degrees * MathF.PI / 180f), MathF.Cos(degrees * MathF.PI / 180f), 0f };
// The fixture's skiff with energy guns "g0".."gN" side by side (one cell each) and the thruster after them. Each gun
// is a weapon mount (node "gN") with one muzzle ("gN.muzzle", node "gN-muzzle"), fires 180 degrees, and rides the joint
// its tuple names (null is a fixed mount).
private static ShipParts Armed(params string[] jointOfGun)
{
var ship = ShipAuthoringTests.Fixture();
var shape = new Shape(jointOfGun.Length + 1, 1);
for (var x = 0; x <= jointOfGun.Length; x++) shape.Cells[x, 0] = true;
ship.Hull.Shape = shape;
ship.Hull.Hardpoints[0].Position = new int2(jointOfGun.Length, 0);
for (var gun = 0; gun < jointOfGun.Length; gun++)
{
ship.Hull.Hardpoints.Add(new HardpointData
{ Type = HardpointType.Energy, Position = new int2(gun, 0), Shape = new Shape(), Transform = $"g{gun}", FiringArc = 180 });
ship.Visual.Anchors.Add(new ShipAnchor { Id = $"g{gun}", Role = "weapon-mount", ModelNodeId = $"g{gun}", Joint = jointOfGun[gun] });
ship.Visual.Anchors.Add(new ShipAnchor { Id = $"g{gun}.muzzle", Role = "weapon-muzzle", ModelNodeId = $"g{gun}-muzzle", ParentId = $"g{gun}" });
}
return ship;
}
private static string Refusal(ShipParts ship) => Assert.Throws<InvalidOperationException>(ship.Validate).Message;
// One gun, on joint "j" with the given degrees of freedom, firing the given arc.
private static ShipParts OneGun(float arc, params (float[] Axis, float Min, float Max)[] dofs)
{
var ship = Armed("j");
ship.Visual.Joints.Add(Joint("j", null, dofs));
ship.Hull.Hardpoints.Single(hardpoint => hardpoint.Transform == "g0").FiringArc = arc;
return ship;
}
[Fact]
public void AnArmedShipWithAJointIsValid() => OneGun(90, (Up, -45f, 45f)).Validate();
[Fact]
public void ReachIsTheYawRangeOfTheChainAgainstTheArcTheHardpointStates()
{
OneGun(90, (Up, -45f, 45f)).Validate();
var short1 = Refusal(OneGun(100, (Up, -45f, 45f)));
Assert.Contains("joint j chain reaches 90 degrees of yaw", short1);
Assert.Contains("100 degree firing arc", short1);
// Serial degrees of freedom add, whether they share a joint or sit on two.
OneGun(120, (Up, -30f, 30f), (Up, -30f, 30f)).Validate();
Assert.Contains("reaches 120", Refusal(OneGun(121, (Up, -30f, 30f), (Up, -30f, 30f))));
var serial = Armed("child");
serial.Visual.Joints.Add(Joint("base", null, (Up, -30f, 30f)));
serial.Visual.Joints.Add(Joint("child", "base", (Up, -30f, 30f)));
serial.Hull.Hardpoints.Single(hardpoint => hardpoint.Transform == "g0").FiringArc = 120;
serial.Validate();
serial.Hull.Hardpoints.Single(hardpoint => hardpoint.Transform == "g0").FiringArc = 121;
Assert.Contains("reaches 120", Refusal(serial));
// A degree of freedom about +X is pitch: it adds nothing, however wide.
Assert.Contains("reaches 0 degrees", Refusal(OneGun(10, (Right, -180f, 180f))));
Assert.Contains("reaches 90", Refusal(OneGun(91, (Up, -45f, 45f), (Right, -180f, 180f))));
// A full turn covers every arc up to 360, and no reach is reported above it.
OneGun(360, (Up, -180f, 180f)).Validate();
Assert.Contains("reaches 360 degrees", Refusal(OneGun(400, (Up, -180f, 180f), (Up, -180f, 180f))));
}
// Reach is Max - Min per degree of freedom, however the limits sit about zero: a sweep from 20 to 50 reaches 30, and one from
// -10 to 50 reaches 60. Symmetric limits cannot tell that from |Min| + |Max| (70, 60) or twice the larger side (100, 100).
[Fact]
public void ReachIsMaxMinusMinForLimitsThatSitOffCentre()
{
OneGun(30, (Up, 20f, 50f)).Validate();
Assert.Contains("reaches 30 degrees", Refusal(OneGun(31, (Up, 20f, 50f))));
OneGun(60, (Up, -10f, 50f)).Validate();
Assert.Contains("reaches 60 degrees", Refusal(OneGun(61, (Up, -10f, 50f))));
OneGun(50, (Up, -50f, 0f)).Validate();
Assert.Contains("reaches 50 degrees", Refusal(OneGun(51, (Up, -50f, 0f))));
// Off-centre limits on two serial degrees of freedom add their own ranges: 30 + 60.
OneGun(90, (Up, 20f, 50f), (Up, -10f, 50f)).Validate();
Assert.Contains("reaches 90 degrees", Refusal(OneGun(91, (Up, 20f, 50f), (Up, -10f, 50f))));
}
[Fact]
public void AnAxisWithinFiveDegreesOfUpIsYawAndOneBeyondItIsNot()
{
OneGun(90, (Tilted(4f), -45f, 45f)).Validate();
Assert.Contains("reaches 0 degrees", Refusal(OneGun(90, (Tilted(6f), -45f, 45f))));
// An axis pointing down is as much yaw as one pointing up.
OneGun(90, (new[] { 0f, -1f, 0f }, -45f, 45f)).Validate();
}
[Fact]
public void AChainStopsAtADrivenAncestorSoItsYawDoesNotCountForTheChild()
{
var ship = Armed("outer", "inner");
ship.Visual.Joints.Add(Joint("outer", null, (Up, -180f, 180f)));
ship.Visual.Joints.Add(Joint("inner", "outer", (Up, -10f, 10f)));
ship.Hull.Hardpoints.Single(hardpoint => hardpoint.Transform == "g1").FiringArc = 20;
ship.Validate();
ship.Hull.Hardpoints.Single(hardpoint => hardpoint.Transform == "g1").FiringArc = 100;
Assert.Contains("joint inner chain reaches 20 degrees", Refusal(ship));
// With nothing riding the outer joint it is only a link in the inner chain, and counts.
ship.Visual.Anchors.Single(anchor => anchor.Id == "g0").Joint = null;
ship.Validate();
}
[Fact]
public void AGunOnAJointStatesItsArc()
{
var ship = OneGun(0, (Up, -180f, 180f));
Assert.Contains("must state its firing arc above 0", Refusal(ship));
// The same hardpoint on no joint is a fixed mount, and a fixed mount at the default arc is fine.
ship.Visual.Anchors.Single(anchor => anchor.Id == "g0").Joint = null;
ship.Validate();
}
[Fact]
public void MountsOnOneJointShareTheirArcAndRotation()
{
var ship = Armed("j", "j");
ship.Visual.Joints.Add(Joint("j", null, (Up, -180f, 180f)));
ship.Validate();
ship.Hull.Hardpoints.Single(hardpoint => hardpoint.Transform == "g1").FiringArc = 90;
Assert.Contains("must share Rotation and FiringArc", Refusal(ship));
ship.Hull.Hardpoints.Single(hardpoint => hardpoint.Transform == "g1").FiringArc = 180;
ship.Hull.Hardpoints.Single(hardpoint => hardpoint.Transform == "g1").Rotation = ItemRotation.Reversed;
Assert.Contains("must share Rotation and FiringArc", Refusal(ship));
// Guns on different joints, or one on none, keep their own.
ship.Visual.Joints.Add(Joint("k", null, (Up, -180f, 180f)));
ship.Visual.Anchors.Single(anchor => anchor.Id == "g1").Joint = "k";
ship.Validate();
}
[Fact]
public void AJointRidesOnlyAWeaponMountThatNamesARealJoint()
{
var ship = Armed("ghost");
Assert.Contains("names an unknown joint", Refusal(ship));
ship = Armed("j");
ship.Visual.Joints.Add(Joint("j", null, (Up, -180f, 180f)));
ship.Visual.Anchors.Single(anchor => anchor.Id == "g0.muzzle").Joint = "j";
Assert.Contains("only a weapon mount rides one", Refusal(ship));
}
[Fact]
public void JointShapeAcceptsItsBoundariesAndTheUnitTolerance()
{
OneGun(1, (Up, -180f, 180f)).Validate();
OneGun(1, (Up, 179f, 180f)).Validate();
OneGun(1, (new[] { 0f, 1.0009f, 0f }, 0f, 5f)).Validate();
OneGun(1, (new[] { 0f, .9991f, 0f }, 0f, 5f)).Validate();
Assert.Contains("must be a unit vector", Refusal(OneGun(1, (new[] { 0f, 1.0015f, 0f }, 0f, 5f))));
Assert.Contains("must be a unit vector", Refusal(OneGun(1, (new[] { 0f, .9985f, 0f }, 0f, 5f))));
}
// ---- Bind: the GLB must have the rig the record states ----
// A model node: its glTF name (unique, what Parent names), its aetheria.id (null for a node the exporter left untagged),
// its parent's name, and whether it carries a mesh.
private record Node(string Name, string Id, string Parent, bool Mesh = false);
// arm > elbow > wrist > (an untagged bracket) > gun > gun-muzzle, with the fixture's other nodes at the root.
private static readonly Node[] RigNodes =
{
new Node("map", "map", null), new Node("collider", "collider", null), new Node("shield", "shield", null),
new Node("tractor", "tractor", null), new Node("thruster-port", "thruster-port", null, true),
new Node("arm", "arm", null), new Node("elbow", "elbow", "arm"), new Node("wrist", "wrist", "elbow"),
new Node("bracket", null, "wrist"), new Node("gun", "gun", "bracket"), new Node("gun-muzzle", "gun-muzzle", "gun")
};
private static string GlbJson(Node[] nodes)
{
var text = new StringBuilder(@"{""asset"":{""version"":""2.0""},""meshes"":[{""primitives"":[]}],""nodes"":[");
for (var index = 0; index < nodes.Length; index++)
{
var node = nodes[index];
var kids = Enumerable.Range(0, nodes.Length).Where(child => nodes[child].Parent == node.Name).ToArray();
text.Append(index > 0 ? "," : "").Append($@"{{""name"":""{node.Name}""");
if (node.Mesh) text.Append(@",""mesh"":0");
if (node.Id != null) text.Append($@",""extras"":{{""aetheria.id"":""{node.Id}""}}");
if (kids.Length > 0) text.Append(@",""children"":[" + string.Join(",", kids) + "]");
text.Append('}');
}
return text.Append("]}").ToString();
}
// The fixture's package with the arm rig (arm, elbow, wrist; the gun on the wrist), then the tweak, written beside a
// GLB of the given nodes.
private string Package(Action<ShipParts> tweak, Node[] nodes = null)
{
var mods = Path.Combine(_directory.Path, "Mods");
Directory.CreateDirectory(mods);
var directory = ShipFixture.WritePackage(mods, "mod.skiff", tweak: ship =>
{
ship.Hull.Hardpoints.Single(hardpoint => hardpoint.Transform == "gun").FiringArc = 90;
ship.Visual.Joints.Add(Joint("arm", null, (Up, -45f, 45f)));
ship.Visual.Joints.Add(Joint("elbow", "arm", (Right, -45f, 45f)));
ship.Visual.Joints.Add(Joint("wrist", "elbow", (Up, -45f, 45f)));
ship.Visual.Anchors.Single(anchor => anchor.Id == "gun").Joint = "wrist";
tweak?.Invoke(ship);
});
File.WriteAllBytes(Path.Combine(directory, "skiff.glb"), ShipFixture.Glb(GlbJson(nodes ?? RigNodes)));
return Path.Combine(directory, "ship.cc");
}
private static string BindRefusal(string path) => Assert.Throws<InvalidOperationException>(() => ShipModCatalog.ReadPackage(path)).Message;
private static Node[] Reparent(string name, string parent) =>
RigNodes.Select(node => node.Name == name ? node with { Parent = parent } : node).ToArray();
[Fact]
public void BindAcceptsARigTheModelHasEvenWithAnUntaggedNodeBetween()
{
var package = ShipModCatalog.ReadPackage(Package(null));
Assert.Equal(new[] { "arm", "elbow", "wrist" }, package.Visual.Joints.Select(joint => joint.Id));
}
// The exporter tags nodes that are not joints (a bracket, a forearm mesh). They sit between a mount and its joint and
// between a joint and its parent joint, and the nearest JOINT above is still what Bind compares.
[Fact]
public void BindWalksPastTaggedNodesThatAreNotJoints()
{
var nodes = RigNodes.Select(node => node.Name switch
{
"bracket" => node with { Id = "bracket" },
"wrist" => node with { Parent = "forearm" },
_ => node
}).Append(new Node("forearm", "forearm", "elbow")).ToArray();
var package = ShipModCatalog.ReadPackage(Package(null, nodes));
Assert.Equal(new[] { "arm", "elbow", "wrist" }, package.Visual.Joints.Select(joint => joint.Id));
Assert.Equal("wrist", package.Visual.Anchors.Single(anchor => anchor.Id == "gun").Joint);
}
[Fact]
public void BindRefusesAMountWhoseJointIsNotTheNearestOneAboveItsNode()
{
Assert.Contains("weapon mount gun must name the nearest joint above its model node",
BindRefusal(Package(ship => ship.Visual.Anchors.Single(anchor => anchor.Id == "gun").Joint = "elbow")));
}
[Fact]
public void BindRefusesAMountThatTheRecordAndTheModelPlaceDifferently()
{
// The record says the gun is fixed; the model hangs it under the wrist.
Assert.Contains("weapon mount gun must name the nearest joint above its model node",
BindRefusal(Package(ship => ship.Visual.Anchors.Single(anchor => anchor.Id == "gun").Joint = null)));
// The record rides the wrist; the model hangs the gun at the root.
Assert.Contains("weapon mount gun must name the nearest joint above its model node", BindRefusal(Package(null, Reparent("gun", null))));
}
[Fact]
public void BindRefusesAJointThatIsNoModelNode()
{
var path = Package(null, RigNodes.Where(node => node.Name != "elbow").Select(node => node.Name == "wrist" ? node with { Parent = null } : node).ToArray());
Assert.Contains("model has no node with aetheria.id=elbow for a joint", BindRefusal(path));
}
[Fact]
public void BindRefusesAJointWhoseParentSkipsAJointNode()
{
Assert.Contains("joint wrist must name the nearest joint above its model node as its Parent",
BindRefusal(Package(ship => ship.Visual.Joints.Single(joint => joint.Id == "wrist").Parent = "arm")));
Assert.Contains("joint elbow must name the nearest joint above its model node as its Parent",
BindRefusal(Package(ship => ship.Visual.Joints.Single(joint => joint.Id == "elbow").Parent = null)));
}
[Fact]
public void BindRefusesAThrusterMeshUnderAJointNamingTheFollowUp() =>
Assert.Contains("gimballed-thrusters", BindRefusal(Package(null, Reparent("thruster-port", "wrist"))));
[Fact]
public void NodeParentsAreTheNearestTaggedAncestorAndRootsHaveNone()
{
var path = Path.Combine(_directory.Path, "rig.glb");
File.WriteAllBytes(path, ShipFixture.Glb(GlbJson(RigNodes)));
var nodes = ShipModCatalog.ReadNodeIds(path);
Assert.Equal(-1, nodes["arm"].Parent);
Assert.Equal((int)nodes["arm"].Index, nodes["elbow"].Parent);
Assert.Equal((int)nodes["wrist"].Index, nodes["gun"].Parent);
Assert.Equal((int)nodes["gun"].Index, nodes["gun-muzzle"].Parent);
}
// ---- ShipModPlan.Rigs ----
[Fact]
public void RigsAreOnePerDrivenJointInHullOrderOfTheirFirstWeaponWithChainsThatStopAtDrivenAncestors()
{
// g0 on the inner joint, g1 and g2 on the outer one (g2 authored first among the anchors).
var ship = Armed("barrel", "turret", "turret");
ship.Visual.Joints.Add(Joint("turret", null, (Up, -180f, 180f)));
ship.Visual.Joints.Add(Joint("barrel", "turret", (Up, -180f, 180f)));
ship.Visual.Anchors.RemoveAll(anchor => anchor.Id == "g1.muzzle");
ship.Visual.Anchors.Add(new ShipAnchor { Id = "g1.b", Role = "weapon-muzzle", ModelNodeId = "g1-b", ParentId = "g1", Order = 1 });
ship.Visual.Anchors.Add(new ShipAnchor { Id = "g1.z", Role = "weapon-muzzle", ModelNodeId = "g1-z", ParentId = "g1", Order = 0 });
ship.Visual.Anchors.Reverse();
var rigs = ShipModPlan.Build(ship.Hull, ship.Visual).Rigs;
Assert.Equal(2, rigs.Length);
Assert.Equal("barrel", rigs[0].Joint);
Assert.Equal(new[] { "barrel" }, rigs[0].Chain);
Assert.Equal(("g0", "g0.muzzle"), (rigs[0].LeadMount, rigs[0].LeadMuzzle));
Assert.Equal("turret", rigs[1].Joint);
Assert.Equal(new[] { "turret" }, rigs[1].Chain);
Assert.Equal(("g1", "g1.z"), (rigs[1].LeadMount, rigs[1].LeadMuzzle));
}
// Hull order, not name order: the first gun rides "turret" and the second "barrel".
[Fact]
public void RigsFollowHullOrderAndNotTheOrderOfTheJointNames()
{
var ship = Armed("turret", "barrel");
ship.Visual.Joints.Add(Joint("turret", null, (Up, -180f, 180f)));
ship.Visual.Joints.Add(Joint("barrel", null, (Up, -180f, 180f)));
var rigs = ShipModPlan.Build(ship.Hull, ship.Visual).Rigs;
Assert.Equal(new[] { "turret", "barrel" }, rigs.Select(rig => rig.Joint));
Assert.Equal(new[] { "g0", "g1" }, rigs.Select(rig => rig.LeadMount));
}
// g1 is listed before g0 in the hull though its name sorts after it.
[Fact]
public void TheLeadMountOfAJointIsItsFirstWeaponInHullOrderWhateverTheNames()
{
var ship = Armed("j", "j");
ship.Visual.Joints.Add(Joint("j", null, (Up, -180f, 180f)));
var g1 = ship.Hull.Hardpoints.Single(hardpoint => hardpoint.Transform == "g1");
ship.Hull.Hardpoints.Remove(g1);
ship.Hull.Hardpoints.Insert(ship.Hull.Hardpoints.FindIndex(hardpoint => hardpoint.Transform == "g0"), g1);
var rig = Assert.Single(ShipModPlan.Build(ship.Hull, ship.Visual).Rigs);
Assert.Equal(("g1", "g1.muzzle"), (rig.LeadMount, rig.LeadMuzzle));
}
[Fact]
public void AnUndrivenParentJointIsPartOfTheChainRootFirst()
{
var ship = Armed("wrist");
ship.Visual.Joints.Add(Joint("arm", null, (Up, -90f, 90f)));
ship.Visual.Joints.Add(Joint("elbow", "arm", (Right, -45f, 45f)));
ship.Visual.Joints.Add(Joint("wrist", "elbow", (Up, -90f, 90f)));
var rig = Assert.Single(ShipModPlan.Build(ship.Hull, ship.Visual).Rigs);
Assert.Equal(new[] { "arm", "elbow", "wrist" }, rig.Chain);
}
[Fact]
public void AShipWithNoGunOnAJointHasNoRigs() =>
Assert.Empty(ShipModPlan.Build(Armed((string)null).Hull, Armed((string)null).Visual).Rigs);
}

View file

@ -67,6 +67,15 @@ public sealed class ShipSchemaPinTests
Assert.Equal(slot, KeyOf(typeof(ShipAnchor), members[slot]));
}
// ship_cc.py edits slots 2 to 4 of a ship and the first five slots of an anchor row, and carries every later slot (replace_visual
// by anchor Id). The rig lives in those later slots; their numbers are the contract that carry-through keeps.
[Fact]
public void TheRigLivesInTheSlotsPastTheOnesPythonEdits()
{
Assert.Equal(Integer("SCHEMATIC_LINES_SLOT") + 1, KeyOf(typeof(ShipAuthoring), nameof(ShipAuthoring.Joints)));
Assert.Equal(Strings("ANCHOR_MEMBERS").Length, KeyOf(typeof(ShipAnchor), nameof(ShipAnchor.Joint)));
}
[Fact]
public void PythonEnumNamesAreTheEnumsInValueOrder()
{

View file

@ -172,17 +172,41 @@ public sealed class ShipValidationTests
Add("anchors-null", s => s.Visual.Anchors = null, "anchors are required");
Add("anchor-null", s => s.Visual.Anchors.Add(null), "anchor IDs must be present and unique");
Add("anchor-id-null", s => s.Visual.Anchors[4].Id = null, "anchor IDs must be present and unique");
Add("anchor-id-blank", s => s.Visual.Anchors.Add(new ShipAnchor { Id = " ", Role = "articulation", ModelNodeId = "x" }), "anchor IDs must be present and unique");
Add("anchor-id-duplicate", s => s.Visual.Anchors.Add(new ShipAnchor { Id = "map", Role = "articulation", ModelNodeId = "x" }), "anchor IDs must be present and unique");
Add("anchor-id-blank", s => s.Visual.Anchors.Add(new ShipAnchor { Id = " ", Role = "weapon-muzzle", ModelNodeId = "x" }), "anchor IDs must be present and unique");
Add("anchor-id-duplicate", s => s.Visual.Anchors.Add(new ShipAnchor { Id = "map", Role = "weapon-muzzle", ModelNodeId = "x" }), "anchor IDs must be present and unique");
Add("anchor-node-null", s => s.Visual.Anchors[4].ModelNodeId = null, "needs a model node ID");
Add("anchor-node-blank", s => s.Visual.Anchors[4].ModelNodeId = " ", "needs a model node ID");
Add("anchor-node-shared", s => s.Visual.Anchors.Add(new ShipAnchor { Id = "other", Role = "articulation", ModelNodeId = "map" }), "claimed by more than one anchor");
Add("anchor-node-shared", s => s.Visual.Anchors.Add(new ShipAnchor { Id = "other", Role = "weapon-muzzle", ModelNodeId = "map" }), "claimed by more than one anchor");
foreach (var role in new[] { "map-icon", "hull-collider", "shield", "tractor" })
{
Add("role-missing-" + role, s => s.Visual.Anchors.RemoveAll(a => a.Role == role), $"exactly one {role} anchor is required");
Add("role-doubled-" + role, s => s.Visual.Anchors.Add(new ShipAnchor { Id = "extra", Role = role, ModelNodeId = "extra" }), $"exactly one {role} anchor is required");
}
void Joint(ShipParts s, string id, string parent, float[] axes, float[] min, float[] max) =>
s.Visual.Joints.Add(new ShipJoint { Id = id, Parent = parent, Axes = axes, Min = min, Max = max });
var yaw = new[] { 0f, 1f, 0f };
Add("joint-id-blank", s => Joint(s, " ", null, yaw, new[] { -1f }, new[] { 1f }), "joint IDs must be present and unique");
Add("joint-null", s => s.Visual.Joints.Add(null), "joint IDs must be present and unique");
Add("joint-id-duplicate", s => { Joint(s, "j", null, yaw, new[] { -1f }, new[] { 1f }); Joint(s, "j", null, yaw, new[] { -1f }, new[] { 1f }); }, "joint IDs must be present and unique");
Add("joint-id-is-an-anchor-node", s => Joint(s, "map", null, yaw, new[] { -1f }, new[] { 1f }), "is also an anchor's model node");
Add("joint-axes-length-four", s => Joint(s, "j", null, new[] { 0f, 1f, 0f, 0f }, new[] { -1f }, new[] { 1f }), "needs one or more degrees of freedom");
Add("joint-no-degrees-of-freedom", s => Joint(s, "j", null, new float[0], new float[0], new float[0]), "needs one or more degrees of freedom");
Add("joint-null-limits", s => Joint(s, "j", null, yaw, null, null), "needs one or more degrees of freedom");
Add("joint-max-count-differs", s => Joint(s, "j", null, yaw, new[] { -1f }, new[] { 1f, 2f }), "needs one or more degrees of freedom");
Add("joint-axis-not-unit", s => Joint(s, "j", null, new[] { 0f, 2f, 0f }, new[] { -1f }, new[] { 1f }), "must be a unit vector");
Add("joint-axis-not-finite", s => Joint(s, "j", null, new[] { 0f, float.NaN, 0f }, new[] { -1f }, new[] { 1f }), "axes and limits must be finite");
Add("joint-limit-not-finite", s => Joint(s, "j", null, yaw, new[] { -1f }, new[] { float.PositiveInfinity }), "axes and limits must be finite");
Add("joint-min-not-finite", s => Joint(s, "j", null, yaw, new[] { float.NaN }, new[] { 1f }), "axes and limits must be finite");
Add("joint-max-not-a-number", s => Joint(s, "j", null, yaw, new[] { -1f }, new[] { float.NaN }), "axes and limits must be finite");
Add("joint-min-above-max", s => Joint(s, "j", null, yaw, new[] { 10f }, new[] { 5f }), "must satisfy -180 <= Min <= Max <= 180");
Add("joint-max-181", s => Joint(s, "j", null, yaw, new[] { 0f }, new[] { 181f }), "must satisfy -180 <= Min <= Max <= 180");
Add("joint-min-minus-181", s => Joint(s, "j", null, yaw, new[] { -181f }, new[] { 0f }), "must satisfy -180 <= Min <= Max <= 180");
Add("joint-parent-dangling", s => Joint(s, "j", "ghost", yaw, new[] { -1f }, new[] { 1f }), "has an unknown parent joint");
Add("joint-cycle", s => { Joint(s, "a", "b", yaw, new[] { -1f }, new[] { 1f }); Joint(s, "b", "a", yaw, new[] { -1f }, new[] { 1f }); }, "is on a parent cycle");
Add("joint-on-a-thruster-mount", s => { Joint(s, "j", null, yaw, new[] { -1f }, new[] { 1f }); s.Visual.Anchors[4].Joint = "j"; }, "gimballed-thrusters");
Add("joint-on-a-radiator-mount", s => { Joint(s, "j", null, yaw, new[] { -1f }, new[] { 1f }); s.Visual.Anchors[4].Role = "radiator-mesh"; s.Visual.Anchors[4].Joint = "j"; s.Hull.Hardpoints[0].Type = HardpointType.Radiator; }, "gimballed-thrusters");
Add("joint-on-a-map-icon", s => { Joint(s, "j", null, yaw, new[] { -1f }, new[] { 1f }); s.Visual.Anchors[0].Joint = "j"; }, "may not name a joint");
Add("anchor-role-unknown", s => s.Visual.Anchors.Add(new ShipAnchor { Id = "x", Role = "engine", ModelNodeId = "x" }), "has unknown role 'engine'");
Add("anchor-role-null", s => s.Visual.Anchors.Add(new ShipAnchor { Id = "x", Role = null, ModelNodeId = "x" }), "has unknown role ''");
Add("anchor-role-cased", s => s.Visual.Anchors[0].Role = "Map-Icon", "has unknown role 'Map-Icon'");

View file

@ -0,0 +1,423 @@
using System;
using System.Collections.Generic;
using CultMath;
using Xunit;
namespace Aetheria.Shared.Tests;
// ThrustAllocator on synthetic columns. A column is (starboard m/s^2, forward m/s^2, clockwise yaw rad/s) per unit
// throttle; the fixtures are written in deg/s the way the probes measured them (map TA3, TA12).
public class ThrustAllocatorTests
{
const float Deg = MathF.PI / 180f;
// The drive carries a constant throttle of about 1.2e-4 (1.6e-4 on the halved hull) from the first touch of Turn, the
// optimum of the ridge against the cost rows; recruitment past the onset is 1e-3 and more within .005 of Turn.
const float LeakBound = 3e-4f;
static float3 Col(float starboard, float forward, float yawDeg) => new(starboard, forward, yawDeg * Deg);
// TA3, the Duel Longinus: two mismatched drives (0, 1) and two Talarias (2 clockwise, 3 counter-clockwise).
static float3[] Duel() => new[]
{
Col(0, 53.94f, 49.24f), Col(0, 61.19f, -55.86f), Col(29.08f, 0, 166.26f), Col(-21.80f, 0, -124.63f),
};
// The clockwise Talaria lost.
static float3[] DamagedDuel() => new[]
{
Col(0, 53.94f, 49.24f), Col(0, 61.19f, -55.86f), default, Col(-21.80f, 0, -124.63f),
};
// TA12's symmetric hull: mains, fore and aft laterals in torque-free pairs, a bow thruster.
static float3[] Symmetric() => new[]
{
Col(0, 50, 20), Col(0, 50, -20), Col(20, 0, 80), Col(-20, 0, -80), Col(20, 0, -60), Col(-20, 0, 60), Col(0, -30, 0),
};
// The hull's half-axis extremes, from the definition: the sum of a row's positive entries, or of the negated
// negative ones. Axis 0 starboard, 1 forward, 2 clockwise yaw.
static (float plus, float minus) Extremes(float3[] columns, int axis)
{
float plus = 0, minus = 0;
foreach (var c in columns)
{
var v = axis == 0 ? c.x : axis == 1 ? c.y : c.z;
if (v > 0) plus += v; else minus -= v;
}
return (plus, minus);
}
static float3 Net(float3[] columns, float[] throttle)
{
float3 net = default;
for (var i = 0; i < columns.Length; i++) net += columns[i] * throttle[i];
return net;
}
static float[] Solve(ThrustAllocator allocator, float3[] columns, float moveX, float moveY, float turn)
{
var throttle = new float[columns.Length];
allocator.Allocate(columns, new float2(moveX, moveY), turn, throttle);
return throttle;
}
static float[] Solve(float3[] columns, float moveX, float moveY, float turn) => Solve(new ThrustAllocator(), columns, moveX, moveY, turn);
static float YawDeg(float3[] columns, float[] throttle) => Net(columns, throttle).z / Deg;
[Fact]
public void AHoldIsExactWithMismatchedDrives()
{
var duel = Duel();
var throttle = Solve(duel, 0, 1, 0);
var clockwise = Extremes(duel, 2).plus;
var net = Net(duel, throttle);
Assert.True(MathF.Abs(net.z) <= 1e-5f * clockwise, $"yaw {net.z / Deg} deg/s");
Assert.True(net.y >= .99f * Extremes(duel, 1).plus, $"forward {net.y}");
}
[Theory]
[InlineData(0)]
[InlineData(1)]
public void ALostDriveIsBalancedByWhatIsLeft(int zeroed)
{
var columns = Duel();
var extreme = Extremes(columns, 2).plus;
columns[zeroed] = default;
var throttle = Solve(columns, 0, 1, 0);
var net = Net(columns, throttle);
Assert.True(MathF.Abs(net.z) <= 1e-5f * extreme, $"yaw {net.z / Deg} deg/s");
Assert.Equal(0f, throttle[zeroed]);
Assert.True(net.y > 0, $"forward {net.y}");
}
[Theory]
[InlineData(1f)]
[InlineData(.5f)]
[InlineData(-.5f)]
[InlineData(-1f)]
public void ATurnIsThatFractionOfTheBoxExtreme(float turn)
{
var duel = Duel();
var (plus, minus) = Extremes(duel, 2);
var expected = turn * (turn > 0 ? plus : minus);
var net = Net(duel, Solve(duel, 0, 0, turn));
Assert.True(MathF.Abs(net.z - expected) <= 1e-4f * MathF.Abs(expected), $"yaw {net.z / Deg} expected {expected / Deg}");
}
[Fact]
public void AttitudeServesFirstAndTheOnsetIsTheColumnsRatio()
{
var duel = Duel();
// The onset is the attitude thruster's yaw over the hull's extreme in that direction.
var clockwiseOnset = duel[2].z / Extremes(duel, 2).plus;
var counterOnset = -duel[3].z / Extremes(duel, 2).minus;
Assert.InRange(clockwiseOnset, .7714f, .7716f);
Assert.InRange(counterOnset, .6904f, .6906f);
var allocator = new ThrustAllocator();
for (var step = 0; step <= 1000; step++)
{
var turn = step * .001f;
var drive = Solve(allocator, duel, 0, 0, turn)[0];
if (turn <= clockwiseOnset - .005f) Assert.True(drive <= LeakBound, $"clockwise turn {turn}: drive {drive}");
if (turn >= clockwiseOnset + .005f) Assert.True(drive > 1e-3f, $"clockwise turn {turn}: drive {drive}");
}
allocator = new ThrustAllocator();
for (var step = 0; step <= 1000; step++)
{
var turn = step * .001f;
var drive = Solve(allocator, duel, 0, 0, -turn)[1];
if (turn <= counterOnset - .005f) Assert.True(drive <= LeakBound, $"counter-clockwise turn {turn}: drive {drive}");
if (turn >= counterOnset + .005f) Assert.True(drive > 1e-3f, $"counter-clockwise turn {turn}: drive {drive}");
}
}
[Fact]
public void TheOnsetMovesWithTheColumns()
{
// Clockwise Talaria lost: the drive serves a clockwise turn from the first touch.
var damaged = DamagedDuel();
var small = Solve(damaged, 0, 0, .01f);
Assert.True(small[0] > 0, $"drive {small[0]}");
Assert.True(MathF.Abs(YawDeg(damaged, small) - .01f * 49.24f) <= .01f * 49.24f * 1e-3f, $"yaw {YawDeg(damaged, small)}");
var full = Solve(damaged, 0, 0, 1f);
Assert.True(MathF.Abs(YawDeg(damaged, full) - 49.24f) <= 49.24f * 1e-3f, $"yaw {YawDeg(damaged, full)}");
// Clockwise Talaria halved: the onset is its new share of the clockwise extreme.
var halved = Duel();
halved[2] = halved[2] * .5f;
var onset = halved[2].z / Extremes(halved, 2).plus;
Assert.InRange(onset, .627f, .629f);
var allocator = new ThrustAllocator();
for (var step = 0; step <= 1000; step++)
{
var turn = step * .001f;
var drive = Solve(allocator, halved, 0, 0, turn)[0];
if (turn <= onset - .005f) Assert.True(drive <= LeakBound, $"turn {turn}: drive {drive}");
if (turn >= onset + .005f) Assert.True(drive > 1e-3f, $"turn {turn}: drive {drive}");
}
}
[Fact]
public void EveryThrottleIsContinuousInTurn()
{
foreach (var columns in new[] { Duel(), DamagedDuel(), Symmetric() })
{
var allocator = new ThrustAllocator();
var previous = Solve(allocator, columns, 0, 0, -1f);
for (var step = -999; step <= 1000; step++)
{
var current = Solve(allocator, columns, 0, 0, step * .001f);
for (var i = 0; i < columns.Length; i++)
Assert.True(MathF.Abs(current[i] - previous[i]) <= .02f, $"turn {step * .001f}: throttle {i} {previous[i]} -> {current[i]}");
previous = current;
}
}
}
[Fact]
public void PureTorqueNeedsNoTranslation()
{
var hull = Symmetric();
var allocator = new ThrustAllocator();
var starboard = Extremes(hull, 0).plus;
var forward = Extremes(hull, 1).plus;
for (var step = -87; step <= 87; step++)
{
var net = Net(hull, Solve(allocator, hull, 0, 0, step * .01f));
Assert.True(MathF.Abs(net.x) <= 1e-3f * starboard, $"turn {step * .01f}: starboard {net.x}");
Assert.True(MathF.Abs(net.y) <= 1e-3f * forward, $"turn {step * .01f}: forward {net.y}");
}
var strafe = Net(hull, Solve(hull, 1, 0, 0));
Assert.True(strafe.x >= .9f * starboard, $"strafe {strafe.x} of {starboard}");
Assert.True(MathF.Abs(strafe.z) <= 1e-3f * Extremes(hull, 2).plus, $"yaw {strafe.z / Deg}");
}
[Fact]
public void TurnComesBeforeTranslation()
{
var duel = Duel();
var throttle = Solve(duel, 0, 1, 1f);
var net = Net(duel, throttle);
var extreme = Extremes(duel, 2).plus;
Assert.True(MathF.Abs(net.z - extreme) <= 1e-4f * extreme, $"yaw {net.z / Deg} of {extreme / Deg}");
Assert.True(throttle[1] < .01f, $"counter-turning drive {throttle[1]}");
}
[Fact]
public void MovementIsThatFractionOfTheHalfAxis()
{
// A torque-free strafe pair of unequal strength and a torque-free main.
var columns = new[] { Col(30, 0, 0), Col(-20, 0, 0), Col(0, 60, 0) };
const float yaw = 1e-4f;
var right = Net(columns, Solve(columns, .5f, 0, 0));
Assert.True(MathF.Abs(right.x - 15f) <= 15e-3f && MathF.Abs(right.z) <= yaw, $"right {right.x}");
var left = Net(columns, Solve(columns, -.5f, 0, 0));
Assert.True(MathF.Abs(left.x + 10f) <= 10e-3f && MathF.Abs(left.z) <= yaw, $"left {left.x}");
var ahead = Net(columns, Solve(columns, 0, .5f, 0));
Assert.True(MathF.Abs(ahead.y - 30f) <= 30e-3f && MathF.Abs(ahead.z) <= yaw, $"ahead {ahead.y}");
}
[Fact]
public void IntentBeyondOneIsClamped()
{
var duel = Duel();
Assert.Equal(Solve(duel, 0, 0, 1f), Solve(duel, 0, 0, 3f));
Assert.Equal(Solve(duel, 1, -1, 0), Solve(duel, 3, -3, 0));
Assert.Equal(Solve(duel, 0, 0, -1f), Solve(duel, 0, 0, -3f));
}
[Fact]
public void NothingAskedNothingFired()
{
Assert.All(Solve(Duel(), 0, 0, 0), t => Assert.Equal(0f, t));
Assert.All(Solve(new float3[4], 1, 1, 1), t => Assert.Equal(0f, t));
new ThrustAllocator().Allocate(ReadOnlySpan<float3>.Empty, new float2(1, 1), 1, Span<float>.Empty);
var withNaN = Duel();
withNaN[2] = new float3(float.NaN, 0, 0);
Assert.All(Solve(withNaN, 0, 1, 1), t => Assert.Equal(0f, t));
var nanYaw = Duel();
nanYaw[0] = new float3(0, 1, float.NaN);
Assert.All(Solve(nanYaw, 0, 1, 0), t => Assert.Equal(0f, t));
// A bad column zeroes the answer even after a good call left throttles in the warm start and in the caller's buffer.
var allocator = new ThrustAllocator();
var buffer = new float[4];
allocator.Allocate(Duel(), new float2(0, 1), .5f, buffer);
Assert.Contains(buffer, t => t > .1f);
allocator.Allocate(withNaN, new float2(0, 1), .5f, buffer);
Assert.All(buffer, t => Assert.Equal(0f, t));
}
[Fact]
public void TheStartDoesNotChangeTheAnswer()
{
var duel = Duel();
var cold = Solve(duel, .3f, .8f, .6f);
foreach (var previous in new[] { (1f, 1f, 1f), (-1f, -.5f, -1f), (0f, 0f, 0f) })
{
var allocator = new ThrustAllocator();
Solve(allocator, duel, previous.Item1, previous.Item2, previous.Item3);
var warm = Solve(allocator, duel, .3f, .8f, .6f);
for (var i = 0; i < duel.Length; i++) Assert.True(MathF.Abs(warm[i] - cold[i]) <= 1e-5f, $"previous {previous}: throttle {i} {cold[i]} vs {warm[i]}");
}
}
[Fact]
public void EqualThrustersShareTheDemand()
{
var columns = new[] { Col(0, 50, 0), Col(0, 50, 0) };
var throttle = Solve(columns, 0, .5f, 0);
Assert.True(MathF.Abs(throttle[0] - throttle[1]) <= 1e-4f, $"{throttle[0]} vs {throttle[1]}");
Assert.True(throttle[0] > .1f);
}
[Fact]
public void AColumnCountChangeResets()
{
var four = Duel();
var three = new[] { four[0], four[2], four[3] };
var allocator = new ThrustAllocator();
var steps = new List<(float3[] columns, float x, float y, float turn)>
{
(four, .2f, .9f, -.7f), (three, -.4f, 1f, .9f), (four, .2f, .9f, -.7f),
};
foreach (var (columns, x, y, turn) in steps)
{
var warm = Solve(allocator, columns, x, y, turn);
var fresh = Solve(columns, x, y, turn);
for (var i = 0; i < columns.Length; i++) Assert.True(MathF.Abs(warm[i] - fresh[i]) <= 1e-5f, $"{columns.Length} columns: throttle {i}");
}
}
[Fact]
public void AShipWithOneThrusterIsFlownFromItsFirstCall()
{
var throttle = Solve(new[] { Col(0, 50, 0) }, 0, 1, 0);
Assert.True(throttle[0] > .99f, $"{throttle[0]}");
}
[Fact]
public void ChangedColumnsOfTheSameCountLeaveNothingBehind()
{
// Thruster 1 first strafes, then only pushes forward: the strafe row it left must not shape the second answer.
var strafing = new[] { Col(0, 60, 0), Col(30, 0, 0), Col(-20, 0, 0) };
var forwardOnly = new[] { Col(0, 60, 0), Col(0, 40, 0), Col(0, -20, 0) };
var allocator = new ThrustAllocator();
Solve(allocator, strafing, 1, 1, .5f);
var warm = Solve(allocator, forwardOnly, 0, 1, 0);
var fresh = Solve(forwardOnly, 0, 1, 0);
for (var i = 0; i < warm.Length; i++) Assert.True(MathF.Abs(warm[i] - fresh[i]) <= 1e-5f, $"throttle {i}: {warm[i]} vs {fresh[i]}");
Assert.True(warm[1] > .9f, $"{warm[1]}");
}
[Fact]
public void AtTheIterationCapTheIterateIsKept()
{
// 128 torque-free forward thrusters from a cold start: the active set frees about one throttle per iteration, so
// the solver stops at its iteration cap (measured: IterationLimit at 100). TA-R4 keeps the iterate it reached,
// which already carries a share of the forward demand; a call that zeroed it would give nothing.
var forward = new float3[128];
for (var i = 0; i < forward.Length; i++) forward[i] = Col(0, 30f + i % 7, 0);
var throttle = Solve(forward, 0, 1, 0);
var reached = Net(forward, throttle).y;
var extreme = Extremes(forward, 1).plus;
Assert.True(reached > .1f * extreme, $"{reached} of {extreme}");
}
[Fact]
public void AFullTurnAgainstAFullReverseKeepsItsWholeYaw()
{
// The only clockwise actuator also pushes forward and the only reverse actuator turns the other way. Delivering
// a full turn against a full reverse leaves a forward error of 2, the top of TA-R2's error box: an error bound
// below 2 would take yaw back to pay for it, and turn-authority-full says the turn is whole.
foreach (var (columns, x, y) in new[]
{
(new[] { Col(0, 50, 100), Col(0, -50, -100) }, 0f, -1f),
(new[] { Col(50, 0, 100), Col(-50, 0, -100) }, -1f, 0f),
(new[] { Col(0, -50, 100), Col(0, 50, -100) }, 0f, 1f),
(new[] { Col(-50, 0, 100), Col(50, 0, -100) }, 1f, 0f),
})
{
var yaw = Net(columns, Solve(columns, x, y, 1)).z;
var extreme = Extremes(columns, 2).plus;
Assert.True(MathF.Abs(yaw - extreme) <= 1e-4f * extreme, $"move ({x},{y}): yaw {yaw / Deg} of {extreme / Deg}");
}
}
// Forty thrusters of 20..60 m/s^2 on random half-axes with random yaw, the shape of a hull far larger than any demo
// ship. Deterministic from the seed.
static float3[] LargeHull(int n, int seed)
{
var rng = new System.Random(seed);
var columns = new float3[n];
for (var i = 0; i < n; i++)
{
var a = 20f + 40f * (float)rng.NextDouble();
var yaw = (float)(rng.NextDouble() * 2 - 1) * 120f;
var dir = rng.Next(10);
columns[i] = dir < 4 ? Col(0, a, yaw) : dir < 6 ? Col(0, -a, yaw) : dir < 8 ? Col(a, 0, yaw) : Col(-a, 0, yaw);
}
return columns;
}
[Fact]
public void NothingAskedAfterAnIterationCapCallFiresNothing()
{
// On this hull the warm solve of a zero-intent call needs more than the solver's 100 iterations, and the iterate it
// stopped at fired throttles up to 1.0 with nothing asked. Whether nothing is asked is decided from the intent, not
// by how far the solver gets.
var histories = new[]
{
(Seed: 9039, History: new[] { (0.0112729073f, -0.170811713f, 0.809294581f), (-0.474286854f, 0.703138232f, 0f), (0.294080615f, 0.934491992f, -0.776120305f) }),
(Seed: 9079, History: new[] { (0.607828975f, 1f, 0.202640772f), (-0.620587587f, 0.0162956715f, -0.898228765f), (0.0739500523f, 1f, -0.903907537f) }),
};
foreach (var (seed, history) in histories)
{
var hull = LargeHull(40, seed);
var allocator = new ThrustAllocator();
foreach (var (x, y, turn) in history) Solve(allocator, hull, x, y, turn);
Assert.All(Solve(allocator, hull, 0, 0, 0), t => Assert.Equal(0f, t));
Assert.All(Solve(allocator, hull, 0, 0, 0), t => Assert.Equal(0f, t));
}
}
[Fact]
public void ASmallIntentIsStillAnsweredWhateverTheColumnScale()
{
// Zero is a fact about the intent alone: an intent of 1e-3 of the half-axis is served at any scale of thrust.
foreach (var scale in new[] { 1e-3f, 1f, 1e3f })
{
var hull = Duel();
for (var i = 0; i < hull.Length; i++) hull[i] *= scale;
var extreme = Extremes(hull, 2).plus;
var yaw = Net(hull, Solve(hull, 0, 0, 1e-3f)).z;
Assert.True(yaw > .5e-3f * extreme, $"scale {scale}: yaw {yaw} of {extreme}");
}
}
[Fact]
public void NothingAskedAfterACallFiresNothing()
{
// The warm start left by a call must not leak into a hold of zero intent: exactly zero, not solver residue.
foreach (var hull in new[] { Duel(), Symmetric() })
foreach (var previous in new[] { (.5f, .5f, .5f), (1f, 1f, 1f), (-.3f, .8f, .6f), (0f, 0f, -1f), (0f, 1f, 0f) })
{
var allocator = new ThrustAllocator();
Solve(allocator, hull, previous.Item1, previous.Item2, previous.Item3);
Assert.All(Solve(allocator, hull, 0, 0, 0), t => Assert.Equal(0f, t));
}
}
[Fact]
public void TheDriveCarriesTheLinearCostsLeakBeforeTheOnset()
{
// The error variables are paid linearly toward zero (TA-R2): that cost, against the ridge, holds the drive at a
// small constant throttle before the onset, 1.30e-4 at turn .5 and 1.14e-4 at turn -.5 on the Duel (a cost row
// pulling the errors the other way gives 1.06e-4 and 0.93e-4). The bounds are the measured value less 8%.
var duel = Duel();
Assert.InRange(Solve(duel, 0, 0, .5f)[0], 1.2e-4f, LeakBound);
Assert.InRange(Solve(duel, 0, 0, -.5f)[1], 1.05e-4f, LeakBound);
}
}