Merge origin/master into consumable-supply

This commit is contained in:
Meta Vens 2026-10-10 14:05:56 +02:00
commit cf6503bf4e
49 changed files with 3229 additions and 99 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

@ -475,7 +475,7 @@ public sealed partial class FireControlCut124Tests : IDisposable
public void AGrazingBlastAtAShippedHullsFarthestCornerLands(string hullName)
{
Shape shape;
var cache = OpenReadOnlyRealCatalog(Path.Combine(FindRepoRoot(), "GameData", "Aetheria.cc"), out _);
var cache = OpenReadOnlyRealCatalog(TestCatalog.Repo, out _);
try { shape = cache.GetByName<HullData>(hullName).Shape; }
finally { cache.Dispose(); }
@ -2573,9 +2573,7 @@ public sealed partial class FireControlCut124Tests : IDisposable
private static CultCache OpenReadOnlyRealCatalog(string catalogPath, out SingleFileMessagePackBackingStore store)
{
var registry = CultDocumentRegistry.ForTypes(typeof(ItemData).Assembly.GetTypes()
.Where(t => t is { IsAbstract: false, IsInterface: false })
.Where(t => t.GetCustomAttribute<CultDocumentAttribute>() != null));
var registry = TestCatalog.Registry();
var cache = new CultCache(registry);
store = new SingleFileMessagePackBackingStore(catalogPath, true);
cache.AddBackingStore(store, AetheriaStores.CatalogTypes);
@ -2588,7 +2586,7 @@ public sealed partial class FireControlCut124Tests : IDisposable
[Fact]
public void ShippedCatalogIsNeutralOnBlastRadiusAndFuse()
{
var gameData = Path.Combine(FindRepoRoot(), "GameData", "Aetheria.cc");
var gameData = TestCatalog.Repo;
var cache = OpenReadOnlyRealCatalog(gameData, out var store);
try
{
@ -2621,7 +2619,7 @@ public sealed partial class FireControlCut124Tests : IDisposable
[Fact]
public void WeaponFuseAndBlastRadiusRoundTripThroughAWrittenCatalog()
{
var src = Path.Combine(FindRepoRoot(), "GameData", "Aetheria.cc");
var src = TestCatalog.Repo;
var fuseValues = new WeaponFuse?[] { null, WeaponFuse.Contact, WeaponFuse.Proximity, WeaponFuse.Delayed };
var radiusValues = new float?[] { null, 0f, 12.5f };
@ -2636,9 +2634,7 @@ public sealed partial class FireControlCut124Tests : IDisposable
var cache = OpenReadOnlyRealCatalog(tmp, out _);
cache.Dispose();
}
var writeCache = new CultCache(CultDocumentRegistry.ForTypes(typeof(ItemData).Assembly.GetTypes()
.Where(t => t is { IsAbstract: false, IsInterface: false })
.Where(t => t.GetCustomAttribute<CultDocumentAttribute>() != null)));
var writeCache = new CultCache(TestCatalog.Registry());
writeCache.AddBackingStore(new SingleFileMessagePackBackingStore(tmp, false), AetheriaStores.CatalogTypes);
var w = writeCache.GetAll<WeaponItemData>().OrderBy(x => x.Name).First();
w.Fuse = fuse;

View file

@ -200,7 +200,7 @@ public sealed class FireControlCut7Tests : IDisposable
[Fact]
public void ShippedCatalogOpensAndGeneratesAnArmedHull()
{
var gameData = Path.Combine(FindRepoRoot(), "GameData", "Aetheria.cc");
var gameData = TestCatalog.Repo;
using var cache = OpenReadOnlyRealCatalog(gameData);
// Force every EquippableItemData -- WeaponItemData included, the type the broken merge could not
@ -255,9 +255,7 @@ public sealed class FireControlCut7Tests : IDisposable
// validation loop -- without the test assembly's own fixture type poisoning it.
private static CultCache OpenReadOnlyRealCatalog(string catalogPath)
{
var registry = CultDocumentRegistry.ForTypes(typeof(ItemData).Assembly.GetTypes()
.Where(t => t is { IsAbstract: false, IsInterface: false })
.Where(t => t.GetCustomAttribute<CultDocumentAttribute>() != null));
var registry = TestCatalog.Registry();
var cache = new CultCache(registry);
try
{

View file

@ -761,9 +761,7 @@ public sealed partial class MiningCut3Tests : IDisposable
// would otherwise be demanded of a catalog that was never authored with it.
private static CultCache OpenShippedCatalogCopy(string catalogPath, string runPath)
{
var registry = CultDocumentRegistry.ForTypes(typeof(ItemData).Assembly.GetTypes()
.Where(t => t is { IsAbstract: false, IsInterface: false })
.Where(t => t.GetCustomAttributes(typeof(CultDocumentAttribute), false).Length > 0));
var registry = TestCatalog.Registry();
var cache = new CultCache(registry);
cache.AddBackingStore(new GameCult.Caching.MessagePack.SingleFileMessagePackBackingStore(catalogPath, false), AetheriaStores.CatalogTypes);
cache.AddBackingStore(new GameCult.Caching.MessagePack.SingleFileMessagePackBackingStore(runPath), AetheriaStores.RunTypes);
@ -776,7 +774,7 @@ public sealed partial class MiningCut3Tests : IDisposable
[Fact]
public void GenerationChoosesTheKindByTheSameFunction()
{
var shipped = Path.Combine(RestoredHullsTests.FindRepoRoot(), "GameData", "Aetheria.cc");
var shipped = TestCatalog.Repo;
var belts = 0;
for (uint seed = 1; seed <= 25 && belts < 3; seed++)
{
@ -1043,7 +1041,7 @@ public sealed partial class MiningCut3Tests : IDisposable
var dir = Path.Combine(_root, "shipped");
Directory.CreateDirectory(dir);
var catalog = Path.Combine(dir, "Aetheria.cc");
File.Copy(Path.Combine(RestoredHullsTests.FindRepoRoot(), "GameData", "Aetheria.cc"), catalog);
File.Copy(TestCatalog.Repo, catalog);
using var cache = OpenShippedCatalogCopy(catalog, Path.Combine(dir, "run.cc"));
Assert.Contains(cache.GetAll<FieldKindData>(), kind => kind.GenerationWeight > 0f);
}

View file

@ -25,9 +25,7 @@ public sealed class PiratesFactionCommandTests : IDisposable
// AetherDb.Open composes the process-wide registry, which in this test host also sees this assembly's TestCatalogGlobal
// (see FireControlCut7Tests). So the copy is stripped through a registry scoped to the shipped assembly and then given
// the record that registry's shared sibling demands, as AetheriaStoresTests does.
var registry = CultDocumentRegistry.ForTypes(typeof(ItemData).Assembly.GetTypes()
.Where(t => t is { IsAbstract: false, IsInterface: false })
.Where(t => t.GetCustomAttribute<CultDocumentAttribute>() != null));
var registry = TestCatalog.Registry();
using (var cache = new CultCache(registry))
{
cache.AddBackingStore(new SingleFileMessagePackBackingStore(CatalogPath), AetheriaStores.CatalogTypes);

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

@ -38,9 +38,7 @@ public sealed class RestoredHullsTests
// real catalog's validation the way the shared, AppDomain-scanning CultCache() default would.
private static CultCache OpenReadOnlyRealCatalog(string catalogPath)
{
var registry = CultDocumentRegistry.ForTypes(typeof(ItemData).Assembly.GetTypes()
.Where(t => t is { IsAbstract: false, IsInterface: false })
.Where(t => t.GetCustomAttribute<CultDocumentAttribute>() != null));
var registry = TestCatalog.Registry();
var cache = new CultCache(registry);
cache.AddBackingStore(new SingleFileMessagePackBackingStore(catalogPath, true), AetheriaStores.CatalogTypes);
return cache;
@ -54,7 +52,7 @@ public sealed class RestoredHullsTests
throw new DirectoryNotFoundException("Run from inside the Aetheria repository.");
}
internal static CultCache OpenCatalog() => OpenReadOnlyRealCatalog(Path.Combine(FindRepoRoot(), "GameData", "Aetheria.cc"));
internal static CultCache OpenCatalog() => OpenReadOnlyRealCatalog(TestCatalog.Repo);
// Shared tutorial-galaxy construction settings (Assets/Resources/Settings.asset's own values), factored out
// so every test that needs a real tutorial Galaxy -- not just EntranceZoneAlwaysGetsADockedStationAcrossSeeds
@ -140,7 +138,7 @@ public sealed class RestoredHullsTests
var scratchRun = Path.Combine(Path.GetTempPath(), $"aetheria-nolagrange-scan-{Guid.NewGuid():N}.cc");
try
{
using var cache = OpenReadOnlyRealCatalogWithScratchRun(Path.Combine(FindRepoRoot(), "GameData", "Aetheria.cc"), scratchRun);
using var cache = OpenReadOnlyRealCatalogWithScratchRun(TestCatalog.Repo, scratchRun);
return ScanForNoLagrangeCandidateZone(cache);
}
finally
@ -170,9 +168,7 @@ public sealed class RestoredHullsTests
// catalog-only cache has no home for them. A scratch run file, deleted after the seed that used it.
private static CultCache OpenReadOnlyRealCatalogWithScratchRun(string catalogPath, string runPath)
{
var registry = CultDocumentRegistry.ForTypes(typeof(ItemData).Assembly.GetTypes()
.Where(t => t is { IsAbstract: false, IsInterface: false })
.Where(t => t.GetCustomAttribute<CultDocumentAttribute>() != null));
var registry = TestCatalog.Registry();
var cache = new CultCache(registry);
cache.AddBackingStore(new SingleFileMessagePackBackingStore(catalogPath, true), AetheriaStores.CatalogTypes);
cache.AddBackingStore(new SingleFileMessagePackBackingStore(runPath), AetheriaStores.RunTypes);
@ -357,7 +353,7 @@ public sealed class RestoredHullsTests
var tutorialSettings = TutorialGalaxySettings();
var background = TutorialBackgroundSettings();
var names = TutorialNameSettings();
var gameData = Path.Combine(FindRepoRoot(), "GameData", "Aetheria.cc");
var gameData = TestCatalog.Repo;
var sawGenuineLagrangeOrbit = false;
for (uint seed = 1; seed <= 25; seed++)
{
@ -398,7 +394,7 @@ public sealed class RestoredHullsTests
var tutorialSettings = TutorialGalaxySettings();
var background = TutorialBackgroundSettings();
var names = TutorialNameSettings();
var gameData = Path.Combine(FindRepoRoot(), "GameData", "Aetheria.cc");
var gameData = TestCatalog.Repo;
var sawGenuineCandidate = false;
for (uint seed = 1; seed <= 25; seed++)
{
@ -439,7 +435,7 @@ public sealed class RestoredHullsTests
[Fact]
public void ThrowReachableWithAuthoredSettings()
{
var gameData = Path.Combine(FindRepoRoot(), "GameData", "Aetheria.cc");
var gameData = TestCatalog.Repo;
var scratchRun = Path.Combine(Path.GetTempPath(), $"aetheria-entrance-throw-{Guid.NewGuid():N}.cc");
try
{
@ -473,7 +469,7 @@ public sealed class RestoredHullsTests
[Fact]
public void MultiRootEntranceStationOrbitsAreAlwaysParentedWithPositiveDistance()
{
var gameData = Path.Combine(FindRepoRoot(), "GameData", "Aetheria.cc");
var gameData = TestCatalog.Repo;
var scratchRun = Path.Combine(Path.GetTempPath(), $"aetheria-entrance-multiroot-{Guid.NewGuid():N}.cc");
try
{
@ -524,7 +520,7 @@ public sealed class RestoredHullsTests
var tutorialSettings = TutorialGalaxySettings();
var background = TutorialBackgroundSettings();
var names = TutorialNameSettings();
var gameData = Path.Combine(FindRepoRoot(), "GameData", "Aetheria.cc");
var gameData = TestCatalog.Repo;
var checkedAny = false;
for (uint seed = 1; seed <= 25; seed++)
@ -723,7 +719,7 @@ public sealed class RestoredHullsTests
[Fact]
public void TutorialEntranceWithNoLagrangeCandidateStillSeatsAStationWithFiniteNearbyTurrets()
{
var gameData = Path.Combine(FindRepoRoot(), "GameData", "Aetheria.cc");
var gameData = TestCatalog.Repo;
var scratchRun = Path.Combine(Path.GetTempPath(), $"aetheria-entrance-widened-{Guid.NewGuid():N}.cc");
try
{
@ -772,7 +768,7 @@ public sealed class RestoredHullsTests
[Fact]
public void EntranceOverrideDoesNotLeakToOtherTutorialZonesOrNonTutorialGames()
{
var gameData = Path.Combine(FindRepoRoot(), "GameData", "Aetheria.cc");
var gameData = TestCatalog.Repo;
var scratchRun = Path.Combine(Path.GetTempPath(), $"aetheria-entrance-leak-{Guid.NewGuid():N}.cc");
try
{
@ -813,7 +809,7 @@ public sealed class RestoredHullsTests
[Fact]
public void ForcedTutorialEntranceStationDoesNotInflateEnemyCount()
{
var gameData = Path.Combine(FindRepoRoot(), "GameData", "Aetheria.cc");
var gameData = TestCatalog.Repo;
var scratchRun = Path.Combine(Path.GetTempPath(), $"aetheria-entrance-enemycount-{Guid.NewGuid():N}.cc");
try
{
@ -895,7 +891,7 @@ public sealed class RestoredHullsTests
[Fact]
public void WideningDoesNotLeakToANonEntranceNoLagrangeZoneThatRollsAStation()
{
var gameData = Path.Combine(FindRepoRoot(), "GameData", "Aetheria.cc");
var gameData = TestCatalog.Repo;
var scratchRun = Path.Combine(Path.GetTempPath(), $"aetheria-widen-leak-{Guid.NewGuid():N}.cc");
try
{

View file

@ -30,7 +30,7 @@ public sealed class RolesBackfillCommandTests : IDisposable
{
Directory.CreateDirectory(Path.Combine(_root, "GameData"));
File.Copy(Path.Combine(AetherDb.FindRoot(), "GameData", "Aetheria.cc"), CatalogPath);
using var cache = new CultCache(ScopedRegistry());
using var cache = new CultCache(TestCatalog.Registry());
cache.AddBackingStore(new SingleFileMessagePackBackingStore(CatalogPath), AetheriaStores.CatalogTypes);
var products = cache.GetAll<FactionProductData>().ToArray();
foreach (var design in cache.GetAll<EquippableItemData>().Where(d => Flattened.Contains(d.Name) || Unnamed.Any(u => u.Design == d.Name)))
@ -38,15 +38,11 @@ public sealed class RolesBackfillCommandTests : IDisposable
}
// A registry scoped to the shipped assembly, so this test assembly's own documents never reach the real catalog.
private static CultDocumentRegistry ScopedRegistry() => CultDocumentRegistry.ForTypes(typeof(ItemData).Assembly.GetTypes()
.Where(t => t is { IsAbstract: false, IsInterface: false })
.Where(t => t.GetCustomAttribute<CultDocumentAttribute>() != null));
// Puts the named designs back to the state they shipped in before the backfill, through a registry scoped to the shipped
// assembly (as PiratesFactionCommandTests strips its faction).
private void Reset(bool flattened, bool unnamed)
{
using var cache = new CultCache(ScopedRegistry());
using var cache = new CultCache(TestCatalog.Registry());
cache.AddBackingStore(new SingleFileMessagePackBackingStore(CatalogPath), AetheriaStores.CatalogTypes);
var designs = cache.GetAll<EquippableItemData>().ToArray();
var products = cache.GetAll<FactionProductData>().ToArray();

View file

@ -18,7 +18,7 @@ using float3 = CultMath.float3;
// RunStart owns what a new run starts with, and Zone.Admit is the one admission into a zone (docs/scenarios-cut.md,
// 2.2 and R). Every test stages into a real arena: the entrance zone of a prelude galaxy at a fixed seed, built from a
// scratch copy of the shipped catalog and the authored settings (Assets/Resources/Settings.asset).
// scratch copy of the catalog the game boots (TestCatalog) and the authored settings (Assets/Resources/Settings.asset).
public sealed partial class RunStartTests : IDisposable
{
private const uint GalaxySeed = 1;
@ -38,11 +38,11 @@ public sealed partial class RunStartTests : IDisposable
var repo = FindRepoRoot();
Directory.CreateDirectory(_root);
var catalog = Path.Combine(_root, "Aetheria.cc");
File.Copy(Path.Combine(repo, "GameData", "Aetheria.cc"), catalog);
File.Copy(TestCatalog.Repo, catalog);
// A registry scoped to the shipped assembly's own [CultDocument] types, as RestoredHullsTests composes it, so
// this test assembly's own documents never reach the real catalog's validation.
_cache = new CultCache(Registry());
_cache = new CultCache(TestCatalog.Registry());
_cache.AddBackingStore(new SingleFileMessagePackBackingStore(catalog), AetheriaStores.CatalogTypes);
_cache.AddBackingStore(new SingleFileMessagePackBackingStore(Path.Combine(_root, "run.cc")), AetheriaStores.RunTypes);
@ -68,11 +68,7 @@ public sealed partial class RunStartTests : IDisposable
Directory.Delete(_root, true);
}
private static CultDocumentRegistry Registry() => CultDocumentRegistry.ForTypes(typeof(ItemData).Assembly.GetTypes()
.Where(t => t is { IsAbstract: false, IsInterface: false })
.Where(t => t.GetCustomAttribute<CultDocumentAttribute>() != null));
private static string FindRepoRoot()
internal static string FindRepoRoot()
{
for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir != null; dir = dir.Parent)
if (File.Exists(Path.Combine(dir.FullName, "Aetheria.Shared", "Aetheria.Shared.csproj")))

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

@ -286,6 +286,18 @@ public sealed class ShipModCatalogTests : IDisposable
Assert.Equal("ship ID collides with an existing catalog ship authoring record.", Assert.Single(composition.Excluded).Reason);
}
// The loader and the LFS rule (GameData/Mods/**/*.glb) agree: only a lowercase .glb is a model.
[Fact]
public void AModelWithAnUppercaseExtensionIsRefused()
{
WritePackage("mod.skiff", modelAsset: "skiff.GLB");
var excluded = Assert.Single(ShipModCatalog.Compose(Shipped, Derived, Mods).Excluded);
Assert.Equal("mod.skiff", excluded.Package);
Assert.Contains("GLB", excluded.Reason);
}
// The game's boot: a bad package is named and the rest boot; with none left, the shipped catalog boots.
[Fact]
public void TheBootCatalogSurvivesBadPackages()
@ -434,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]
@ -598,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

@ -452,4 +452,132 @@ public sealed class StatResolverTests : IDisposable
Assert.Equal(baselineCache, resolver.CacheEntryCount);
Assert.Equal(baselineModifiers, resolver.ModifierEntryCount);
}
// Ruling boost-stacking-multiply: every multiplier on one stat multiplies, with no stacking penalty, and every
// constant adds. The rig is the production path end to end: gear carrying StatModifierData is equipped on a ship
// beside a thruster, a consumable is minted through ItemManager.CreateInstance and activated on the ship, and
// the resolved value is read through EquippedItem.Evaluate. Nothing here calls AttachModifier by hand.
private sealed class ThrustRig
{
public CultCache Cache;
public ItemManager Items;
public Ship Ship;
public EquippedItem Engine;
public PerformanceStat Thrust;
public Func<ConsumableItem> Consumable; // null when the rig was built without one
public float Resolved => Engine.Evaluate(Thrust);
// Two ticks: the first executes every modifier, the second applies it (StatModifier.Update).
public void Tick(float dt) { for (var i = 0; i < 2; i++) Ship.Update(dt); }
}
private static StatModifierData ThrustModifier(StatModifierType type, float value) => new StatModifierData
{
Stat = new StatReference { Target = nameof(ThrusterData), Stat = nameof(ThrusterData.Thrust) },
Modifier = new PerformanceStat { Min = value, Max = value },
Type = type
};
// A Thrust-10 thruster and one gear per entry of `gear`, in that attach order, plus (optionally) a consumable
// whose single modifier is `consumable`. The hull has four hardpoints, so at most three gear modifiers.
private ThrustRig BuildThrustRig((StatModifierType Type, float Value)[] gear, (StatModifierType Type, float Value)? consumable = null)
{
var thrust = new PerformanceStat { Min = 10, Max = 10 };
var cache = AetheriaStores.Open(Catalog, catalogWritable: true);
cache.Upsert(new TestCatalogGlobal { Name = "Temperament" });
var hullShape = new Shape(3, 3);
foreach (var cell in hullShape.AllCoordinates) hullShape[cell] = true;
var cells = new[] { HardpointCell, SecondHardpointCell, FirstGunCell, SecondGunCell };
cache.Upsert(new HullData
{
Name = "Skiff", HullType = HullType.Ship, Shape = hullShape, Durability = 10,
Hardpoints = cells.Select(c => new HardpointData { Type = HardpointType.Sensors, Position = c, Shape = new Shape() }).ToList()
});
cache.Upsert(new GearData { Name = "Engine", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 10, Behaviors = { new ThrusterData { Thrust = thrust } } });
for (var i = 0; i < gear.Length; i++)
cache.Upsert(new GearData { Name = "Boost" + i, Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 10, Behaviors = { ThrustModifier(gear[i].Type, gear[i].Value) } });
if (consumable != null)
cache.Upsert(new ConsumableItemData { Name = "Stim", Duration = 1f, Shape = new Shape(), Behaviors = { ThrustModifier(consumable.Value.Type, consumable.Value.Value) } });
cache.FlushAsync().Wait();
var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { });
var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null);
var ship = new Ship(items, zone, Mint(cache, items, cache.GetByName<HullData>("Skiff")), new EntitySettings());
Assert.True(ship.TryEquip(Mint(cache, items, cache.GetByName<GearData>("Engine")), cells[0]));
for (var i = 0; i < gear.Length; i++)
{
// A test gear has no authored heat response, so its thermal performance reads 0 and it would sit offline;
// the override is the entity's own switch for keeping a part running, not a stand-in for the rule.
var boost = Mint(cache, items, cache.GetByName<GearData>("Boost" + i));
boost.OverrideShutdown = true;
Assert.True(ship.TryEquip(boost, cells[i + 1]));
}
ship.OverrideShutdown = true;
zone.Entities.Add(ship);
ship.Activate();
Func<ConsumableItem> mint = null;
if (consumable != null)
{
var design = cache.GetByName<ConsumableItemData>("Stim");
mint = () => Assert.IsType<ConsumableItem>(items.CreateInstance(items.Lots.Add(
new Lot { Design = cache.RefOf<ItemData>(design), Origin = new Attributed(), Quality = .5f, Roles = new List<RoleFill>() })));
}
return new ThrustRig { Cache = cache, Items = items, Ship = ship, Engine = ship.Equipment.Single(e => e.Data.Name == "Engine"), Thrust = thrust, Consumable = mint };
}
// Two scales multiply: x1.2 and x1.25 on one stat resolve to base x1.5, and x1.1, x1.2, x1.25 to base x1.65,
// whatever order they attach in. Mutations at StatResolver.ScaleModifier: a sum of excesses reads 14.5 and
// 15.5, the strongest-only rule 12.5, a diminishing curve 14.67, and `result *= value * value` or
// `result *= value + 0.01f` (functions of the scale itself) read off 15.
[Theory]
[InlineData(new[] { 1.2f, 1.25f }, 15f)]
[InlineData(new[] { 1.25f, 1.2f }, 15f)]
[InlineData(new[] { 1.1f, 1.2f, 1.25f }, 16.5f)]
[InlineData(new[] { 1.25f, 1.1f, 1.2f }, 16.5f)]
[InlineData(new[] { 1.2f, 1.25f, 1.1f }, 16.5f)]
public void TwoScalesOnOneStatMultiply(float[] scales, float expected)
{
var rig = BuildThrustRig(scales.Select(s => (StatModifierType.Multiplier, s)).ToArray());
using var _ = rig.Cache;
Assert.Equal(10f, rig.Resolved, 3); // modifiers not yet applied
rig.Tick(.1f);
Assert.Equal(expected, rig.Resolved, 3);
}
// A gear modifier and a consumable modifier on one drive's Thrust share one entry and multiply: x1.2 gear and
// x1.5 consumable read x1.8, and when the consumable expires only the gear's x1.2 remains.
[Fact]
public void AConsumableBoostMultipliesWithGear()
{
var rig = BuildThrustRig(new[] { (StatModifierType.Multiplier, 1.2f) }, (StatModifierType.Multiplier, 1.5f));
using var _ = rig.Cache;
rig.Tick(.1f);
Assert.Equal(12f, rig.Resolved, 3); // gear alone
rig.Ship.ActivateConsumable(rig.Consumable());
rig.Tick(.1f); // 0.8s of the 1s remain
Assert.Equal(18f, rig.Resolved, 3);
rig.Tick(.5f); // the consumable's duration has run out
Assert.Equal(12f, rig.Resolved, 3);
}
// Constants add, and compose with scales through PerformanceStat.Evaluate: (base x scale) + constant. +3 and +4
// resolve as a constant of 7; with a x2 scale beside them the value is Evaluate's for scale 2 and constant 7,
// (10 x 2) + 7. Mutations at ConstantModifier: `result = Math.Max(result, value)` reads constant 4;
// `result += value * 2` reads constant 14.
[Theory]
[InlineData(new[] { 3f, 4f }, new float[0], 1f, 7f, 17f)]
[InlineData(new[] { 3f, 4f }, new[] { 2f }, 2f, 7f, 27f)]
public void TwoConstantsOnOneStatAdd(float[] constants, float[] scales, float expectedScale, float expectedConstant, float expected)
{
var rig = BuildThrustRig(constants.Select(c => (StatModifierType.Constant, c))
.Concat(scales.Select(s => (StatModifierType.Multiplier, s))).ToArray());
using var _ = rig.Cache;
rig.Tick(.1f);
Assert.Equal(expectedScale, rig.Ship.Resolver.ScaleModifier(rig.Engine, rig.Thrust), 3);
Assert.Equal(expectedConstant, rig.Ship.Resolver.ConstantModifier(rig.Engine, rig.Thrust), 3);
Assert.Equal(expected, rig.Resolved, 3);
}
}

View file

@ -0,0 +1,53 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using GameCult.Caching;
// The catalog the game boots, for tests: ShipModCatalog.ResolveCatalog over GameData/Mods, the call ActionGameManager
// makes. The game skips a broken package so a player still boots; a test never does, so an exclusion throws here and
// a broken first-party package fails the suite instead of vanishing from it.
internal static class TestCatalog
{
private static readonly Lazy<string> Shared = new Lazy<string>(() => ForRepo(RunStartTests.FindRepoRoot()));
// The repo's catalog with its first-party packages composed in, resolved once per test process.
public static string Repo => Shared.Value;
// The shipped assembly's own [CultDocument] types and nothing the test assembly registers (CultDocumentRegistry.ForTypes
// does not re-scan the AppDomain), so this assembly's fixture documents never become catalog globals the real catalog
// must hold. The one registry every test that opens a real catalog, and the composition behind Repo, uses.
public static CultDocumentRegistry Registry() => CultDocumentRegistry.ForTypes(typeof(ItemData).Assembly.GetTypes()
.Where(t => t is { IsAbstract: false, IsInterface: false })
.Where(t => t.GetCustomAttribute<CultDocumentAttribute>() != null));
// The catalog of the repository at repoRoot: <root>/GameData/Aetheria.cc plus <root>/GameData/Mods, composed into a
// per-call temp directory that goes away with the process.
public static string ForRepo(string repoRoot)
{
var work = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "aetheria-testcatalog-" + Guid.NewGuid().ToString("N"))).FullName;
AppDomain.CurrentDomain.ProcessExit += (_, _) => { try { Directory.Delete(work, true); } catch (IOException) { } };
return Resolve(Path.Combine(repoRoot, "GameData", "Aetheria.cc"), Path.Combine(repoRoot, "GameData", "Mods"), work);
}
public static string Resolve(string shippedCatalog, string modsRoot, string workDir)
{
// Every directory under the first-party tree is a package. The game treats a directory without a ship.cc as not a
// package (a stray folder is not an error for a player), so the compose never names it; a first-party package whose
// ship.cc is gone must not vanish from the catalog the suite stages from.
var lost = Directory.Exists(modsRoot)
? Directory.GetDirectories(modsRoot).Where(directory => !File.Exists(Path.Combine(directory, "ship.cc"))).Select(Path.GetFileName).OrderBy(name => name, StringComparer.Ordinal).ToArray()
: Array.Empty<string>();
if (lost.Length > 0)
throw new InvalidOperationException("First-party packages hold no ship.cc: " + string.Join(", ", lost));
var (catalog, excluded) = ShipModCatalog.ResolveCatalog(shippedCatalog, Path.Combine(workDir, "derived.cc"), modsRoot, Registry());
if (excluded.Length > 0)
throw new InvalidOperationException("First-party packages were excluded from the catalog: " +
string.Join("; ", excluded.Select(entry => entry.Package + ": " + entry.Reason)));
return catalog;
}
}

View file

@ -0,0 +1,95 @@
using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using GameCult.Caching;
using Xunit;
// TestCatalog.Resolve: the catalog every RunStartTests partial stages from is the one the game boots.
public sealed class TestCatalogTests : IDisposable
{
private readonly TempDirectory _directory = new TempDirectory();
private string Shipped => Path.Combine(_directory.Path, "Aetheria.cc");
private string Mods => Path.Combine(_directory.Path, "Mods");
private string Work => Path.Combine(_directory.Path, "Work");
public TestCatalogTests()
{
Directory.CreateDirectory(Mods);
using var cache = AetheriaStores.Open(Shipped, catalogWritable: true, registry: TestCatalog.Registry());
cache.Upsert(new HullData { Name = "Wasp", Shape = ShipAuthoringTests.Fixture().Hull.Shape });
cache.FlushAsync().Wait();
}
public void Dispose() => _directory.Dispose();
[Fact]
public void NoModsMeansTheShippedCatalog()
{
var before = File.ReadAllBytes(Shipped);
Assert.Equal(Shipped, TestCatalog.Resolve(Shipped, Path.Combine(_directory.Path, "absent"), Work));
Assert.Equal(Shipped, TestCatalog.Resolve(Shipped, Mods, Work));
Assert.Equal(SHA256.HashData(before), SHA256.HashData(File.ReadAllBytes(Shipped)));
}
[Fact]
public void APackageReachesTheFixture()
{
ShipFixture.WritePackage(Mods, "mod.skiff");
var catalog = TestCatalog.Resolve(Shipped, Mods, Work);
Assert.NotEqual(Shipped, catalog);
using var cache = AetheriaStores.Open(catalog, registry: TestCatalog.Registry());
Assert.Equal("Skiff", cache.Get<HullData>(ShipModCatalog.HullKey("mod.skiff")).Name);
Assert.Contains("Wasp", cache.GetAll<HullData>().Select(hull => hull.Name));
}
[Fact]
public void ABrokenPackageFailsLoudly()
{
ShipFixture.WritePackage(Mods, "mod.good", hullName: "Good");
ShipFixture.WritePackage(Mods, "mod.broken", hullName: "Broken");
File.Delete(Path.Combine(Mods, "mod.broken", "skiff.glb"));
var error = Assert.Throws<InvalidOperationException>(() => TestCatalog.Resolve(Shipped, Mods, Work));
Assert.Contains("mod.broken", error.Message);
Assert.DoesNotContain("mod.good", error.Message);
}
[Fact]
public void AFirstPartyPackageComposesOverTheRealCatalog()
{
// A repository root holding the real shipped catalog (which has no TestCatalogGlobal record) and one valid package
// under GameData/Mods, the layout TestCatalog.Repo resolves from.
var root = Path.Combine(_directory.Path, "repo");
Directory.CreateDirectory(Path.Combine(root, "GameData"));
File.Copy(Path.Combine(RunStartTests.FindRepoRoot(), "GameData", "Aetheria.cc"), Path.Combine(root, "GameData", "Aetheria.cc"));
ShipFixture.WritePackage(Path.Combine(root, "GameData", "Mods"), "mod.skiff", hullName: "FixtureSkiff");
var catalog = TestCatalog.ForRepo(root);
Assert.NotEqual(Path.Combine(root, "GameData", "Aetheria.cc"), catalog);
// Opened as RunStartTests opens it: the shipped assembly's registry, the game's own global check.
using var cache = AetheriaStores.Open(catalog, registry: TestCatalog.Registry());
Assert.Equal("FixtureSkiff", cache.Get<HullData>(ShipModCatalog.HullKey("mod.skiff")).Name);
Assert.NotEmpty(cache.GetAll<HullData>().Where(hull => hull.Name != "FixtureSkiff"));
}
[Fact]
public void APackageWithoutItsShipFileFailsLoudly()
{
ShipFixture.WritePackage(Mods, "mod.good", hullName: "Good");
ShipFixture.WritePackage(Mods, "mod.lost", hullName: "Lost");
File.Delete(Path.Combine(Mods, "mod.lost", "ship.cc"));
var error = Assert.Throws<InvalidOperationException>(() => TestCatalog.Resolve(Shipped, Mods, Work));
Assert.Contains("mod.lost", error.Message);
Assert.Contains("ship.cc", error.Message);
Assert.DoesNotContain("mod.good", error.Message);
}
}

View file

@ -0,0 +1,274 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CultMath;
using GameCult.Caching;
using Xunit;
using static CultMath.math;
// A ThrottleLock on an active consumable replaces the pilot's movement intent with full forward, read once at
// the top of Ship.Update's active branch. Turn is untouched. Every observation is a thruster's Axis after a real
// Ship.Update, with the effect started through Entity.ActivateConsumable.
public sealed class ThrottleLockTests : IDisposable
{
private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-throttlelock-" + Guid.NewGuid().ToString("N"));
private string Catalog => Path.Combine(_root, "Aetheria.cc");
public ThrottleLockTests() => Directory.CreateDirectory(_root);
public void Dispose() => Directory.Delete(_root, true);
private static GameplaySettings Settings() => new GameplaySettings
{
DefaultEntitySettings = new EntitySettings(),
Tiers = new[] { new RarityTier { Name = "Common", Quality = .5f, Rarity = 0, Color = new float3(1, 1, 1) } },
QualityPriceModifier = new ExponentialLerp()
};
private static PerformanceStat Constant(float v) => new PerformanceStat { Min = v, Max = v };
private static EquippableItem Mint(CultCache cache, ItemManager items, ItemData design, ItemRotation rotation = ItemRotation.None) => new EquippableItem
{
Data = cache.RefOf<ItemData>(design),
Durability = design is EquippableItemData equippable ? equippable.Durability : 0,
Rotation = rotation,
Lot = items.Lots.Add(new Lot { Design = cache.RefOf<ItemData>(design), Origin = new Attributed(), Quality = .5f, Roles = new List<RoleFill>() })
};
private sealed class Fixture
{
public CultCache Cache;
public ItemManager Items;
public Ship Ship;
public ConsumableItemData Lock;
public Thruster Forward, Reverse, Clockwise;
public Thruster[] Right, Left; // pairs with opposing torque: a lone off-axis strafe thruster cancels its own torque
public void ActivateLock() => Ship.ActivateConsumable(new ConsumableItem
{
Data = Cache.RefOf<ItemData>(Lock),
Lot = Items.Lots.Add(new Lot { Design = Cache.RefOf<ItemData>(Lock), Origin = new Attributed(), Quality = .5f, Roles = new List<RoleFill>() })
});
}
// One thruster per intent direction, plus two reverse thrusters either side of the centre line, one of
// which has clockwise torque (the one Turn reaches). Thrusters are found by their item's rotation, as Ship
// sorts them.
private Fixture Build(float lockDuration)
{
var cache = AetheriaStores.Open(Catalog, catalogWritable: true);
cache.Upsert(new TestCatalogGlobal { Name = "Temperament" });
var hullShape = new Shape(5, 5);
foreach (var cell in hullShape.AllCoordinates) hullShape[cell] = true;
cache.Upsert(new HullData { Name = "Skiff", HullType = HullType.Ship, Shape = hullShape, Durability = 10, Mass = 1000 });
cache.Upsert(new GearData
{
Name = "Thruster", Hardpoint = HardpointType.Tool, Shape = new Shape(), Durability = 10,
MinimumTemperature = 0, MaximumTemperature = 1000, OptimalTemperature = 280, PlateauWidth = 400,
Behaviors = { new ThrusterData { Thrust = Constant(100), Visibility = Constant(0), Heat = Constant(0), EnergyUsage = Constant(0) } }
});
var lockData = new ConsumableItemData { Name = "Overdrive", Duration = lockDuration, Behaviors = { new ThrottleLockData() } };
cache.Upsert(lockData);
cache.FlushAsync().Wait();
var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { });
var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null);
var ship = new Ship(items, zone, Mint(cache, items, cache.GetByName<HullData>("Skiff")), new EntitySettings());
var gear = cache.GetByName<GearData>("Thruster");
Assert.True(ship.TryEquip(Mint(cache, items, gear, ItemRotation.Reversed), new int2(2, 1)));
Assert.True(ship.TryEquip(Mint(cache, items, gear, ItemRotation.None), new int2(1, 2)));
Assert.True(ship.TryEquip(Mint(cache, items, gear, ItemRotation.None), new int2(3, 2)));
// Strafe pairs sit either side of the centre line across the ship's length, so their torques oppose.
Assert.True(ship.TryEquip(Mint(cache, items, gear, ItemRotation.CounterClockwise), new int2(1, 1)));
Assert.True(ship.TryEquip(Mint(cache, items, gear, ItemRotation.CounterClockwise), new int2(1, 3)));
Assert.True(ship.TryEquip(Mint(cache, items, gear, ItemRotation.Clockwise), new int2(3, 1)));
Assert.True(ship.TryEquip(Mint(cache, items, gear, ItemRotation.Clockwise), new int2(3, 3)));
zone.Entities.Add(ship);
ship.Aim = float3(0, 0, 1);
ship.Activate();
var thrusters = ship.GetBehaviors<Thruster>().ToArray();
return new Fixture
{
Cache = cache, Items = items, Ship = ship, Lock = cache.GetByName<ConsumableItemData>("Overdrive"),
Forward = thrusters.Single(t => t.Item.EquippableItem.Rotation == ItemRotation.Reversed),
Right = thrusters.Where(t => t.Item.EquippableItem.Rotation == ItemRotation.CounterClockwise).ToArray(),
Left = thrusters.Where(t => t.Item.EquippableItem.Rotation == ItemRotation.Clockwise).ToArray(),
Reverse = thrusters.First(t => t.Item.EquippableItem.Rotation == ItemRotation.None && t.Torque <= 0),
Clockwise = thrusters.First(t => t.Item.EquippableItem.Rotation == ItemRotation.None && t.Torque > 0)
};
}
// Spec ALockedThrottleIgnoresIntent. Mutation: read MovementDirection in place of move at any of the six
// sites in Ship.Update and the matching assertion goes red.
[Fact]
public void ALockedThrottleIgnoresIntent()
{
var f = Build(100f);
using var _ = f.Cache;
f.ActivateLock();
Assert.True(f.Ship.ThrottleLocked);
foreach (var intent in new[] { float2(0, -1), float2(1, 0), float2(-1, 0) })
{
f.Ship.MovementDirection = intent;
f.Ship.Turn = 0;
f.Ship.Update(0.01f);
Assert.Equal(1f, f.Forward.Axis);
Assert.Equal(0f, f.Reverse.Axis);
Assert.All(f.Right, t => Assert.Equal(0f, t.Axis));
Assert.All(f.Left, t => Assert.Equal(0f, t.Axis));
}
// Turning stays with the pilot: the clockwise-torque thruster follows Turn while the lock holds.
f.Ship.MovementDirection = float2(0, -1);
f.Ship.Turn = 1;
f.Ship.Update(0.01f);
Assert.Equal(1f, f.Clockwise.Axis);
f.Ship.Turn = 0;
f.Ship.Update(0.01f);
Assert.Equal(0f, f.Clockwise.Axis);
}
// Spec TheLockEndsWithItsEffect. Mutation: make ThrottleLocked a latch (set on activation, never cleared)
// and the post-expiry reverse axis stays 0.
[Fact]
public void TheLockEndsWithItsEffect()
{
var f = Build(1f);
using var _ = f.Cache;
f.ActivateLock();
f.Ship.MovementDirection = float2(0, -1);
f.Ship.Update(0.5f);
Assert.Equal(0f, f.Reverse.Axis);
f.Ship.Update(2f); // runs past the Duration; the effect leaves at the end of this tick
Assert.False(f.Ship.ThrottleLocked);
f.Ship.Update(0.01f);
Assert.Equal(1f, f.Reverse.Axis);
Assert.Equal(0f, f.Forward.Axis);
}
// Spec AnUnlockedShipFollowsIntent. Mutation: replace the conditional by an unconditional float2(0, 1) and
// the reverse and strafe assertions go red.
[Fact]
public void AnUnlockedShipFollowsIntent()
{
var f = Build(1f);
using var _ = f.Cache;
Assert.False(f.Ship.ThrottleLocked);
f.Ship.MovementDirection = float2(0, -1);
f.Ship.Update(0.01f);
Assert.Equal(1f, f.Reverse.Axis);
Assert.Equal(0f, f.Forward.Axis);
f.Ship.MovementDirection = float2(1, 0);
f.Ship.Update(0.01f);
Assert.All(f.Right, t => Assert.Equal(1f, t.Axis));
Assert.All(f.Left, t => Assert.Equal(0f, t.Axis));
Assert.Equal(0f, f.Forward.Axis);
f.Ship.MovementDirection = float2(-1, 0);
f.Ship.Update(0.01f);
Assert.All(f.Left, t => Assert.Equal(1f, t.Axis));
Assert.All(f.Right, t => Assert.Equal(0f, t.Axis));
f.Ship.MovementDirection = float2(0, 1);
f.Ship.Update(0.01f);
Assert.Equal(1f, f.Forward.Axis);
Assert.Equal(0f, f.Reverse.Axis);
}
// Finding zero-stick-unpinned. Mutation: float2(0, length(MovementDirection)) as the locked intent. The lock
// supplies full forward whatever the stick's magnitude, including none and a short reverse push.
[Fact]
public void ALockedShipGetsFullForwardWhateverTheStickLength()
{
var f = Build(100f);
using var _ = f.Cache;
f.ActivateLock();
foreach (var intent in new[] { float2(0, 0), float2(.3f, .2f), float2(-.5f, -.5f) })
{
f.Ship.MovementDirection = intent;
f.Ship.Turn = 0;
f.Ship.Update(0.01f);
Assert.Equal(1f, f.Forward.Axis);
Assert.Equal(0f, f.Reverse.Axis);
Assert.All(f.Right, t => Assert.Equal(0f, t.Axis));
Assert.All(f.Left, t => Assert.Equal(0f, t.Axis));
}
}
// Finding ccw-turn-unpinned. Mutation: drop the counter-clockwise Turn. Turn in either sign reaches only the
// thrusters with torque of that sign, at full, while the lock holds forward.
[Fact]
public void ALockedShipTurnsBothWays()
{
var f = Build(100f);
using var _ = f.Cache;
f.ActivateLock();
var all = f.Ship.GetBehaviors<Thruster>().ToArray();
var cw = all.Where(t => t.Torque > 0 && t.Item.EquippableItem.Rotation == ItemRotation.None).ToArray();
var ccw = all.Where(t => t.Torque < 0 && t.Item.EquippableItem.Rotation == ItemRotation.None).ToArray();
Assert.NotEmpty(cw);
Assert.NotEmpty(ccw);
f.Ship.MovementDirection = float2(1, -1);
foreach (var turn in new[] { 1f, -1f })
{
f.Ship.Turn = turn;
f.Ship.Update(0.01f);
Assert.All(turn > 0 ? cw : ccw, t => Assert.Equal(1f, t.Axis));
Assert.All(turn > 0 ? ccw : cw, t => Assert.Equal(0f, t.Axis));
Assert.Equal(1f, f.Forward.Axis);
}
}
// Finding non-lock-consumable-unpinned. Mutation: any active consumable locks. A consumable without
// ThrottleLockData leaves the pilot's intent in force.
[Fact]
public void AConsumableWithoutTheLockDoesNotLock()
{
var f = Build(100f);
using var _ = f.Cache;
var plain = new ConsumableItemData { Name = "Plain", Duration = 100f };
f.Cache.Upsert(plain);
f.Ship.ActivateConsumable(new ConsumableItem
{
Data = f.Cache.RefOf<ItemData>(plain),
Lot = f.Items.Lots.Add(new Lot { Design = f.Cache.RefOf<ItemData>(plain), Origin = new Attributed(), Quality = .5f, Roles = new List<RoleFill>() })
});
Assert.False(f.Ship.ThrottleLocked);
f.Ship.MovementDirection = float2(0, -1);
f.Ship.Update(0.01f);
Assert.Equal(1f, f.Reverse.Axis);
Assert.Equal(0f, f.Forward.Axis);
}
// Finding lock-end-boundary-unpinned, finding lock-end-at-90pct-unpinned. Mutations: the lock ends at half
// Duration, at 0.8 or 0.9 of Duration, or one tick late. Duration 1 stepped in 0.25 s ticks (exact in
// floats) locks the axes on exactly four ticks (reverse stays 0), the effect is gone when the fourth ends,
// and the fifth tick follows the stick. The count scales with Duration: 2 s locks eight ticks.
[Theory]
[InlineData(1f, 4)]
[InlineData(2f, 8)]
public void TheLockEndsAtTheExactTickOfItsDuration(float duration, int lockedTicks)
{
var f = Build(duration);
using var _ = f.Cache;
f.ActivateLock();
f.Ship.MovementDirection = float2(0, -1);
for (var i = 0; i < lockedTicks; i++)
{
Assert.True(f.Ship.ThrottleLocked);
f.Ship.Update(.25f);
Assert.Equal(0f, f.Reverse.Axis);
Assert.Equal(1f, f.Forward.Axis);
}
Assert.False(f.Ship.ThrottleLocked);
f.Ship.Update(.25f);
Assert.Equal(1f, f.Reverse.Axis);
Assert.Equal(0f, f.Forward.Axis);
}
}

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);
}
}

View file

@ -0,0 +1,431 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CultMath;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
using MessagePack;
using UniRx;
using Xunit;
using static CultMath.math;
using float2 = CultMath.float2;
using float3 = CultMath.float3;
using int2 = CultMath.int2;
// Vapour clouds in the sim (aetheria-release cut vapour-cloud, ruling vapour-cloud-obscuration): a VapourDump
// behaviour vents a zone cloud that thins every sensor sight line through it, both ways, through Sensor.Gain's
// one detection rule; a lock falls by the existing detection-threshold rule and nothing else. The scene is two
// ships facing each other along z with a fixed visibility, so what a sensor gathers is a number the clouds
// alone change: steady info is visibility x sensitivity / (distance x TargetInfoDecay), and visibility 100,
// sensitivity 1, decay .5 puts it at .5 at range 400 (above the .1 threshold) and saturated at range 40.
public sealed class VapourCloudTests : IDisposable
{
private const float Dt = .05f;
private const float Threshold = .1f;
private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-vapour-" + Guid.NewGuid().ToString("N"));
private readonly List<CultCache> _caches = new List<CultCache>();
private static readonly object Glow = new object();
public VapourCloudTests() => Directory.CreateDirectory(_root);
public void Dispose()
{
foreach (var c in _caches) c.Dispose();
Directory.Delete(_root, true);
}
private static PerformanceStat Constant(float v) => new PerformanceStat { Min = v, Max = v };
private static Shape Solid(int w, int h)
{
var shape = new Shape(w, h);
foreach (var cell in shape.AllCoordinates) shape[cell] = true;
return shape;
}
private sealed class Lab
{
public ItemManager Items;
public Zone Zone;
public Ship Observer;
public Ship Target;
public EquippedItem Dump;
public LockWeapon Lock;
public int Lot = 1;
public bool HoldTarget = true;
}
private Lab Build(float distance, float radius = 20f, float opacity = .9f, float lifetime = 1000f)
{
var settings = new GameplaySettings
{
DefaultEntitySettings = new EntitySettings(),
Tiers = new[] { new RarityTier { Name = "Common", Quality = .5f, Rarity = 0, Color = new float3(1, 1, 1) } },
QualityPriceModifier = new ExponentialLerp(),
TargetDetectionInfoThreshold = Threshold, TargetArmorInfoThreshold = .2f, TargetGearInfoThreshold = .8f,
TargetInfoDecay = .5f, VisibilityDecay = 0f,
FiringArc = 170, CommitHorizon = .5f, SchematicCellSize = 1f
};
var cache = AetheriaStores.Open(Path.Combine(_root, Guid.NewGuid().ToString("N") + ".cc"), catalogWritable: true);
_caches.Add(cache);
cache.Upsert(new TestCatalogGlobal { Name = "Temperament" });
cache.Upsert(new HullData
{
Name = "Hull", HullType = HullType.Ship, Shape = Solid(5, 5), Durability = 1000000, Mass = 1000,
Hardpoints = { new HardpointData { Type = HardpointType.Sensors, Position = new int2(0, 0), Shape = new Shape() } }
});
GearData Gear(string name, HardpointType hardpoint, BehaviorData behavior) => new GearData
{
Name = name, Hardpoint = hardpoint, Shape = new Shape(), Durability = 1,
MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000,
Behaviors = { behavior }
};
cache.Upsert(Gear("Eye", HardpointType.Tool, new SensorData
{
Sensitivity = Constant(1f),
SensitivityCurve = new BezierCurve { Keys = new[] { float4(0, 1, 0, 0), float4(1, 1, 0, 0) } },
PingBoost = Constant(.000004f), PingEnergy = Constant(0f), PingVisibility = Constant(5f),
PingRange = Constant(300f), PingCooldown = Constant(4f)
}));
cache.Upsert(Gear("Vent", HardpointType.Tool, new VapourDumpData
{
Radius = Constant(radius), Opacity = Constant(opacity), Lifetime = Constant(lifetime)
}));
cache.Upsert(Gear("LockGun", HardpointType.Sensors, new LockWeaponData
{
Damage = Constant(0), Range = Constant(1000), MinRange = Constant(0), Velocity = Constant(0),
Spread = Constant(0), DamageSpread = Constant(0), Penetration = Constant(0), Count = Constant(1),
BurstTime = Constant(0), Cooldown = Constant(1000),
DamageCurve = new BezierCurve { Keys = new[] { float4(0, 1, 0, 0), float4(1, 1, 0, 0) } },
LockSpeed = Constant(1), SensorImpact = Constant(1), LockAngle = Constant(170),
DirectionImpact = Constant(1), Decay = Constant(1)
}));
cache.FlushAsync().Wait();
var ledger = new ProvenanceLedger();
for (var i = 1; i <= 50; i++) ledger.Lots[i] = new Lot { Origin = new Attributed(), Quality = 1 };
var items = new ItemManager(cache, ledger, settings, _ => { });
var zone = new Zone(items, new PlanetSettings(), new ZonePack { Radius = 5000 }, new GalaxyZone { Name = "Vapour", Owner = null }, null);
var lab = new Lab { Items = items, Zone = zone };
EquippableItem Make(string name) => new EquippableItem
{
Data = items.ItemData.RefOf<ItemData>(items.ItemData.GetByName<GearData>(name)), Durability = 1, Lot = lab.Lot++
};
Ship NewShip()
{
var hull = items.ItemData.RefOf<ItemData>(items.ItemData.GetByName<HullData>("Hull"));
var ship = new Ship(items, zone, new EquippableItem { Data = hull, Durability = 1000000, Lot = lab.Lot++ }, new EntitySettings());
Assert.True(ship.TryEquip(Make("Eye")));
return ship;
}
lab.Observer = NewShip();
Assert.True(lab.Observer.TryEquip(Make("LockGun"), new int2(0, 0)));
lab.Target = NewShip();
var dump = Make("Vent");
Assert.True(lab.Target.TryEquip(dump));
lab.Dump = lab.Target.Equipment.Single(x => x.EquippableItem == dump);
// Held off until a test pulls the trigger: the dump vents on its first run.
lab.Dump.Enabled.Value = false;
zone.Entities.Add(lab.Observer);
zone.Entities.Add(lab.Target);
lab.Observer.Activate();
lab.Target.Activate();
lab.Observer.Position = float3(0, 0, 0);
lab.Observer.Aim = float3(0, 0, 1);
lab.Target.Position = float3(0, 0, distance);
lab.Target.Aim = float3(0, 0, -1);
lab.Observer.SetIff(lab.Target, true);
lab.Target.SetIff(lab.Observer, true);
zone.Update(0f);
lab.Lock = lab.Observer.Weapons.OfType<LockWeapon>().Single();
return lab;
}
// One tick: both ships stay where they were put, facing each other, each a fixed visibility to the other's sensor.
private static void Tick(Lab lab)
{
foreach (var ship in new[] { lab.Observer, lab.Target })
{
ship.VisibilitySources[Glow] = 100f;
if (ship != lab.Target || lab.HoldTarget) ship.Velocity = float2.zero;
}
lab.Observer.Direction = float2(0, 1);
lab.Target.Direction = float2(0, -1);
lab.Zone.Update(Dt);
}
private static void Run(Lab lab, int ticks)
{
for (var i = 0; i < ticks; i++) Tick(lab);
}
private static float Info(Ship watcher, Ship watched) => watcher.EntityInfoGathered[watched];
// The observer has settled on the target and holds a full lock on it: the state a cloud has to break.
private static void Establish(Lab lab)
{
Run(lab, 100);
Assert.True(Info(lab.Observer, lab.Target) > Threshold, "the observer never gathered the target");
Assert.Contains(lab.Target, lab.Observer.VisibleEnemies);
lab.Observer.SetTarget(lab.Target);
Run(lab, 100);
Assert.True(lab.Lock.IsLocked, "the observer never locked the target");
Assert.Empty(lab.Zone.Clouds);
}
private static void Vent(Lab lab)
{
lab.Dump.Enabled.Value = true;
for (var i = 0; i < 5 && lab.Zone.Clouds.Count == 0; i++) Tick(lab);
Assert.Single(lab.Zone.Clouds);
}
private static VapourCloud Hand(Zone zone, float2 at, float radius, float opacity, float lifetime = 1000f)
{
var cloud = new VapourCloud { Body = new KinematicBody { Position = at }, Radius = radius, Opacity = opacity, Lifetime = lifetime };
zone.Vent(cloud);
return cloud;
}
[Fact]
public void ACloudBreaksALockAtRange()
{
var lab = Build(400f);
Establish(lab);
Vent(lab);
var ticks = 0;
while (ticks++ < 600 && !lab.Observer.Target.Value.IsNone) Tick(lab);
Assert.True(lab.Observer.Target.Value.IsNone, "the cloud never broke the target");
Assert.True(Info(lab.Observer, lab.Target) < Threshold, $"info {Info(lab.Observer, lab.Target)} is above the threshold");
Run(lab, 3);
Assert.Equal(0f, lab.Lock.Lock);
Assert.DoesNotContain(lab.Target, lab.Observer.VisibleEnemies);
}
[Fact]
public void AStrongCloseSensorBurnsThrough()
{
var lab = Build(40f);
Establish(lab);
var before = Info(lab.Observer, lab.Target);
Vent(lab);
Run(lab, 600);
var after = Info(lab.Observer, lab.Target);
Assert.True(after < before - .2f, $"the cloud thinned nothing: {before} -> {after}");
Assert.True(after > Threshold, $"info {after} fell below the threshold");
Assert.Equal(lab.Target, lab.Observer.Target.Value.Entity);
Assert.True(lab.Lock.IsLocked);
}
[Fact]
public void TheCloudBlindsItsVenter()
{
var lab = Build(400f);
Run(lab, 100);
Assert.True(Info(lab.Target, lab.Observer) > Threshold, "the venter never gathered the observer");
Assert.Contains(lab.Observer, lab.Target.VisibleEnemies);
Vent(lab);
Run(lab, 300);
Assert.True(Info(lab.Target, lab.Observer) < Threshold);
Assert.DoesNotContain(lab.Observer, lab.Target.VisibleEnemies);
// (The observer updates before the venter in the tick that vents, so it is one tick behind.)
Assert.Equal(Info(lab.Observer, lab.Target), Info(lab.Target, lab.Observer), 3);
}
[Fact]
public void ACloudFadesAndIsRemoved()
{
var lab = Build(400f);
// Vented 3s into the zone's life: the fade runs from the vent, not from the zone's start.
for (var i = 0; i < 3; i++) lab.Zone.Update(1f);
var cloud = Hand(lab.Zone, float2(0, 0), 10f, .8f, lifetime: 10f);
var a = float2(-5, 0);
var b = float2(5, 0);
Assert.Equal(.2f, lab.Zone.Obscuration(a, b), 5);
for (var i = 0; i < 5; i++) lab.Zone.Update(1f);
Assert.Equal(.4f, cloud.OpacityAt(lab.Zone.Time), 5);
Assert.Equal(.6f, lab.Zone.Obscuration(a, b), 5);
Assert.Single(lab.Zone.Clouds);
for (var i = 0; i < 5; i++) lab.Zone.Update(1f);
Assert.Empty(lab.Zone.Clouds);
Assert.Equal(1f, lab.Zone.Obscuration(a, b));
}
[Fact]
public void ACloudDriftsWithItsVelocityUntilItFades()
{
var lab = Build(400f);
var cloud = new VapourCloud { Body = new KinematicBody { Position = float2(0, 0), Velocity = float2(10, 0) }, Radius = 5f, Opacity = .5f, Lifetime = 1000f };
lab.Zone.Vent(cloud);
Assert.Equal(.5f, lab.Zone.Obscuration(float2(0, -20), float2(0, 20)), 5);
lab.Zone.Update(1f);
// The launch velocity decays on the zone's launch drag, so it has moved most of the way and no further.
Assert.InRange(cloud.Body.Position.x, 5f, 9.9f);
Assert.Equal(1f, lab.Zone.Obscuration(float2(0, -20), float2(0, 20)));
Assert.Equal(.5f, lab.Zone.Obscuration(float2(cloud.Body.Position.x, -20), float2(cloud.Body.Position.x, 20)), 2);
}
[Fact]
public void ACloudWithNoLifetimeObscuresNothing()
{
var lab = Build(400f);
var cloud = Hand(lab.Zone, float2(0, 0), 10f, .8f, lifetime: 0f);
Assert.Equal(0f, cloud.OpacityAt(lab.Zone.Time));
Assert.Equal(1f, lab.Zone.Obscuration(float2(-5, 0), float2(5, 0)));
}
[Fact]
public void AnEffectVentsOnce()
{
var lab = Build(400f, radius: 17f, opacity: .7f, lifetime: 123f);
lab.HoldTarget = false;
Run(lab, 2);
lab.Target.Velocity = float2(3, 0);
VapourCloud vented = null;
float2 venterVelocity = float2.zero;
float2 venterAt = float2.zero;
float2 cloudVelocity = float2.zero;
float2 cloudAt = float2.zero;
using var sub = lab.Zone.Clouds.ObserveAdd().Subscribe(add =>
{
vented = add.Value;
cloudVelocity = add.Value.Body.Velocity;
cloudAt = add.Value.Body.Position;
venterVelocity = lab.Target.Velocity;
venterAt = lab.Target.Position.xz;
});
lab.Dump.Enabled.Value = true;
Run(lab, 100);
Assert.Single(lab.Zone.Clouds);
Assert.Same(vented, lab.Zone.Clouds.Single());
Assert.True(length(venterVelocity) > 0f, "the venter was not moving");
Assert.Equal(venterVelocity, cloudVelocity);
Assert.Equal(venterAt, cloudAt);
Assert.Same(lab.Target, vented.Venter);
// Each stat is the authored one, evaluated through the host.
Assert.Equal(17f, vented.Radius);
Assert.Equal(.7f, vented.Opacity);
Assert.Equal(123f, vented.Lifetime);
}
[Fact]
public void ACloudThinsOnlyTheSightLinesItTouches()
{
var lab = Build(400f);
var first = Hand(lab.Zone, float2(0, 0), 10f, .6f);
float Through(float2 a, float2 b) => lab.Zone.Obscuration(a, b);
Assert.Equal(.4f, Through(float2(-50, 0), float2(50, 0)), 5);
Assert.Equal(.4f, Through(float2(50, 0), float2(-50, 0)), 5);
// Passing wide of the centre but within the radius, neither end inside the disc.
Assert.Equal(.4f, Through(float2(-50, 9.9f), float2(50, 9.9f)), 5);
Assert.Equal(1f, Through(float2(-50, 10.1f), float2(50, 10.1f)));
// Ending inside the disc, and a point inside it (the observer inside its own cloud).
Assert.Equal(.4f, Through(float2(-50, 0), float2(5, 0)), 5);
Assert.Equal(.4f, Through(float2(3, 0), float2(3, 0)), 5);
Assert.Equal(1f, Through(float2(30, 0), float2(30, 0)));
// A segment that stops short of the disc, or starts past it, touches nothing even on the same line.
Assert.Equal(1f, Through(float2(-50, 0), float2(-20, 0)));
Assert.Equal(1f, Through(float2(20, 0), float2(50, 0)));
// Two clouds on one sight line multiply.
var second = Hand(lab.Zone, float2(30, 0), 5f, .5f);
Assert.NotEqual(first.Id, second.Id);
Assert.Equal(.2f, Through(float2(-50, 0), float2(50, 0)), 5);
Assert.Equal(.4f, Through(float2(-50, 0), float2(15, 0)), 5);
}
// Where the rule is decided: once the start-up seed has decayed away, the info a sensor settles at is what
// survives the cloud times what the open sight line settles at, in both directions.
[Fact]
public void TheGainIsScaledByWhatSurvivesTheCloud()
{
var clear = Build(400f);
var cloudy = Build(400f);
// Mid-way between them and clear of both: only the segment, not either end, touches it.
Hand(cloudy.Zone, float2(0, 200), 10f, .6f, lifetime: 1e6f);
Run(clear, 400);
Run(cloudy, 400);
Assert.True(Info(clear.Observer, clear.Target) > Threshold);
Assert.Equal(.4f, Info(cloudy.Observer, cloudy.Target) / Info(clear.Observer, clear.Target), 2);
Assert.Equal(.4f, Info(cloudy.Target, cloudy.Observer) / Info(clear.Target, clear.Observer), 2);
}
// A ping is gathered through the same rule. Settled, the tick that a ping reaches the target adds the ping gain
// in place of the passive one; that extra, in a lab with a cloud on the sight line, is what survives the
// cloud times the extra in the open (info is linear in the gain while nothing saturates).
[Fact]
public void ThePingGainIsScaledToo()
{
float PingExtra(Lab lab)
{
Run(lab, 400);
lab.Observer.Sensor.Ping();
var biggest = 0f;
var last = Info(lab.Observer, lab.Target);
for (var i = 0; i < 38; i++)
{
Tick(lab);
biggest = max(biggest, Info(lab.Observer, lab.Target) - last);
last = Info(lab.Observer, lab.Target);
}
return biggest;
}
var clear = Build(250f);
var cloudy = Build(250f);
Hand(cloudy.Zone, float2(0, 125), 10f, .6f, lifetime: 1e6f);
var open = PingExtra(clear);
Assert.True(open > .05f, $"the ping left no mark on the open trace ({open})");
Assert.Equal(.4f, PingExtra(cloudy) / open, 2);
}
// The chunk path reads the same rule: the passive rate toward a point is scaled by the same survivor fraction.
[Fact]
public void TheChunkRateIsScaledByTheSameFactor()
{
var lab = Build(100f);
var at = float2(0, 100);
var open = lab.Observer.Sensor.PassiveRate(100f, at);
Assert.True(open > 0f);
Hand(lab.Zone, float2(0, 50), 10f, .6f);
Assert.Equal(.4f, lab.Observer.Sensor.PassiveRate(100f, at) / open, 5);
}
// The dump's wire shape: BehaviorData union 42, its radius, opacity and lifetime at keys 1, 2 and 3.
[Fact]
public void TheDumpIsUnion42WithRadiusOpacityLifetimeAtKeys1To3()
{
var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(ZonePack).Assembly);
var data = new VapourDumpData { Radius = Constant(1f), Opacity = Constant(2f), Lifetime = Constant(3f) };
var bytes = MessagePackSerializer.Serialize<BehaviorData>(data, options);
var reader = new MessagePackReader(bytes);
Assert.Equal(2, reader.ReadArrayHeader());
Assert.Equal(42, reader.ReadInt32());
Assert.Equal(4, reader.ReadArrayHeader());
reader.Skip();
Assert.Equal(1f, MessagePackSerializer.Deserialize<PerformanceStat>(ref reader, options).Min);
Assert.Equal(2f, MessagePackSerializer.Deserialize<PerformanceStat>(ref reader, options).Min);
Assert.Equal(3f, MessagePackSerializer.Deserialize<PerformanceStat>(ref reader, options).Min);
}
}