Merge origin/master into damage-falloff

Conflicts: FusedRounds scenario brief and fixture comment, SmokeRoundsSteppedTests, and AetherDb's usage line keep both sides, with
DeathCluster renamed Cluster Cannon. GameData/Aetheria.cc is master's blob; range-falloff is rerun on it in the next commit.
This commit's catalog does not carry the falloff stats, so CatalogRole/falloff catalog tests do not pass here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-14 09:54:44 +02:00
commit 97b7566ee9
65 changed files with 3360 additions and 336 deletions

View file

@ -24,7 +24,7 @@ using static CultMath.math;
// (to decide whether the pump can keep up this tick). Cut 7 asks for the brownout curve to live on exactly
// the stats the behaviour actually curves (PumpedHeat), but F6 forbade a PowerSupply term on any
// stat a request reads at all, on pain of the exact oscillation Soul measured against the shipped catalog's own
// "OK Disperser" radiator (SOUL_RadiatorRequestDependsOnItsOwnGrantAndOscillates, docs/stats-and-power-cut.md).
// "Heat Pump" radiator (SOUL_RadiatorRequestDependsOnItsOwnGrantAndOscillates, docs/stats-and-power-cut.md).
// The six tests below that authored one were marked Skip rather than deleted or silently reworked to hide the
// gap, naming the conflict as real, scoped work for a future pass rather than a fix a registry correction should
// smuggle in.

View file

@ -95,6 +95,106 @@ public sealed class CatalogRoleTests
Assert.True(makerless.Length == 0, "products with no maker: " + string.Join(", ", makerless));
}
// A design is named like a node on a tech tree and the brand lives in the product it sells (rulings
// catalog-grows-generic-designs-branded-products, designs-are-tech-nodes): no design's product bears the design's name.
[Fact]
public void EveryProductCarriesABrand()
{
using var cache = RestoredHullsTests.OpenCatalog();
var products = cache.GetAll<FactionProductData>().ToArray();
var unbranded = cache.GetAll<EquippableItemData>().Where(design => design is not HullData)
.Where(design => products.Any(p => p.Design.Key.Equals(cache.RefOf(design).Key) && p.Name == design.Name))
.Select(design => design.Name).OrderBy(n => n, StringComparer.Ordinal).ToArray();
Assert.True(unbranded.Length == 0, "designs sold under their own name: " + string.Join(", ", unbranded));
}
// The Capacitor is the one Tool design with a role map by name; a key that falls out of step with the design's name leaves
// roles-backfill finding no map for it.
[Fact]
public void TheCapacitorDesignCarriesItsRoleMap()
{
using var cache = RestoredHullsTests.OpenCatalog();
var capacitor = cache.GetAll<EquippableItemData>().Single(design => design.Name == "Capacitor");
Assert.True(Program.HasRoleMap(capacitor), "roles-backfill finds no role map for the Capacitor design");
}
// A design is a tech node: its text may not name a product the catalog sells (the brand lives on the product).
[Fact]
public void NoDesignTextNamesAProduct()
{
using var cache = RestoredHullsTests.OpenCatalog();
var productNames = cache.GetAll<FactionProductData>().Select(p => p.Name).Where(n => n.Length > 3).ToHashSet();
var branded = cache.GetAll<EquippableItemData>().Where(design => design is not HullData && design.Description != null)
.Where(design => productNames.Any(n => design.Description.Contains(n)))
.Select(design => design.Name).OrderBy(n => n, StringComparer.Ordinal).ToArray();
Assert.True(branded.Length == 0, "designs whose text names a product: " + string.Join(", ", branded));
}
// Authoring notes are not player text, and every product of a design this cut renamed or branded speaks in its own
// voice (Miss Terri's and the Pirates' records are other passes').
[Fact]
public void NoProductTextIsAnAuthoringNote()
{
using var cache = RestoredHullsTests.OpenCatalog();
var products = cache.GetAll<FactionProductData>().ToArray();
string[] notes = { Program.AuthoringNote.Trim(), "[TODO]", "subsidiary plight" };
var noted = products.Where(p => p.Description != null && notes.Any(n => p.Description.Contains(n))).Select(p => p.Name).OrderBy(n => n, StringComparer.Ordinal).ToArray();
Assert.True(noted.Length == 0, "products whose text is an authoring note: " + string.Join(", ", noted));
var touched = Program.Renames.Select(r => r.Generic).Concat(Program.Brands.Select(b => b.Design)).ToHashSet();
var designs = cache.GetAll<EquippableItemData>().Where(d => touched.Contains(d.Name)).ToArray();
Assert.Equal(touched.Count, designs.Length);
var silent = products
.Where(p => designs.Any(d => p.Design.Key.Equals(cache.RefOf(d).Key)))
.Where(p => cache.Get(p.Manufacturer)?.ShortName is not ("Miss Terri's" or "Pirates"))
.Where(p => string.IsNullOrWhiteSpace(p.Description))
.Select(p => p.Name).OrderBy(n => n, StringComparer.Ordinal).ToArray();
Assert.True(silent.Length == 0, "products with no text of their own: " + string.Join(", ", silent));
}
// A rename changes Name and Description and nothing else: the design and its products keep their keys and makers, and the
// flavour that moved lives on the product.
[Fact]
public void RenamedDesignsKeepTheirKeysAndProducts()
{
using var cache = RestoredHullsTests.OpenCatalog();
var expected = new (string DesignKey, string Generic, (string Key, string Name, string Maker)[] Products)[]
{
("0271bb97-4ce8-4d64-97c3-8bfd3f76b2c6", "Light Machine Gun", new[] { ("7a1f63b0-68de-4976-a338-bc779db3386a", "ClearPath", "Lightsail") }),
("3baa2c43-b389-4438-94cb-fbb04489cd77", "Heavy Reactor", new[] { ("1edd87f7-2592-4744-a9ba-618f403f91ce", "Manhattan", "Zhestokost") }),
("49b4c15a-c10b-49c0-9dad-31dfb9b3a9b9", "Cargo Bay", new[] { ("4ecc97af-c1fa-4563-902e-72a094ad8322", "Store-All Plus", "Lightsail"), ("ed3c70eb23814d5181d99fa84f6194d4", null, "Pirates") }),
("88e81a2b-45fd-49de-830f-c896adae8d5b", "Racing Drive", new[] { ("9ccc095374d64fde94dd8d04bdc97c2a", "Victoire", "Alakrita") }),
("632420a6-4419-4647-a92b-5e22ea289025", "Lightning Projector", new[] { ("f0f8389f9dd64228b02a68392fcf4007", "DragOnBreath", "Lucent") }),
};
foreach (var (designKey, generic, sold) in expected)
{
var design = Assert.Single(cache.GetAll<EquippableItemData>(), d => cache.RefOf(d).Key.Value == designKey);
Assert.Equal(generic, design.Name);
Assert.Equal(Program.Renames.Single(r => r.Generic == generic).Functional, design.Description);
var products = cache.GetAll<FactionProductData>().Where(p => p.Design.Key.Equals(cache.RefOf(design).Key)).ToArray();
Assert.Equal(sold.Select(p => p.Key).OrderBy(k => k, StringComparer.Ordinal), products.Select(p => cache.RefOf(p).Key.Value).OrderBy(k => k, StringComparer.Ordinal));
foreach (var (key, name, maker) in sold)
{
var product = products.Single(p => cache.RefOf(p).Key.Value == key);
if (name != null) Assert.Equal(name, product.Name);
Assert.Equal(maker, cache.Get(product.Manufacturer).ShortName);
}
}
// The text that moved: Victoire carries the racing drive's old line, DragOnBreath plight's old one.
string TextOf(string productKey) => cache.GetAll<FactionProductData>().Single(p => cache.RefOf(p).Key.Value == productKey).Description;
Assert.Equal("The most responsive thruster on the market, for the most irresponsible of racing pilots.", TextOf("9ccc095374d64fde94dd8d04bdc97c2a"));
Assert.StartsWith("Chain lightning has your enemies chain smoking", TextOf("f0f8389f9dd64228b02a68392fcf4007"));
// The mine launcher: the design takes the functional line its product used to carry; the product is the brand.
var mine = Assert.Single(cache.GetAll<EquippableItemData>(), d => cache.RefOf(d).Key.Value == "1b4a2bb358eb432eb1cfc0ccf3317303");
Assert.Equal("Mine Launcher", mine.Name);
Assert.Equal("Lays a drifting proximity mine that arms after two seconds.", mine.Description);
var brand = Assert.Single(cache.GetAll<FactionProductData>(), p => p.Design.Key.Equals(cache.RefOf(mine).Key));
Assert.Equal("parting gift", brand.Name);
Assert.Equal("DME", cache.Get(brand.Manufacturer).ShortName);
}
// A benefit rises with quality across 0.8x to 1.2x of its authored value (Max/Min 1.5), a cost falls across 1.2x to 0.8x
// (Max/Min 2/3). The ratio and the role are pinned, not the value, so an operator retune of a design stays green.
private static void AssertRange(EquippableItemData design, string field, bool cost, string role)
@ -121,13 +221,13 @@ public sealed class CatalogRoleTests
AssertRange(autocannon, "Range", false, "barrel");
AssertRange(autocannon, "Penetration", false, "barrel");
var lrm = Design("LRMM72");
var lrm = Design("Long-Range Missile Rack");
Assert.Equal(new[] { "guidance system", "thruster", "warhead" }, Roles(lrm));
AssertRange(lrm, "Damage", false, "warhead");
AssertRange(lrm, "Cooldown", true, "guidance system");
AssertRange(lrm, "LockAngle", false, "guidance system");
var srm = Design("SRMM72");
var srm = Design("Short-Range Missile Rack");
Assert.Equal(new[] { "guidance system", "thruster", "warhead" }, Roles(srm));
AssertRange(srm, "Damage", false, "warhead");
AssertRange(srm, "Cooldown", true, "guidance system");
@ -152,12 +252,12 @@ public sealed class CatalogRoleTests
AssertRange(Design("Small Drive"), "Thrust", false, "nozzle");
// Designs whose non-flat stats named no role are pointed at the role their kind's map gives them.
AssertNamed(Design("DeathCluster"), "Count", "feed mechanism");
AssertNamed(Design("Cluster Cannon"), "Count", "feed mechanism");
AssertNamed(Design("Flak Gun"), "Count", "feed mechanism");
AssertNamed(Design("GT 3K"), "MinRange", "guidance system");
AssertNamed(Design("plight"), "DamageSpread", "focusing array");
AssertNamed(Design("MoveOnPro"), "Modifier", "core");
AssertNamed(Design("MoveOnPro Station Reactor"), "Modifier", "core");
AssertNamed(Design("Guided Missile Launcher"), "MinRange", "guidance system");
AssertNamed(Design("Lightning Projector"), "DamageSpread", "focusing array");
AssertNamed(Design("Muon Fusion Reactor"), "Modifier", "core");
AssertNamed(Design("Muon Fusion Station Reactor"), "Modifier", "core");
// Each seller's means come from its maker's profile; the Pirates are middling and inconsistent.
var profiles = new Dictionary<string, (float Mean, float Dev)>
@ -182,4 +282,92 @@ public sealed class CatalogRoleTests
}
Assert.Contains(cache.GetAll<FactionProductData>(), p => p.Design.Key.Equals(cache.RefOf(autocannon).Key) && cache.Get(p.Manufacturer).ShortName == "Pirates");
}
// aetheria-release cut sensor-catalog (ruling sensor-stat-set): every sensor design's intercept factor varies with its
// maker's emission-discipline quality, brand flavour is a product's quality (Lucent loud, Finch quiet), and the
// Passive Array is a Tool listener with two products from makers other than Miss Terri's and the Pirates.
[Fact]
public void TheCatalogCarriesSensorStats()
{
using var cache = RestoredHullsTests.OpenCatalog();
var products = cache.GetAll<FactionProductData>().ToArray();
string MakerOf(FactionProductData p) => cache.Get(p.Manufacturer).ShortName;
var sensors = cache.GetAll<EquippableItemData>().Where(d => d.Behaviors.OfType<SensorData>().Any()).ToArray();
Assert.NotEmpty(sensors);
foreach (var design in sensors)
{
var alpha = design.Behaviors.OfType<SensorData>().Single().InterceptFactor;
Assert.NotNull(alpha);
Assert.NotEqual(alpha.Min, alpha.Max);
Assert.Equal(new[] { "emission-discipline" }, NamedQualityRoles(alpha));
}
double[] Discipline(string maker) => products
.Where(p => sensors.Any(s => cache.RefOf(s).Key.Equals(p.Design.Key)) && MakerOf(p) == maker)
.Select(p => (double)p.Roles.Single(r => r.Role == "emission-discipline").Mean).ToArray();
var lucent = Discipline("Lucent");
var finch = Discipline("Finch");
Assert.NotEmpty(lucent);
Assert.NotEmpty(finch);
Assert.True(lucent.Max() < finch.Min(), "a Lucent sensor must be louder than every Finch one");
var array = Assert.Single(cache.GetAll<EquippableItemData>(), d => d.Name == "Passive Array");
Assert.Equal(HardpointType.Tool, array.HardpointType);
Assert.True(array.Behaviors.OfType<ListenerData>().Single().Multiple.Min >= 2f);
var makers = products.Where(p => p.Design.Key.Equals(cache.RefOf(array).Key)).Select(MakerOf).ToArray();
Assert.Equal(2, makers.Distinct().Count());
Assert.DoesNotContain(makers, m => m == "Pirates" || m == "Miss Terri's");
}
// The intercept factor alpha is quality-derived (ruling sensor-stat-set): evaluated by the stat's own Evaluate over a
// lot that fills only emission-discipline, so a design that read the lot's workmanship instead would read the decoy.
private sealed class DisciplineContext : IStatContext
{
public DisciplineContext(float discipline) =>
Lot = new Lot { Quality = .123f, Roles = new List<RoleFill> { new RoleFill { Role = "emission-discipline", Quality = discipline } } };
public Lot Lot { get; }
public float HeatFactor(float exponent) => 1f;
public float DurabilityFactor(float exponent) => 1f;
public float ConsumableProgressFactor(float exponent) => 1f;
public float PowerSupplyFactor(float exponent) => 1f;
public float ScaleModifier(PerformanceStat stat) => 1f;
public float ConstantModifier(PerformanceStat stat) => 0f;
}
// A sensor of middling discipline reads exactly 1 (it is heard where it sees), the worst discipline reads the loud end
// .5 and the best the quiet end 2, and the exponent is the one that puts the midpoint on 1: lerp(.5, 2, .5^e) = 1.
// Each product then reads alpha at its own authored discipline: Lucent below 1 (loud), Finch and Sol above (quiet),
// every other maker at 1. The expectations come from that formula, not from numbers copied out of the catalog.
[Fact]
public void ASensorsInterceptFactorIsDerivedFromItsEmissionDiscipline()
{
using var cache = RestoredHullsTests.OpenCatalog();
var sensors = cache.GetAll<EquippableItemData>().Where(d => d.Behaviors.OfType<SensorData>().Any()).ToArray();
Assert.NotEmpty(sensors);
float Alpha(EquippableItemData design, float discipline) =>
design.Behaviors.OfType<SensorData>().Single().InterceptFactor.Evaluate(new DisciplineContext(discipline));
foreach (var design in sensors)
{
Assert.Equal(1f, Alpha(design, .5f), 4);
Assert.Equal(.5f, Alpha(design, 0f), 4);
Assert.Equal(2f, Alpha(design, 1f), 4);
var term = Assert.Single(design.Behaviors.OfType<SensorData>().Single().InterceptFactor.Terms);
Assert.Equal(MathF.Log(3f) / MathF.Log(2f), term.Exponent, 4); // (2 - .5) / (1 - .5) = 3 = 2^e
}
var products = cache.GetAll<FactionProductData>()
.Where(p => sensors.Any(s => cache.RefOf(s).Key.Equals(p.Design.Key))).ToArray();
Assert.NotEmpty(products);
foreach (var product in products)
{
var design = sensors.Single(s => cache.RefOf(s).Key.Equals(product.Design.Key));
var maker = cache.Get(product.Manufacturer).ShortName;
var alpha = Alpha(design, product.Roles.Single(r => r.Role == "emission-discipline").Mean);
if (maker == "Lucent") Assert.True(alpha < .8f, $"{product.Name}: a Lucent sensor must be loud, reads {alpha}");
else if (maker == "Finch" || maker == "Sol") Assert.True(alpha > 1.25f, $"{product.Name}: a {maker} sensor must be quiet, reads {alpha}");
else Assert.Equal(1f, alpha, 3);
}
Assert.Contains(products, p => cache.Get(p.Manufacturer).ShortName == "Lucent");
Assert.Contains(products, p => cache.Get(p.Manufacturer).ShortName == "Finch");
}
}

View file

@ -59,6 +59,24 @@ public sealed partial class ContactRevealTests : IDisposable
// PingRange (300) over the intercept factor.
cache.Upsert(Eye("Shout", sensitivity: 2f, interceptFactor: 2f, beamWidth: 10f));
cache.Upsert(Eye("Roar", sensitivity: 2f, interceptFactor: .5f, beamWidth: 10f));
// The catalog's sensor alpha (AetherDb sensor-stat-set): .5 to 2 over one Quality term on the equipped lot's
// emission-discipline role, exponent log2(3) so a middling part (.5) reads 1.
var disciplined = Eye("Disciplined", sensitivity: 2f);
disciplined.Roles.Add(new ItemRole { Name = "emission-discipline" });
disciplined.Behaviors.OfType<SensorData>().Single().InterceptFactor = new PerformanceStat
{
Min = .5f, Max = 2f,
Terms = { new StatTerm { Source = StatSource.Quality, Exponent = MathF.Log(3f) / MathF.Log(2f), Role = "emission-discipline" } }
};
cache.Upsert(disciplined);
cache.Upsert(Listener("Listener", 3f));
cache.Upsert(new ConsumableItemData { Name = "Earpiece", Duration = 30f, Shape = new Shape(), Behaviors = { new ListenerData { Multiple = Const(3f) } } });
cache.Upsert(Listener("Wide", 5f));
cache.Upsert(Listener("Narrow", 1.5f));
cache.Upsert(Listener("Hush", .5f));
cache.Upsert(new ConsumableItemData { Name = "HushEarpiece", Duration = 30f, Shape = new Shape(), Behaviors = { new ListenerData { Multiple = Const(.5f) } } });
cache.Upsert(new ConsumableItemData { Name = "WideEarpiece", Duration = 30f, Shape = new Shape(), Behaviors = { new ListenerData { Multiple = Const(5f) } } });
cache.Upsert(new ConsumableItemData { Name = "NarrowEarpiece", Duration = 30f, Shape = new Shape(), Behaviors = { new ListenerData { Multiple = Const(1.5f) } } });
cache.Upsert(Tool("Reactor", new ReactorData { Charge = Const(1000), Efficiency = Const(1), OverloadEfficiency = Const(1), ThrottlingFactor = Const(2) }));
cache.Upsert(Tool("Targeting", new TargetingSystemData { Accuracy = Const(1), Resolution = Const(1000f), Precision = Const(1000f), Tracking = Const(1000000f) }));
cache.Upsert(Tool("Thruster", new ThrusterData { Thrust = Const(100), Visibility = Const(10), Heat = Const(0), EnergyUsage = Const(10) }));
@ -99,6 +117,14 @@ public sealed partial class ContactRevealTests : IDisposable
cache.Upsert(SpannedWeapon("SpanBeam", Spanned(new ConstantWeaponData())));
cache.Upsert(Locker("Locker", interceptFactor: null));
cache.Upsert(Locker("Hushed", interceptFactor: 4f));
// Scanners (cut inspection-scanner): range 200 and a two second scan; "QuietScanner" is heard at a quarter of it.
cache.Upsert(Tool("Scanner", ScannerBehavior(range: 200f, scanTime: 2f)));
cache.Upsert(Tool("QuietScanner", ScannerBehavior(range: 200f, scanTime: 2f, interceptFactor: 4f)));
cache.Upsert(new ConsumableItemData
{
Name = "ScannerCharge", Duration = 30f, Shape = new Shape(),
Behaviors = { ScannerBehavior(range: 200f, scanTime: 2f) }
});
cache.Upsert(new ConsumableItemData
{
Name = "Pinger", Duration = 30f, Shape = new Shape(),
@ -241,9 +267,13 @@ public sealed partial class ContactRevealTests : IDisposable
private EquippableItem Make(string name) => new EquippableItem
{
Data = _items.ItemData.RefOf<ItemData>(_items.ItemData.GetByName<ItemData>(name)), Durability = 10, Lot = _nextLot++
Data = _items.ItemData.RefOf<ItemData>(_items.ItemData.GetByName<ItemData>(name)), Durability = 10,
Lot = _preparedLots.Remove(name, out var prepared) ? prepared : _nextLot++
};
// Lots a test built through the ItemManager for the next mount of that name, ahead of Add (a ship takes no gear once deployed).
private readonly Dictionary<string, int> _preparedLots = new Dictionary<string, int>();
// A ship at `position` with `mounts` on its sensor hardpoints in order, the tools on free cells and a thruster
// on the centre column. A ship with a gun also gets the reactor and targeting a gun needs to fire.
private Ship Add(float3 position, string[] mounts = null, string[] tools = null, bool thruster = false)

View file

@ -9,8 +9,8 @@ using float3 = CultMath.float3;
// staging what its brief claims fails here.
public sealed partial class RunStartTests
{
// Crossing: the demo's cast; plight and FastBlast+- fitted in separate weapon groups with the Fire Control Array
// aboard; a piloted hostile Djinni that crosses the bow inside 400 m; and an unpiloted neutral one inside plight's
// Crossing: the demo's cast; projector and Cell Blaster fitted in separate weapon groups with the Fire Control Array
// aboard; a piloted hostile Djinni that crosses the bow inside 400 m; and an unpiloted neutral one inside the Lightning Projector's
// arc, short of its Range and beyond three quarters of it.
[Fact]
public void CrossingConditions()
@ -21,12 +21,12 @@ public sealed partial class RunStartTests
Assert.Equal(4, galaxy.HomeZones.Count);
var player = staged.Player;
var plight = player.Equipment.Single(item => item.Data.Name == "plight");
var small = player.Equipment.Single(item => item.Data.Name == "FastBlast+-");
var projector = player.Equipment.Single(item => item.Data.Name == "Lightning Projector");
var small = player.Equipment.Single(item => item.Data.Name == "Cell Blaster");
Assert.Contains(player.Equipment, item => item.Data.Name == "Fire Control Array");
var groupOf = new System.Func<EquippedItem, int>(item => System.Array.FindIndex(player.WeaponGroups, group => group.items.Contains(item)));
Assert.True(groupOf(plight) >= 0 && groupOf(small) >= 0, "both guns are in a weapon group");
Assert.NotEqual(groupOf(plight), groupOf(small));
Assert.True(groupOf(projector) >= 0 && groupOf(small) >= 0, "both guns are in a weapon group");
Assert.NotEqual(groupOf(projector), groupOf(small));
Assert.Equal(2, staged.Entities.Count);
var crosser = staged.Entities[0];
@ -54,10 +54,10 @@ public sealed partial class RunStartTests
Assert.Equal(0, AgentsOf(arena, waiting));
var toWaiting = waiting.Position - player.Position;
EvSettle(player); // a weapon's Range is read once the ship's stats have settled; the geometry above is as staged
var range = plight.Behaviors.OfType<Weapon>().Single().Range;
Assert.True(FireControl.InArc(plight, toWaiting), "the waiting Djinni is inside plight's arc");
Assert.True(length(toWaiting) <= range, "the waiting Djinni is inside plight's Range");
Assert.True(length(toWaiting) > .75f * range, "the waiting Djinni is beyond three quarters of plight's Range");
var range = projector.Behaviors.OfType<Weapon>().Single().Range;
Assert.True(FireControl.InArc(projector, toWaiting), "the waiting Djinni is inside the Lightning Projector's arc");
Assert.True(length(toWaiting) <= range, "the waiting Djinni is inside the Lightning Projector's Range");
Assert.True(length(toWaiting) > .75f * range, "the waiting Djinni is beyond three quarters of the Lightning Projector's Range");
// The crossing is what the sim does with that staging, read in the player's frame: the arena's gravity and the
// crosser's pilot act from the first tick, so the t=0 facing proves nothing. Within CrossingSeconds the crosser's
@ -79,8 +79,8 @@ public sealed partial class RunStartTests
crossedMetres = length(after);
Assert.True(after.z > 0, "the crosser passes the bow line ahead of the player, not astern");
Assert.True(length(after) < CrossingMetres, "the crosser passes inside the stated distance");
Assert.True(FireControl.InArc(small, after), "FastBlast+- bears on the crosser as it crosses");
Assert.True(dot(FireControl.MountDirection(small), float3(player.Direction.x, 0, player.Direction.y)) > 0, "FastBlast+- mounts forward");
Assert.True(FireControl.InArc(small, after), "Cell Blaster bears on the crosser as it crosses");
Assert.True(dot(FireControl.MountDirection(small), float3(player.Direction.x, 0, player.Direction.y)) > 0, "Cell Blaster mounts forward");
}
}
Assert.True(swept, $"the crosser's bearing never swept across the bow within {CrossingSeconds} s");

View file

@ -314,4 +314,22 @@ public sealed partial class ContactRevealTests
Assert.Equal(1f, locker.Equipment.SelectMany(i => i.Behaviors).OfType<LockWeapon>().Single().InterceptFactor);
Assert.Equal(4f, hushed.Equipment.SelectMany(i => i.Behaviors).OfType<LockWeapon>().Single().InterceptFactor);
}
// A catalog-style sensor reads its intercept factor through the lot the ship equips it from: the lot's
// emission-discipline fill is the input (the workmanship is a decoy at .123), so a Sensor that read only the quiet or only
// the loud end, or the workmanship, reads the wrong number. The expectations are lerp(.5, 2, q^log2(3)): a middling part
// reads 1, the Lucent mean (.2) reads about .62 and the Finch mean (.8) about 1.55.
[Theory]
[InlineData(.5f, 1f)]
[InlineData(.2f, .6168f)]
[InlineData(.8f, 1.5534f)]
public void ASensorReadsItsInterceptFactorFromItsLotsEmissionDiscipline(float discipline, float expected)
{
var lot = _items.CreateLot(_openCache.GetByName<EquippableItemData>("Disciplined"), _maker, .123f);
_items.Lots[lot].Roles = new List<RoleFill> { new RoleFill { Role = "emission-discipline", Quality = discipline } };
_preparedLots["Disciplined"] = lot;
var ship = Add(float3(0, 0, 0), new[] { "Disciplined" });
Assert.Equal(expected, SensorOf(ship).InterceptFactor, 3);
}
}

View file

@ -22,16 +22,24 @@ public sealed partial class RunStartTests
{
private const float EvDt = 1f / 60f;
// The Duel's guns on a Longinus: the generated Longinus's thrusters (two Large Drive forward, two Talaria on the
// flanks) and power, its Targeting Computer, and the Duel's cockpit, guns, launchers and sensor.
private static ScenarioFit EvLonginus(ScenarioStage stage, string gun = "FastBlast+-", string second = null) => stage.Fit("Longinus",
("Cockpit 2x2", int2(2, 6), ItemRotation.None), ("Core Power", int2(2, 4), ItemRotation.None),
// The Longinus's drive train, fitted by name: its cockpit and power and the generated Longinus's thrusters (two Large Drive
// forward, two Rugged Drive on the flanks).
private static readonly (string design, int2 cell, ItemRotation rotation)[] EvLonginusDrive =
{
("Cockpit 2x2", int2(2, 6), ItemRotation.None), ("Compact Reactor", int2(2, 4), ItemRotation.None),
("Large Drive", int2(1, 0), ItemRotation.Reversed), ("Large Drive", int2(3, 0), ItemRotation.Reversed),
("Talaria", int2(2, 14), ItemRotation.CounterClockwise), ("Talaria", int2(3, 14), ItemRotation.Clockwise),
("GT 3K", int2(0, 5), ItemRotation.None), ("GT 3K", int2(5, 5), ItemRotation.None), (gun, int2(1, 8), ItemRotation.None),
(second ?? gun, int2(4, 8), ItemRotation.None), ("Iapyx", int2(2, 2), ItemRotation.CounterClockwise), ("Iapyx", int2(3, 2), ItemRotation.Clockwise),
("not if i see you first", int2(3, 10), ItemRotation.None), ("PotaT+-", int2(1, 6), ItemRotation.None),
("Targeting Computer", int2(1, 7), ItemRotation.None), ("Store-All Plus", int2(2, 8), ItemRotation.None));
("Rugged Drive", int2(2, 14), ItemRotation.CounterClockwise), ("Rugged Drive", int2(3, 14), ItemRotation.Clockwise),
};
// The Duel's guns on a Longinus: the drive train above, its Targeting Computer, and the Duel's guns, launchers and sensor.
private static ScenarioFit EvLonginus(ScenarioStage stage, string gun = "Cell Blaster", string second = null) => stage.Fit("Longinus",
EvLonginusDrive.Concat(new (string design, int2 cell, ItemRotation rotation)[]
{
("Guided Missile Launcher", int2(0, 5), ItemRotation.None), ("Guided Missile Launcher", int2(5, 5), ItemRotation.None), (gun, int2(1, 8), ItemRotation.None),
(second ?? gun, int2(4, 8), ItemRotation.None), ("Radiator", int2(2, 2), ItemRotation.CounterClockwise), ("Radiator", int2(3, 2), ItemRotation.Clockwise),
("Compact Sensor", int2(3, 10), ItemRotation.None), ("Capacitor", int2(1, 6), ItemRotation.None),
("Targeting Computer", int2(1, 7), ItemRotation.None), ("Cargo Bay", int2(2, 8), ItemRotation.None)
}).ToArray());
// The catalog's two generated ships, far apart in the fixture arena, at the fixture seed.
private (Zone arena, Ship longinus, Ship djinni) EvFleet()
@ -52,6 +60,25 @@ public sealed partial class RunStartTests
return (arena, longinus, djinni);
}
// The two ships the flight tests measure, fitted by name and far apart in the fixture arena: EvDjinni's eight Talaria
// and the Longinus's drive train (EvLonginusDrive: two Large Drives and two Talaria). Neither follows the catalog's census: the generator
// draws from the run's item stream, so a catalog cut would change which gear a generated hull carried (sensor-catalog h1).
private (Zone arena, Ship longinus, Ship djinni) EvFitted()
{
Ship longinus = null, djinni = null;
var scenario = new Scripted(false, stage =>
{
stage.Player(stage.Bare("Djinni"), float2(-50000, -50000));
djinni = stage.Place(EvDjinni(stage), float2(-10000, -30000), facing: float2(0, 1)) as Ship;
longinus = stage.Place(stage.Fit("Longinus", EvLonginusDrive), float2(-30000, -30000), facing: float2(0, 1)) as Ship;
});
var (_, arena, _, failures) = Launch(scenario, Inputs(() => GalaxySeed));
Assert.True(failures.Count == 0, string.Join("; ", failures));
Assert.NotNull(longinus);
Assert.NotNull(djinni);
return (arena, longinus, djinni);
}
// Idle long enough for stats and power to reach their idle state, then at rest, facing +y,
// and, after three seconds of coasting, with nothing observed: the track forgets on its own.
private static void EvSettle(Ship ship)
@ -269,10 +296,15 @@ public sealed partial class RunStartTests
return (Half(float2(1, 0)), Half(float2(0, 1)));
}
// Each factor is fitted to its own ship's fleet fit: reach over measured motion. Djinni: 1.69 nose-on and 1.31 broadside at
// the last measurement, each with about 4% to spare. Longinus broadside: 1.23 (reach 12.74 over measured 10.40) with
// about 3.5% to spare, so an inflation of its envelope of 4% or more breaks its half.
private const float DjinniNoseOnFactor = 1.75f, DjinniBroadsideFactor = 1.36f, LonginusBroadsideFactor = 1.27f;
[Fact]
public void ReachIsWhatTheShipCanDo()
{
var (_, longinus, djinni) = EvFleet();
var (_, longinus, djinni) = EvFitted();
const float window = .5f;
var results = new List<(string name, (float noseOn, float broadside) reach, (float noseOn, float broadside) allocated, (float noseOn, float broadside) measured)>();
foreach (var (name, ship) in new[] { ("longinus", longinus), ("djinni", djinni) })
@ -288,10 +320,12 @@ public sealed partial class RunStartTests
}
// The envelope's reach is the capability and the measured motion is the best of fifteen fixed control policies, so
// the reach covers it: no more than 10% below it.
// The Djinni's measured motion sits further below its reach (+38% nose-on, +26% broadside at the last measurement):
// its strafers are off-axis and the envelope, summed from what each thruster can push, does not model that. Its
// allocator holds the whole box (its allocated reach is the envelope's), so the allocated reach says nothing more
// about it. The bound still pins that the reach covers what the ship does.
// The Djinni's measured motion sits further below its reach (reach 1.69 times the measured nose-on and 1.31 times the broadside at the last measurement): its strafers are off-axis and the
// envelope, summed from what each thruster can push, does not model that. Its allocator holds the whole box (its
// allocated reach is within 8% of the envelope's), so the allocated reach moves with the reach and bounds nothing.
// The ceiling is therefore the measured motion, which no function of Reach produces, times the factor the fitted
// Djinni shows with about 4% to spare (DjinniNoseOnFactor, DjinniBroadsideFactor): a reach scaled by 1.1 or more
// breaks it, however the allocated reach moves.
// The Longinus's allocator holds the heading and pays for the drive torque out of the flank thrusters (ruling
// allocator-divergence-accepted), so the envelope's box support overstates what a controlled flight spends. Its
// measured motion is bounded by the reach of the push the allocator itself gives it on each half-axis, from the
@ -300,8 +334,8 @@ public sealed partial class RunStartTests
{
if (name == "djinni")
{
Assert.InRange(reach.noseOn, measured.noseOn * .9f, measured.noseOn * 1.6f);
Assert.InRange(reach.broadside, measured.broadside * .9f, measured.broadside * 1.6f);
Assert.InRange(reach.noseOn, measured.noseOn * .9f, measured.noseOn * DjinniNoseOnFactor);
Assert.InRange(reach.broadside, measured.broadside * .9f, measured.broadside * DjinniBroadsideFactor);
}
else
{
@ -311,7 +345,7 @@ public sealed partial class RunStartTests
// with other rolls). The ceiling is that, from the columns
// the allocator solves with, not an open bound: an envelope inflated by a factor (doubled: 2.7 and 2.3) breaks it.
Assert.InRange(reach.noseOn, measured.noseOn * .9f, allocated.noseOn * 1.5f);
Assert.InRange(reach.broadside, measured.broadside * .9f, allocated.broadside * 1.2f);
Assert.InRange(reach.broadside, measured.broadside * .9f, measured.broadside * LonginusBroadsideFactor);
Assert.InRange(measured.noseOn, allocated.noseOn * .9f, allocated.noseOn * 1.15f);
Assert.InRange(measured.broadside, allocated.broadside * .85f, allocated.broadside * 1.15f);
}
@ -349,7 +383,7 @@ public sealed partial class RunStartTests
var settings = _items.GameplaySettings;
var thrusters = longinus.GetBehaviors<Thruster>().Where(t => t.Item.Active.Value).ToList();
var largeDrives = thrusters.Where(t => t.Item.Data.Name == "Large Drive").ToList();
var flanks = thrusters.Where(t => t.Item.Data.Name == "Talaria").ToList();
var flanks = thrusters.Where(t => t.Item.Data.Name == "Rugged Drive").ToList();
Assert.Equal(2, largeDrives.Count);
Assert.Equal(2, flanks.Count);
@ -362,7 +396,7 @@ public sealed partial class RunStartTests
var forward = largeDrives.Sum(t => t.Thrust) / mass;
Assert.InRange(envelope.Forward, forward * .99f, forward * 1.01f);
Assert.Equal(0f, envelope.Reverse);
// One Talaria pushes each way, and each has its own lot's thrust: the sides are the two flanks' accelerations.
// One Rugged Drive pushes each way, and each has its own lot's thrust: the sides are the two flanks' accelerations.
var flankAccelerations = flanks.Select(t => t.Thrust / mass).OrderBy(a => a).ToArray();
var sides = new[] { envelope.Left, envelope.Right }.OrderBy(a => a).ToArray();
Assert.InRange(sides[0], flankAccelerations[0] * .99f, flankAccelerations[0] * 1.01f);
@ -580,17 +614,17 @@ public sealed partial class RunStartTests
public Weapon Gun, Laser, GunnerLaser;
}
// The target's fit, written out: the Djinni's own hardpoints filled with the Talaria it is generated with, its
// The target's fit, written out: the Djinni's own hardpoints filled with the Rugged Drive it is generated with, its
// reactor, cockpit and radiators. What the evasion tests price is this ship's strafing, not whatever the generator
// rolls for it from the galaxy.
private static ScenarioFit EvDjinni(ScenarioStage stage) => stage.Fit("Djinni",
("Cockpit 2x2", int2(6, 3), ItemRotation.None), ("Core Power", int2(6, 11), ItemRotation.None),
("Talaria", int2(6, 0), ItemRotation.Reversed), ("Talaria", int2(5, 1), ItemRotation.Reversed), ("Talaria", int2(7, 1), ItemRotation.Reversed),
("Talaria", int2(4, 4), ItemRotation.CounterClockwise), ("Talaria", int2(4, 11), ItemRotation.CounterClockwise),
("Talaria", int2(9, 4), ItemRotation.Clockwise), ("Talaria", int2(9, 11), ItemRotation.Clockwise),
("Talaria", int2(6, 14), ItemRotation.None),
("Iapyx", int2(1, 4), ItemRotation.Reversed), ("Iapyx", int2(3, 1), ItemRotation.Reversed),
("Iapyx", int2(9, 1), ItemRotation.Reversed), ("Iapyx", int2(11, 4), ItemRotation.Reversed));
("Cockpit 2x2", int2(6, 3), ItemRotation.None), ("Compact Reactor", int2(6, 11), ItemRotation.None),
("Rugged Drive", int2(6, 0), ItemRotation.Reversed), ("Rugged Drive", int2(5, 1), ItemRotation.Reversed), ("Rugged Drive", int2(7, 1), ItemRotation.Reversed),
("Rugged Drive", int2(4, 4), ItemRotation.CounterClockwise), ("Rugged Drive", int2(4, 11), ItemRotation.CounterClockwise),
("Rugged Drive", int2(9, 4), ItemRotation.Clockwise), ("Rugged Drive", int2(9, 11), ItemRotation.Clockwise),
("Rugged Drive", int2(6, 14), ItemRotation.None),
("Radiator", int2(1, 4), ItemRotation.Reversed), ("Radiator", int2(3, 1), ItemRotation.Reversed),
("Radiator", int2(9, 1), ItemRotation.Reversed), ("Radiator", int2(11, 4), ItemRotation.Reversed));
private EvRange EvRangeLaunch()
{
@ -598,9 +632,9 @@ public sealed partial class RunStartTests
var scenario = new Scripted(false, stage =>
{
stage.Player(stage.Bare("Djinni"), float2(-50000, -50000));
gunner = stage.Place(EvLonginus(stage, "FastBlast+-", "ColdFire"), float2(0, 0), facing: float2(0, 1)) as Ship;
gunner = stage.Place(EvLonginus(stage, "Cell Blaster", "Long Laser"), float2(0, 0), facing: float2(0, 1)) as Ship;
target = stage.Place(EvDjinni(stage), float2(0, 200), facing: float2(0, 1)) as Ship;
lasing = stage.Place(EvLonginus(stage, "ColdFire"), float2(0, 400), facing: float2(0, -1)) as Ship;
lasing = stage.Place(EvLonginus(stage, "Long Laser"), float2(0, 400), facing: float2(0, -1)) as Ship;
});
var (_, arena, _, failures) = Launch(scenario, Inputs(() => GalaxySeed));
Assert.True(failures.Count == 0, string.Join("; ", failures));
@ -787,7 +821,7 @@ public sealed partial class RunStartTests
[Fact]
public void TheThrustersReadLiveThrust()
{
var (_, _, djinni) = EvFleet();
var (_, _, djinni) = EvFitted();
EvSettle(djinni);
djinni.Update(EvDt);
var thrusters = djinni.GetBehaviors<Thruster>().ToList();

View file

@ -367,8 +367,8 @@ public sealed partial class RunStartTests
{
("Point Defense Gun", 40f, 80000, 60f, WeaponModifiers.RapidFire, (1.5f, 4f), (1f, 1f), (300f, 550f), (.06f, .025f), (1f, .3f),
(1100f, 1600f), (.4f, .2f), (40f, 15f), (400f, 150f), true, 250, 3f),
("Point Defense Laser", 30f, 110000, 30f, PdDesign("Spectra").WeaponModifiers, (5f, 12f), (1f, 1f), (400f, 750f), (.2f, .1f), (.05f, 0f),
(0f, 0f), (6f, 10f), (300f, 150f), (300f, 100f), false, PdDesign("Spectra").Behaviors.OfType<InstantWeaponData>().Single().MagazineSize, PdDesign("Spectra").Behaviors.OfType<InstantWeaponData>().Single().ReloadTime),
("Point Defense Laser", 30f, 110000, 30f, PdDesign("Light Laser").WeaponModifiers, (5f, 12f), (1f, 1f), (400f, 750f), (.2f, .1f), (.05f, 0f),
(0f, 0f), (6f, 10f), (300f, 150f), (300f, 100f), false, PdDesign("Light Laser").Behaviors.OfType<InstantWeaponData>().Single().MagazineSize, PdDesign("Light Laser").Behaviors.OfType<InstantWeaponData>().Single().ReloadTime),
("Flak Gun", 120f, 180000, 80f, WeaponModifiers.Cluster, (30f, 70f), (6f, 8f), (350f, 800f), (.6f, .35f), (4f, 2f),
(900f, 1300f), (1f, .5f), (300f, 150f), (800f, 300f), true, 40, 4f),
};
@ -449,20 +449,20 @@ public sealed partial class RunStartTests
return FireControl.TrackingRate(range.Gun, range.Gunner);
}
var pd = FireControl.PMount(omega, RateOf("Point Defense Gun"));
var clearPath = FireControl.PMount(omega, RateOf("ClearPath"));
var clearPath = FireControl.PMount(omega, RateOf("Light Machine Gun"));
Assert.True(pd >= .75f, $"the PD gun follows a speed demon: {pd}");
Assert.True(clearPath <= .25f, $"the machine gun does not: {clearPath}");
}
// Data check, not a behaviour test: ruling plight-shape, plight is one wide, two high and fits a Longinus Energy hardpoint.
// Data check, not a behaviour test: ruling plight-shape, the Lightning Projector is one wide, two high and fits a Longinus Energy hardpoint.
[Fact]
public void PlightHasItsRuledShape()
{
var plight = _cache.GetAll<WeaponItemData>().Single(w => w.Name == "plight");
Assert.Equal(1, plight.Shape.Width);
Assert.Equal(2, plight.Shape.Height);
Assert.True(plight.Shape.Cells[0, 0] && plight.Shape.Cells[0, 1], "both cells are occupied");
var projector = _cache.GetAll<WeaponItemData>().Single(w => w.Name == "Lightning Projector");
Assert.Equal(1, projector.Shape.Width);
Assert.Equal(2, projector.Shape.Height);
Assert.True(projector.Shape.Cells[0, 0] && projector.Shape.Cells[0, 1], "both cells are occupied");
var longinus = _cache.GetAll<HullData>().Single(h => h.Name == "Longinus");
Assert.Contains(longinus.Hardpoints, hardpoint => hardpoint.Type == HardpointType.Energy && hardpoint.Takes(plight));
Assert.Contains(longinus.Hardpoints, hardpoint => hardpoint.Type == HardpointType.Energy && hardpoint.Takes(projector));
}
}

View file

@ -0,0 +1,319 @@
using System;
using System.IO;
using CultMath;
using GameCult.Caching;
using Xunit;
using static CultMath.math;
using float2 = CultMath.float2;
using float3 = CultMath.float3;
// The global flow as a world fact (campaign aetheria-fauna, cut fauna-flow-field; ruling sim-knows-the-flow; target
// invariants flow-one-owner and flow-step-free). Every test reads Zone.Flow / Zone.FlowScroll, the path a fauna
// class will read, from zones built the way the other ServerShared tests build them.
public sealed class FlowFieldTests : IDisposable
{
private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-flow-" + Guid.NewGuid().ToString("N"));
private readonly CultCache _cache;
private readonly ItemManager _items;
public FlowFieldTests()
{
Directory.CreateDirectory(_root);
_cache = AetheriaStores.Open(Path.Combine(_root, "flow.cc"), catalogWritable: true);
_cache.Upsert(new VerseGrammar { Revision = 1 });
_cache.FlushAsync().Wait();
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 = .1f, TargetGearInfoThreshold = .8f,
FiringArc = 170, CommitHorizon = .5f, SchematicCellSize = 2f
};
_items = new ItemManager(_cache, new ProvenanceLedger(), settings, _ => { });
}
public void Dispose()
{
_cache.Dispose();
Directory.Delete(_root, true);
}
private static FlowSettings Flow(float amplitude = 15f, float slide = 0f, float swirl = 0f) => new FlowSettings
{
GlobalScale = 512f, GlobalAmplitude = amplitude, GlobalScrollSpeed = .025f, Period = 8f,
SlopeAmplitude = slide, SwirlAmplitude = swirl
};
// A zone at `time` (the pack's clock, as a saved zone restores it), flat unless `depth` digs the zone's own well.
private Zone ZoneWith(FlowSettings flow, double time = 0, float depth = 0f) => new Zone(_items,
new PlanetSettings { Flow = flow, ZoneDepth = depth, ZoneDepthExponent = 2f },
new ZonePack { Time = time }, new GalaxyZone { Name = "Flow Zone", Owner = null }, null);
private static readonly float3[] Probes =
{
new float3(0, 0, 0), new float3(37.5f, 12f, -80.25f), new float3(-410f, -30f, 125f),
new float3(1234f, 50f, 987f), new float3(-2501f, 7f, -3333f), new float3(9000f, 90f, -4000f)
};
private static void AssertClose(float3 expected, float3 actual, float tolerance = 1e-3f)
{
Assert.True(abs(expected.x - actual.x) <= tolerance && abs(expected.y - actual.y) <= tolerance &&
abs(expected.z - actual.z) <= tolerance, $"expected {expected} but flow was {actual}");
}
[Fact]
public void ScrollIsSpeedTimesZoneTime()
{
// The flow at zone time t is the flow at time 0 of a field moved along y by -scale * speed * t, so the
// noise scrolls by speed x zone time and nothing else (an odd t keeps the shift off a whole field period).
const double t = 7.0;
var flow = Flow();
var later = ZoneWith(flow, t);
var start = ZoneWith(flow, 0);
var shift = flow.GlobalScale * flow.GlobalScrollSpeed * (float) t;
foreach (var p in Probes)
AssertClose(start.Flow(new float3(p.x, p.y - shift, p.z)), later.Flow(p));
Assert.Equal(flow.GlobalScrollSpeed * t, later.FlowScroll.x, 6);
Assert.Equal(float2(0f, 0f), start.FlowScroll);
}
[Fact]
public void FlowDoesNotDependOnStepSize()
{
var fine = ZoneWith(Flow());
var coarse = ZoneWith(Flow());
for (var i = 0; i < 60; i++) fine.Update(1f / 60f);
for (var i = 0; i < 7; i++) coarse.Update(1f / 7f);
Assert.Equal(1.0, fine.Time, 4);
Assert.Equal(1.0, coarse.Time, 4);
foreach (var p in Probes) AssertClose(fine.Flow(p), coarse.Flow(p));
Assert.Equal(fine.FlowScroll.x, coarse.FlowScroll.x, 5);
Assert.Equal(fine.FlowScroll.y, coarse.FlowScroll.y, 5);
// The flow moved: a scroll of 0.025 per second is a different field from the start, somewhere.
var start = ZoneWith(Flow());
Assert.Contains(Probes, p => length(start.Flow(p) - fine.Flow(p)) > .05f);
}
[Fact]
public void ZeroAmplitudesGiveZeroFlowAndNoNaN()
{
// All amplitudes zero (and a zero scale a bad config could carry): no term runs, so nothing divides by zero.
var none = ZoneWith(new FlowSettings());
foreach (var p in Probes) Assert.Equal(float3.zero, none.Flow(p));
// A zone built from default PlanetSettings has no flow, the baseline every other ServerShared test relies on.
var defaults = new Zone(_items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Default", Owner = null }, null);
foreach (var p in Probes) Assert.Equal(float3.zero, defaults.Flow(p));
// A term with zero amplitudes is skipped outright: not even a gradient that cannot be normalised reaches it.
var unusable = float2(float.PositiveInfinity, float.NaN);
Assert.Equal(float3.zero, FlowField.Slope(new FlowSettings(), unusable));
// A flat zone has a zero gradient; swirl and slide are zero there, never NaN.
var flat = ZoneWith(Flow(amplitude: 0f, slide: 1f, swirl: 1f));
foreach (var p in Probes)
{
var f = flat.Flow(p);
Assert.False(float.IsNaN(f.x) || float.IsNaN(f.y) || float.IsNaN(f.z), "zero gradient gave NaN");
Assert.Equal(float3.zero, f);
}
}
[Fact]
public void SlopeTermSwirlsAndSlidesOnTheGradient()
{
// The zone's own well is deepest at the origin: downhill at p is toward it.
var at = new float3(500f, 3f, 300f);
var downhill = normalize(float2(-at.x, -at.z));
var slide = ZoneWith(Flow(amplitude: 0f, slide: 1.5f), depth: 64f).Flow(at);
Assert.Equal(0f, slide.y, 4);
Assert.Equal(1.5f * downhill.x, slide.x, 2);
Assert.Equal(1.5f * downhill.y, slide.z, 2);
// Swirl is perpendicular to downhill, and has a handedness: (down.y, -down.x).
var swirl = ZoneWith(Flow(amplitude: 0f, swirl: 2f), depth: 64f).Flow(at);
Assert.Equal(0f, swirl.y, 4);
Assert.Equal(2f * downhill.y, swirl.x, 2);
Assert.Equal(-2f * downhill.x, swirl.z, 2);
Assert.Equal(0f, dot(float2(swirl.x, swirl.z), downhill), 2);
Assert.Equal(2f, length(float2(swirl.x, swirl.z)), 2);
}
[Fact]
public void ZoneFlowReadsItsPlanetSettings()
{
var one = ZoneWith(Flow(amplitude: 15f), 3.0);
var two = ZoneWith(Flow(amplitude: 30f), 3.0);
foreach (var p in Probes) AssertClose(one.Flow(p) * 2f, two.Flow(p));
// The flow is live (the origin is a legitimate zero of the field, so it is not every probe).
Assert.Contains(Probes, p => length(one.Flow(p)) > 1f);
}
[Fact]
public void ZoneFlowIsTheLawAtTheScrollTheShaderGets()
{
// Zone.Flow and the lowered scroll are one zone-time value: the flow at p is the law evaluated at the zone's
// own FlowScroll, after any run of steps (a flow that ran ahead of or behind the shader's scroll differs here).
var zone = ZoneWith(Flow(), 3.25);
for (var step = 0; step < 90; step++)
{
zone.Update(1f / 60f);
foreach (var p in Probes) AssertClose(FlowField.Global(Flow(), p, zone.FlowScroll), zone.Flow(p), 1e-4f);
}
}
[Fact]
public void PausedSimFreezesTheFlowPhases()
{
// Presenters take their cycle phase from zone time: a zone that does not advance does not move them, and a
// zone that does moves them by dt / period (mod 1).
const float period = 8f;
var zone = ZoneWith(Flow(), 5.0);
var before = zone.CyclePhase(period);
var scroll = zone.FlowScroll;
zone.Update(0f);
Assert.Equal(before, zone.CyclePhase(period));
Assert.Equal(scroll, zone.FlowScroll);
zone.Update(2f);
Assert.Equal(frac(before + 2f / period), zone.CyclePhase(period), 5);
Assert.InRange(zone.CyclePhase(period), 0f, .9999999f);
}
[Theory]
[InlineData(1)]
[InlineData(10)]
public void ScrollKeepsAdvancingAtDaysOfZoneTime(int days)
{
// Zone time persists and only grows. A float of speed x time stops resolving a 1/60 s step after days; the
// phases the shader gets stay in [0, 1) and advance by speed x dt on every step.
const double dt = 1.0 / 60.0;
var flow = Flow();
var zone = ZoneWith(flow, days * 86400.0 + .1);
var previous = zone.FlowScroll;
for (var step = 0; step < 30; step++)
{
zone.Update((float) dt);
var now = zone.FlowScroll;
Assert.InRange(now.x, 0f, .9999999f);
Assert.InRange(now.y, 0f, .9999999f);
var dx = now.x - previous.x;
var dy = now.y - previous.y;
if (dx < -.5f) dx += 1f;
if (dy < -.5f) dy += 1f;
var expected = flow.GlobalScrollSpeed * dt;
Assert.InRange((double) dx, expected - 5e-7, expected + 5e-7);
Assert.InRange((double) dy, expected * 1.61803398875 - 5e-7, expected * 1.61803398875 + 5e-7);
previous = now;
}
}
// The law as Volumetric.cginc spelled it before the per-octave fold: Tri3D(p) with p * Golden for the second
// octave and p = pos / scale - (0, speed * t, 0), in double with the unfolded scroll. The oracle the fold must
// agree with; it shares no code with FlowField.
// The origin is a degenerate point of the field (a zero cross product), where no law can be compared.
private static readonly float3[] OffOrigin = Probes[1..];
private static double OTri(double x) => Math.Abs(x - Math.Floor(x) - .5);
private static double[] OTri3(double x, double y, double z) => new[] { OTri(z + OTri(y)), OTri(z + OTri(x)), OTri(y + OTri(x)) };
private static double[] ONormalize(double[] v)
{
var l = Math.Sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
return new[] { v[0] / l, v[1] / l, v[2] / l };
}
private static double[] UnfoldedLaw(FlowSettings f, float3 p, double t)
{
double g = 1.61803398875f;
var s = (double) f.GlobalScrollSpeed * t;
double x = p.x / (double) f.GlobalScale, y = p.y / (double) f.GlobalScale - s, z = p.z / (double) f.GlobalScale;
var t1 = ONormalize(OTri3(x, y, z));
var t2 = ONormalize(OTri3(x * g, y * g, z * g));
var c = new[] { t1[1] * t2[2] - t1[2] * t2[1], t1[2] * t2[0] - t1[0] * t2[2], t1[0] * t2[1] - t1[1] * t2[0] };
return new[] { c[0] * f.GlobalAmplitude, c[1] * f.GlobalAmplitude * .5, c[2] * f.GlobalAmplitude };
}
private static double Distance(float3 a, double[] b) =>
Math.Sqrt((a.x - b[0]) * (a.x - b[0]) + (a.y - b[1]) * (a.y - b[1]) + (a.z - b[2]) * (a.z - b[2]));
[Fact]
public void FoldedScrollIsTheUnfoldedLawAtAnyAge()
{
// fold-law: the phase each octave gets is the unfolded speed x time (second octave: x Golden), folded once in
// double. Computing the second from the folded first (frac(frac(s) x Golden)) agrees below 40 s and nowhere after.
var f = Flow();
foreach (var t in new[] { 0.0, 3.1, 39.99, 40.0, 40.01, 86400.0, 864000.0 + .3, 8640000.0 + .7 })
foreach (var p in OffOrigin)
Assert.True(Distance(FlowField.Global(f, p, FlowField.Scroll(f, t)), UnfoldedLaw(f, p, t)) / f.GlobalAmplitude < 5e-5,
$"t={t} p={p}");
}
[Fact]
public void NoJumpWhereAPhaseWraps()
{
// Each octave's phase wraps at its own times (the first every 40 s of zone time at speed .025): across a wrap
// the flow moves by what the unfolded law moves, so nothing jumps.
var f = Flow();
double speed = f.GlobalScrollSpeed, golden = 1.61803398875f;
const double h = 1.0 / 120.0;
foreach (var (octave, cycles) in new[] { (0, 1.0), (0, 21600.0), (1, 1.0), (1, 34950.0) })
{
var t = octave == 0 ? cycles / speed : cycles / (speed * golden);
var before = FlowField.Scroll(f, t - h);
var after = FlowField.Scroll(f, t + h);
Assert.True(octave == 0 ? before.x > .9f && after.x < .1f : before.y > .9f && after.y < .1f,
$"octave {octave} cycles {cycles}: the probe times do not straddle a wrap");
foreach (var p in OffOrigin)
{
var folded = FlowField.Global(f, p, after) - FlowField.Global(f, p, before);
var a = UnfoldedLaw(f, p, t + h);
var b = UnfoldedLaw(f, p, t - h);
Assert.True(Distance(folded, new[] { a[0] - b[0], a[1] - b[1], a[2] - b[2] }) / f.GlobalAmplitude < 1e-4,
$"octave {octave} cycles {cycles} p={p}");
}
}
}
[Theory]
[InlineData(10)]
[InlineData(100)]
public void CycleKeepsAdvancingAtDays(int days)
{
// The cycle phase takes zone time in double: a float zone time at 10 days (8.6e5 s) resolves 0.06 s and at
// 100 days 1 s, so a 1/60 s step would not move the phase.
foreach (var period in new[] { 8f, .25f })
{
const double dt = 1.0 / 60.0;
var time = days * 86400.0 + .1;
var previous = FlowField.Cycle(time, period);
for (var step = 0; step < 30; step++)
{
time += dt;
var now = FlowField.Cycle(time, period);
var advance = now - previous;
if (advance < -.5f) advance += 1f;
Assert.InRange((double) advance, dt / period - 1e-5, dt / period + 1e-5);
previous = now;
}
}
}
[Fact]
public void PhasesAreStrictlyBelowOne()
{
// A phase just below an integer rounds to 1f in a float cast; the contract is [0, 1), so it reads 0 instead
// (1 is 0 modulo 1: the flow there is the flow at 0).
var f = Flow();
double speed = f.GlobalScrollSpeed, golden = 1.61803398875f;
foreach (var gap in new[] { 1e-9, 1e-12 })
{
var first = FlowField.Scroll(f, (1.0 - gap) / speed);
var second = FlowField.Scroll(f, (2.0 - gap) / (speed * golden));
Assert.InRange(first.x, 0f, .9999999f);
Assert.InRange(second.y, 0f, .9999999f);
Assert.InRange(FlowField.Cycle(8.0 * (1.0 - gap), 8f), 0f, .9999999f);
}
}
}

View file

@ -0,0 +1,240 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
using Xunit;
// AetherDb's generic-designs command (aetheria-release, cut generic-design-names), run on a scratch copy of the shipped
// catalog, which already carries the applied result: each case first puts a few records back to their old shape.
public sealed class GenericDesignsCommandTests : IDisposable
{
private readonly string _root = Path.Combine(Path.GetTempPath(), "generic-designs-command-" + Guid.NewGuid().ToString("N"));
private string CatalogPath => Path.Combine(_root, "GameData", "Aetheria.cc");
public GenericDesignsCommandTests()
{
Directory.CreateDirectory(Path.Combine(_root, "GameData"));
Directory.CreateDirectory(Path.Combine(_root, "Assets", "Resources"));
var shipped = AetherDb.FindRoot();
File.Copy(Path.Combine(shipped, "GameData", "Aetheria.cc"), CatalogPath);
File.Copy(Path.Combine(shipped, "Assets", "Resources", "Settings.asset"), Path.Combine(_root, "Assets", "Resources", "Settings.asset"));
}
public void Dispose() => Directory.Delete(_root, true);
private void Edit(Action<AetherDb> edit)
{
var db = AetherDb.Open(catalogWritable: true, root: _root);
try { edit(db); }
finally { db.Cache.Dispose(); }
}
private T Read<T>(Func<AetherDb, T> read)
{
var db = AetherDb.Open(root: _root);
try { return read(db); }
finally { db.Cache.Dispose(); }
}
private static void Save(AetherDb db, EquippableItemData design) =>
db.Cache.Commit(batch => batch.Upsert(design.GetType(), design, db.Cache.RefOf(design).Key));
private static void Save(AetherDb db, FactionProductData product) =>
db.Cache.Commit(batch => batch.Upsert(typeof(FactionProductData), product, db.Cache.RefOf(product).Key));
private static EquippableItemData DesignNamed(AetherDb db, string name) =>
db.Cache.GetAll<EquippableItemData>().Single(d => d.Name == name);
private static FactionProductData ProductNamed(AetherDb db, string name) =>
db.Cache.GetAll<FactionProductData>().Single(p => p.Name == name);
[Fact]
public void An_applied_catalog_is_left_alone_by_a_dry_run_and_by_apply()
{
var before = File.ReadAllBytes(CatalogPath);
Assert.Equal(0, Program.GenericDesigns(apply: false, root: _root));
Assert.Equal(before, File.ReadAllBytes(CatalogPath));
Assert.Equal(0, Program.GenericDesigns(apply: true, root: _root));
Assert.Equal(before, File.ReadAllBytes(CatalogPath));
}
[Fact]
public void A_dry_run_writes_nothing_and_apply_restores_both_records()
{
var (designText, productText, brandedDesignText, rowText) = Read(db => (DesignNamed(db, "Light Machine Gun").Description,
ProductNamed(db, "Hammerfall").Description, DesignNamed(db, "Autocannon").Description, ProductNamed(db, "Skiron").Description));
Edit(db =>
{
var design = DesignNamed(db, "Light Machine Gun");
design.Name = "ClearPath";
design.Description = "Defend your precious cargo.";
Save(db, design);
var product = ProductNamed(db, "Hammerfall");
product.Name = "Autocannon";
product.Description = "";
Save(db, product);
var branded = DesignNamed(db, "Autocannon");
branded.Description = "";
Save(db, branded);
var row = ProductNamed(db, "Skiron");
row.Description = "";
Save(db, row);
});
var reverted = File.ReadAllBytes(CatalogPath);
Assert.Equal(0, Program.GenericDesigns(apply: false, root: _root));
Assert.Equal(reverted, File.ReadAllBytes(CatalogPath));
Assert.Equal(0, Program.GenericDesigns(apply: true, root: _root));
Read(db =>
{
Assert.Equal(designText, DesignNamed(db, "Light Machine Gun").Description);
Assert.DoesNotContain(db.Cache.GetAll<EquippableItemData>(), d => d.Name == "ClearPath");
Assert.Equal(productText, ProductNamed(db, "Hammerfall").Description);
Assert.Equal(brandedDesignText, DesignNamed(db, "Autocannon").Description);
Assert.Equal(rowText, ProductNamed(db, "Skiron").Description);
Assert.DoesNotContain(db.Cache.GetAll<FactionProductData>(), p => p.Name == "Autocannon" && db.Cache.Get(p.Manufacturer)?.ShortName == "Zhestokost");
return 0;
});
}
// Re-spell every record's payload in a longer, equally valid MessagePack form (an array16 header for the fixarray one). The
// catalog then holds bytes no re-encode through the current types would reproduce, so a write that re-encodes records it did
// not author shows as changed bytes; a write that lands onto the file as it is leaves them alone.
private int WidenEveryPayload()
{
var snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(CatalogPath));
var widened = 0;
foreach (var record in snapshot.Records)
{
var payload = record.Payload;
if (payload.Length == 0 || (payload[0] & 0xF0) != 0x90) continue;
record.Payload = new byte[] { 0xDC, 0x00, (byte)(payload[0] & 0x0F) }.Concat(payload.Skip(1)).ToArray();
widened++;
}
File.WriteAllBytes(CatalogPath, CultDocumentMessagePackSerialization.SerializeSnapshot(snapshot));
return widened;
}
private Dictionary<string, CultPersistedRecord> Records() =>
CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(CatalogPath)).Records.ToDictionary(r => r.Key, StringComparer.Ordinal);
[Fact]
public void Apply_writes_only_the_records_it_authors_and_restores_the_rewritten_design_texts()
{
var (largeDriveText, tractorText, smokeText, tractorProductText) = Read(db => (DesignNamed(db, "Large Drive").Description, DesignNamed(db, "Tractor Beam").Description,
DesignNamed(db, "Smoke Proximity").Description, ProductNamed(db, "Space Tractor").Description));
Edit(db =>
{
var drive = DesignNamed(db, "Large Drive");
drive.Description = "Keeps you going and going and going...";
Save(db, drive);
var smoke = DesignNamed(db, "Smoke Proximity");
smoke.Description = "A Spectra that bursts by proximity, blast 8. For scenarios; no one builds it.";
Save(db, smoke);
var tractor = ProductNamed(db, "Space Tractor");
tractor.Description = "It's a tractor. In space.";
Save(db, tractor);
});
Assert.True(WidenEveryPayload() > 100, "the scratch catalog should hold many records in the widened spelling");
var before = Records();
Assert.Equal(0, Program.GenericDesigns(apply: true, root: _root));
var after = Records();
Assert.Equal(before.Count, after.Count);
var changed = before.Keys.Where(key => !before[key].Payload.AsSpan().SequenceEqual(after[key].Payload)).ToArray();
Assert.Equal(3, changed.Length);
foreach (var (key, record) in before.Where(pair => !changed.Contains(pair.Key)))
Assert.True(record.Payload.AsSpan().SequenceEqual(after[key].Payload), "a record the command did not author has changed bytes");
Read(db =>
{
Assert.Equal(largeDriveText, DesignNamed(db, "Large Drive").Description);
Assert.Equal(tractorText, DesignNamed(db, "Tractor Beam").Description);
Assert.Equal(smokeText, DesignNamed(db, "Smoke Proximity").Description);
Assert.Equal(tractorProductText, ProductNamed(db, "Space Tractor").Description);
return 0;
});
}
[Fact]
public void A_generic_name_held_by_another_design_is_refused_and_nothing_is_written()
{
Edit(db =>
{
var cargo = DesignNamed(db, "Cargo Bay");
cargo.Name = "Store-All Plus";
Save(db, cargo);
var flak = DesignNamed(db, "Flak Gun");
flak.Name = "Cargo Bay";
Save(db, flak);
});
var before = File.ReadAllBytes(CatalogPath);
Assert.Throws<InvalidOperationException>(() => Program.GenericDesigns(apply: true, root: _root));
Assert.Equal(before, File.ReadAllBytes(CatalogPath));
}
[Fact]
public void A_brand_already_held_by_another_product_is_refused()
{
Edit(db =>
{
var product = ProductNamed(db, "Hammerfall");
product.Name = "Autocannon";
Save(db, product);
var other = ProductNamed(db, "Wren");
other.Name = "Hammerfall";
Save(db, other);
});
var before = File.ReadAllBytes(CatalogPath);
Assert.Throws<InvalidOperationException>(() => Program.GenericDesigns(apply: true, root: _root));
Assert.Equal(before, File.ReadAllBytes(CatalogPath));
}
[Fact]
public void A_row_whose_old_and_generic_names_are_both_absent_is_refused()
{
Edit(db =>
{
var gun = DesignNamed(db, "Light Machine Gun");
gun.Name = "Neither Name";
Save(db, gun);
});
var before = File.ReadAllBytes(CatalogPath);
Assert.Throws<InvalidOperationException>(() => Program.GenericDesigns(apply: true, root: _root));
Assert.Equal(before, File.ReadAllBytes(CatalogPath));
}
[Fact]
public void A_brand_row_whose_maker_sells_no_product_of_the_design_under_either_name_is_refused()
{
Edit(db =>
{
var product = ProductNamed(db, "Hammerfall");
product.Name = "Neither Name";
Save(db, product);
});
var before = File.ReadAllBytes(CatalogPath);
Assert.Throws<InvalidOperationException>(() => Program.GenericDesigns(apply: true, root: _root));
Assert.Equal(before, File.ReadAllBytes(CatalogPath));
}
[Fact]
public void A_shipped_authoring_note_is_stripped_from_a_product_the_tables_do_not_name()
{
Edit(db =>
{
var product = ProductNamed(db, "LockOn");
product.Description += Program.AuthoringNote;
Save(db, product);
});
Assert.Equal(0, Program.GenericDesigns(apply: true, root: _root));
Read(db =>
{
Assert.EndsWith("target.", ProductNamed(db, "LockOn").Description);
return 0;
});
}
}

View file

@ -17,7 +17,7 @@ public sealed class LaunchSuppressorCatalogTests
internal const string MildName = "Launch Baffle";
// The observer's sensor, named: the reveal readings below are this design's PassiveInfo, so a catalog that gains an earlier
// sensor must not change which one the observer fits.
private const string SensorName = "not if i see you first";
private const string SensorName = "Compact Sensor";
private const float Flash = 1000f;
private const float Tick = .25f; // exact in floats: four ticks are one second

View file

@ -0,0 +1,211 @@
using System.Linq;
using CultMath;
using GameCult.Caching.MessagePack;
using MessagePack;
using Xunit;
using static CultMath.math;
using float3 = CultMath.float3;
// Passive listening gear (ruling sensor-stat-set): an observer with a listener hears an emission at the emitter's own
// range times the listener's Multiple, bearing only. The pinger is the fixture's "Eye" (PingRange 300, intercept
// factor absent so 1), so a sensor hears it at 300 and the "Listener" (Multiple 3) at 900. Every fixture drives the
// production path: Sensor.Execute posts through Entity.Emit and Sense hears, ticking inside Zone.Update.
public sealed partial class ContactRevealTests
{
private static GearData Listener(string name, float multiple)
{
var cell = new Shape(1, 1);
cell[new int2(0, 0)] = true;
return new GearData
{
Name = name, Hardpoint = HardpointType.Tool, Shape = cell, Durability = 10,
MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000,
Behaviors = { new ListenerData { Multiple = Const(multiple) } }
};
}
// ---- AListenerHearsAtItsMultiple ----
[Theory]
[InlineData(899f, true)]
[InlineData(901f, false)]
public void AListenerHearsAtItsMultiple(float distance, bool heard)
{
var p = Add(float3(0, 0, 0), new[] { "Eye" });
var ear = Add(float3(distance, 0, 0), tools: new[] { "Listener" });
var at = PingAt(p);
if (!heard) { Assert.Empty(ear.RevealsOf(p)); return; }
var reveal = Assert.Single(ear.RevealsOf(p));
Assert.Equal(SignatureChannel.Emission, reveal.Channel);
Assert.Equal(at, reveal.Time);
AssertBearing(-1f, 0f, reveal.Bearing); // normalize((P - ear).xz)
Assert.Equal(0f, Track(ear, p)); // bearing only: it builds no track
}
// ---- AListenerAndASensorTakeTheLarger ----
[Theory]
[InlineData(true, 899f, true)]
[InlineData(true, 901f, false)]
[InlineData(false, 299f, true)]
[InlineData(false, 301f, false)]
public void AListenerAndASensorTakeTheLarger(bool listenerActive, float distance, bool heard)
{
var p = Add(float3(0, 0, 0), new[] { "Eye" });
var both = Add(float3(distance, 0, 0), new[] { "Eye" }, new[] { "Listener" }); // a sum would hear at 1200
var listener = both.Equipment.Single(i => i.Behaviors.Any(b => b is Listener));
listener.Enabled.Value = listenerActive;
PingAt(p);
Assert.Equal(heard ? 1 : 0, both.RevealsOf(p).Count());
}
// ---- AnInactiveListenerHearsNothing ----
[Fact]
public void AnInactiveListenerHearsNothing()
{
var p = Add(float3(0, 0, 0), new[] { "Eye" });
var ear = Add(float3(100, 0, 0), tools: new[] { "Listener" });
ear.Equipment.Single(i => i.Behaviors.Any(b => b is Listener)).Enabled.Value = false;
PingAt(p);
Assert.Empty(ear.RevealsOf(p));
}
// ---- AConsumableListenerHearsAtItsMultiple ----
// The Earpiece is a consumable hosting a Listener (Multiple 3): an observer with it active hears the "Eye" at 900, the
// same as with the gear; with it not yet activated it has no instrument at all.
[Theory]
[InlineData(true, 899f, true)]
[InlineData(true, 901f, false)]
[InlineData(false, 100f, false)]
public void AConsumableListenerHearsAtItsMultiple(bool activated, float distance, bool heard)
{
var p = Add(float3(0, 0, 0), new[] { "Eye" });
var ear = Add(float3(distance, 0, 0));
if (activated)
{
var data = _openCache.GetByName<ConsumableItemData>("Earpiece");
ear.ActivateConsumable(Assert.IsType<ConsumableItem>(_items.CreateInstance(_items.CreateLot(data, _maker, .5f))));
Assert.Single(ear.FindActiveConsumable(data).Behaviors.OfType<Listener>()); // fixture: the consumable hosts it
}
PingAt(p);
Assert.Equal(heard ? 1 : 0, ear.RevealsOf(p).Count());
}
// ---- Stacking: HearingMultiple is the largest of 1 (an active sensor) and each ACTIVE listener's Multiple ----
// The pinger's range is 300, so a hearer at 300 x M - 1 hears and one at 300 x M + 1 does not. The largest listener
// is never first or last, so a sum, a first-wins and a last-wins each hear at the wrong distance.
private void Activate(Ship ship, string consumable)
{
var data = _openCache.GetByName<ConsumableItemData>(consumable);
ship.ActivateConsumable(Assert.IsType<ConsumableItem>(_items.CreateInstance(_items.CreateLot(data, _maker, .5f))));
}
[Theory]
[InlineData(1499f, true)]
[InlineData(1501f, false)]
public void GearListenersTakeTheLargestMultipleNotTheSumOrTheLast(float distance, bool heard)
{
var p = Add(float3(0, 0, 0), new[] { "Eye" });
var ear = Add(float3(distance, 0, 0), tools: new[] { "Listener", "Wide", "Narrow" }); // 3, 5, 1.5: the largest is the middle one
PingAt(p);
Assert.Equal(heard ? 1 : 0, ear.RevealsOf(p).Count());
}
[Theory]
[InlineData(1499f, true)]
[InlineData(1501f, false)]
public void ConsumableListenersTakeTheLargestMultipleNotTheSumOrTheLast(float distance, bool heard)
{
var p = Add(float3(0, 0, 0), new[] { "Eye" });
var ear = Add(float3(distance, 0, 0));
Activate(ear, "Earpiece"); // 3
Activate(ear, "WideEarpiece"); // 5
Activate(ear, "NarrowEarpiece"); // 1.5
PingAt(p);
Assert.Equal(heard ? 1 : 0, ear.RevealsOf(p).Count());
}
// A listener that is switched on but not online (destroyed) hears nothing: Active, not Enabled, gates it, so the
// 5x array that is down does not lift the 3x one that is up.
[Theory]
[InlineData(899f, true)]
[InlineData(901f, false)]
public void ADestroyedListenerDoesNotLiftTheOnesThatAreUp(float distance, bool heard)
{
var p = Add(float3(0, 0, 0), new[] { "Eye" });
var ear = Add(float3(distance, 0, 0), tools: new[] { "Listener", "Wide" });
var wide = ear.Equipment.Single(i => i.Behaviors.Any(b => b is Listener l && l.Multiple == 5f));
wide.EquippableItem.Durability = 0;
Tick(.1f);
Assert.True(wide.Enabled.Value); // fixture: switched on
Assert.False(wide.Active.Value); // and not online
PingAt(p);
Assert.Equal(heard ? 1 : 0, ear.RevealsOf(p).Count());
}
// The floor of 1 belongs to an active sensor, not to each listener: a listener-only ship with a Multiple of .5
// hears at half the pinger's range, and the same listener beside a sensor hears at the sensor's full range.
[Theory]
[InlineData(false, 149f, true)]
[InlineData(false, 151f, false)]
[InlineData(true, 299f, true)]
[InlineData(true, 301f, false)]
public void AMultipleBelowOneIsFlooredBySensorsNotByTheListener(bool withSensor, float distance, bool heard)
{
var p = Add(float3(0, 0, 0), new[] { "Eye" });
var ear = Add(float3(distance, 0, 0), withSensor ? new[] { "Eye" } : null, new[] { "Hush" });
PingAt(p);
Assert.Equal(heard ? 1 : 0, ear.RevealsOf(p).Count());
}
[Theory]
[InlineData(149f, true)]
[InlineData(151f, false)]
public void AConsumableMultipleBelowOneIsNotClampedUp(float distance, bool heard)
{
var p = Add(float3(0, 0, 0), new[] { "Eye" });
var ear = Add(float3(distance, 0, 0));
Activate(ear, "HushEarpiece");
PingAt(p);
Assert.Equal(heard ? 1 : 0, ear.RevealsOf(p).Count());
}
// ---- ListenerDataRoundTripsAsUnionKey50 ----
[Fact]
public void ListenerDataRoundTripsAsUnionKey50()
{
var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(ZonePack).Assembly);
var data = new ListenerData { Multiple = Const(2.5f) };
var bytes = MessagePackSerializer.Serialize<BehaviorData>(data, options);
var reader = new MessagePackReader(bytes);
Assert.Equal(2, reader.ReadArrayHeader());
Assert.Equal(50, reader.ReadInt32());
Assert.Equal(2, reader.ReadArrayHeader()); // Group is key 0, then Multiple
var back = Assert.IsType<ListenerData>(MessagePackSerializer.Deserialize<BehaviorData>(bytes, options));
Assert.Equal(2.5f, back.Multiple.Min);
}
}

View file

@ -23,11 +23,11 @@ public sealed class MunitionPartsTests : IDisposable
// both ranged stats. The column names are the retired fields'.
private static readonly (string Design, float ThrustMin, float ThrustMax, float MissileVelocityMin, float MissileVelocityMax, float DodgeFrequency)[] Golden =
{
("GT 3K", 135, 325, 150, 300, 0.25f),
("LRMM72", 400, 600, 200, 300, 0.25f),
("SRMM72", 1600, 2400, 400, 600, 1f),
("pswarm", 500, 2000, 400, 600, 1f),
("scorched void policy", 500, 2000, 400, 600, 1f),
("Guided Missile Launcher", 135, 325, 150, 300, 0.25f),
("Long-Range Missile Rack", 400, 600, 200, 300, 0.25f),
("Short-Range Missile Rack", 1600, 2400, 400, 600, 1f),
("Swarm Rocket Pod", 500, 2000, 400, 600, 1f),
("Incendiary Rocket Pod", 500, 2000, 400, 600, 1f),
};
private static PerformanceStat Flat(float value) => new PerformanceStat { Min = value, Max = value };
@ -208,13 +208,13 @@ public sealed class MunitionPartsTests : IDisposable
[Fact]
public void CatalogLoadRefusesAnIncompleteOrStrayMunitionPart()
{
using (AetheriaStores.Open(Forged<WeaponItemData>(d => d.Name == "GT 3K", _ => { }), registry: TestCatalog.Registry())) { }
using (AetheriaStores.Open(Forged<WeaponItemData>(d => d.Name == "Guided Missile Launcher", _ => { }), registry: TestCatalog.Registry())) { }
foreach (var part in AllParts)
{
var path = Forged<WeaponItemData>(d => d.Name == "GT 3K", d => d.Behaviors.RemoveAll(b => b.GetType() == part));
var path = Forged<WeaponItemData>(d => d.Name == "Guided Missile Launcher", d => d.Behaviors.RemoveAll(b => b.GetType() == part));
var refusal = Assert.ThrowsAny<Exception>(() => AetheriaStores.Open(path, registry: TestCatalog.Registry()));
Assert.Contains("GT 3K", refusal.ToString());
Assert.Contains("Guided Missile Launcher", refusal.ToString());
Assert.Contains(part.Name, refusal.ToString());
}
@ -245,13 +245,13 @@ public sealed class MunitionPartsTests : IDisposable
// The Longinus's own gear: two drives, a core, a cockpit and a sensor, so the ship has thrusters, a sensor and a plume
// for any munition contribution to be seen against.
private static readonly (string Name, int X, int Y)[] ShipGear =
{ ("Large Drive", 1, 0), ("Large Drive", 3, 0), ("Core Power", 2, 4), ("Cockpit 2x2", 2, 6), ("not if i see you first", 3, 10) };
{ ("Large Drive", 1, 0), ("Large Drive", 3, 0), ("Compact Reactor", 2, 4), ("Cockpit 2x2", 2, 6), ("Compact Sensor", 3, 10) };
// A GT 3K fitted to a Longinus launcher hardpoint beside that gear, its lot's thruster role at the given quality.
// A Guided Missile Launcher fitted to a Longinus launcher hardpoint beside that gear, its lot's thruster role at the given quality.
private static EquippedItem Fit(CultCache cache, float thrusterQuality, out Ship ship)
{
var hull = cache.GetByName<HullData>("Longinus");
var gt = cache.GetByName<WeaponItemData>("GT 3K");
var gt = cache.GetByName<WeaponItemData>("Guided Missile Launcher");
var hardpoint = hull.Hardpoints.First(h => h.Type == HardpointType.Launcher && h.IsFilledBy(gt));
var settings = RestoredHullsTests.Settings();
var ledger = new ProvenanceLedger();
@ -269,7 +269,7 @@ public sealed class MunitionPartsTests : IDisposable
zone.Admit(ship, piloted: false);
// Settle at the item's optimal temperature, as ConditionRatioTests does, so heat and wear read their identity and only
// the role's quality moves a stat.
var item = ship.Equipment.Single(e => e.Data.Name == "GT 3K");
var item = ship.Equipment.Single(e => e.Data.Name == "Guided Missile Launcher");
foreach (var cell in item.InsetShape.Coordinates) ship.Temperature[cell.x, cell.y] = gt.OptimalTemperature;
item.UpdatePerformance();
item.UpdatePerformance();
@ -280,7 +280,7 @@ public sealed class MunitionPartsTests : IDisposable
public void PartsReadThroughTheItem()
{
using var cache = RestoredHullsTests.OpenCatalog();
var design = cache.GetByName<WeaponItemData>("GT 3K");
var design = cache.GetByName<WeaponItemData>("Guided Missile Launcher");
var poor = Fit(cache, .2f, out var poorShip);
var good = Fit(cache, .9f, out _);
@ -324,7 +324,7 @@ public sealed class MunitionPartsTests : IDisposable
public void ShipSumsIgnoreTheFittedMunitionParts()
{
using var cache = RestoredHullsTests.OpenCatalog();
var design = cache.GetByName<WeaponItemData>("GT 3K");
var design = cache.GetByName<WeaponItemData>("Guided Missile Launcher");
var part = Part<MunitionThrusterData>(design);
var item = Fit(cache, .5f, out var ship);
for (var i = 0; i < 5; i++) ship.Update(.1f);

View file

@ -79,13 +79,13 @@ public sealed class PiratesFactionCommandTests : IDisposable
var expected = new (string Design, string Name, string Description)[]
{
("Autocannon", "🫳🔫", "Serial number filed off. Still shoots."),
("Earp", "🪦🤠", "The previous owner had no further use for it."),
("FastBlast+-", "🧾🚫", "Warranty void where prohibited, which is everywhere."),
("6k Shooter", "🎨🙈", "The logo underneath is somebody else's problem."),
("scorched void policy", "🔥", "Turns out we did start the fire after all."),
("Long Slug Rifle", "🪦🤠", "The previous owner had no further use for it."),
("Cell Blaster", "🧾🚫", "Warranty void where prohibited, which is everywhere."),
("Slug Rifle", "🎨🙈", "The logo underneath is somebody else's problem."),
("Incendiary Rocket Pod", "🔥", "Turns out we did start the fire after all."),
("Targeting Computer", "👀🎯", "Somebody else's eyes. They still work."),
("Small Drive", "🔑🏃💨", "Hotwired. Do not ask about the ignition."),
("Store-All Plus", "📦🤫", "Contents not as declared."),
("Cargo Bay", "📦🤫", "Contents not as declared."),
};
Assert.Equal(expected.Select(e => e.Name).OrderBy(n => n, StringComparer.Ordinal), products.Select(p => p.Name).OrderBy(n => n, StringComparer.Ordinal));
foreach (var (designName, name, description) in expected)

View file

@ -306,7 +306,7 @@ public sealed class PowerCurveTests : IDisposable
// --- F6 (docs/stats-and-power-cut.md, Soul pass 2026-09-19) named PumpedHeat as a Radiator request field
// --- (PowerRequest's own early-out gate reads it, the exact shape Soul reproduced against the shipped
// --- catalog's "OK Disperser": SOUL_RadiatorRequestDependsOnItsOwnGrantAndOscillates) and, at the time,
// --- catalog's "Heat Pump": SOUL_RadiatorRequestDependsOnItsOwnGrantAndOscillates) and, at the time,
// --- refused a PowerSupply term there for exactly that reason. The nominal-request ruling above is what
// --- actually fixes the oscillation (the request no longer reads the live grant at all), so this shape is
// --- accepted now -- the six shipped records this ruling exists to make legal again include exactly this

View file

@ -298,7 +298,7 @@ public sealed class RestoredHullsTests
Assert.True(ship.TryEquip(gearItem, hardpoint.Position));
}
// A reactor: Victoire (one of Cut 1's own restored thrusters, docs/locomotion-cut.md's own note on it)
// A reactor: Racing Drive (one of Cut 1's own restored thrusters, docs/locomotion-cut.md's own note on it)
// carries a real EnergyUsage draw unlike its four siblings, so an unpowered ship reads as though only
// some fitting thrusters produce thrust -- an artifact of which design TryEquip's own hardpoint search
// happens to land on, not of the restored content. Every hull here also has a Reactor hardpoint; a real
@ -952,7 +952,7 @@ public sealed class RestoredHullsTests
// Every restored thruster's particle effect is Thruster 1.prefab, by the legacy record (soul-dump.txt).
var thruster1Guid = GuidOf("Assets/Content/Prefabs/Thrusters/Thruster 1.prefab");
var restoredThrusterNames = new[] { "deep space burnout", "Large Drive", "Victoire", "Small Drive", "Talaria", "RevvITup 2.0", "Medium Drive" };
var restoredThrusterNames = new[] { "Burn Drive", "Large Drive", "Racing Drive", "Small Drive", "Rugged Drive", "High-Thrust Drive", "Medium Drive" };
foreach (var name in restoredThrusterNames)
{
var design = cache.GetAll<GearData>().First(g => g.Name == name);

View file

@ -13,13 +13,13 @@ using Xunit;
// oracle, since the command produced it.
public sealed class RolesBackfillCommandTests : IDisposable
{
private static readonly string[] Flattened = { "Autocannon", "LRMM72", "SRMM72", "Mine Launcher", "Large Drive", "Small Drive" };
private static readonly string[] Flattened = { "Autocannon", "Long-Range Missile Rack", "Short-Range Missile Rack", "Mine Launcher", "Large Drive", "Small Drive" };
// Designs that shipped with non-flat stats whose Quality term named no role; the field is the stat to unname.
private static readonly (string Design, string Field)[] Unnamed =
{
("DeathCluster", "Count"), ("Flak Gun", "Count"), ("GT 3K", "MinRange"), ("plight", "DamageSpread"),
("MoveOnPro", "Modifier"), ("MoveOnPro Station Reactor", "Modifier"),
("Cluster Cannon", "Count"), ("Flak Gun", "Count"), ("Guided Missile Launcher", "MinRange"), ("Lightning Projector", "DamageSpread"),
("Muon Fusion Reactor", "Modifier"), ("Muon Fusion Station Reactor", "Modifier"),
};
private readonly string _root = Path.Combine(Path.GetTempPath(), "roles-backfill-" + Guid.NewGuid().ToString("N"));
@ -165,7 +165,7 @@ public sealed class RolesBackfillCommandTests : IDisposable
static Dictionary<string, float> Exponents(EquippableItemData d) => CatalogRoleTests.StatsOf(d)
.SelectMany(s => s.Stat.Terms.Where(t => t.Source == StatSource.Quality && !string.IsNullOrEmpty(t.Role)).Select(t => (s.Name, t.Exponent)))
.ToDictionary(x => x.Name, x => x.Exponent);
var designs = new[] { "Autocannon", "LRMM72" };
var designs = new[] { "Autocannon", "Long-Range Missile Rack" };
Dictionary<string, Dictionary<string, float>> shipped;
Dictionary<string, Dictionary<string, float>> Read(EquippableItemData[] all) => all.Where(d => designs.Contains(d.Name)).ToDictionary(d => d.Name, Exponents);
using (var catalog = RestoredHullsTests.OpenCatalog()) shipped = Read(catalog.GetAll<EquippableItemData>().ToArray());

View file

@ -445,7 +445,7 @@ public sealed partial class RunStartTests : IDisposable
}
// The sold hardpoint gear the generator gives no home today: the production rule (LoadoutGenerator.HasHome over the hulls a
// product sells). The Smoke Test Hull, which no product sells, gives ChargeBlast SG and ChargeBlast+- no home; authoring a
// product sells). The Smoke Test Hull, which no product sells, gives Charged Scatter Blaster and Charged Blaster no home; authoring a
// sold hull that takes one shows up here as a changed list.
[Fact]
public void TheSoldHardpointGearWithNoHomeToday()
@ -456,7 +456,7 @@ public sealed partial class RunStartTests : IDisposable
.Where(design => sold.Contains(_cache.RefOf(design).Key) && design.Price > 0)
.Where(design => !LoadoutGenerator.HasHome(design, hulls))
.Select(design => design.Name).OrderBy(name => name, StringComparer.Ordinal).ToArray();
Assert.Equal(new[] { "CShot RainbowLite Lazer", "ChargeBlast SG", "ChargeBlast+-", "OK Disperser" }, homeless);
Assert.Equal(new[] { "Charged Blaster", "Charged Scatter Blaster", "Heat Pump", "Heavy Beam Laser" }, homeless);
}

View file

@ -0,0 +1,433 @@
using System;
using System.Collections.Generic;
using System.Linq;
using CultMath;
using GameCult.Caching.MessagePack;
using MessagePack;
using Xunit;
using static CultMath.math;
using float2 = CultMath.float2;
using float3 = CultMath.float3;
// Inspection (rulings quiet-gear-identifiable-hull-layout-known, scan-held-beam, scan-is-an-act, reveal-ends-on-perception,
// sensor-stat-set): a scanner held on its ship's tracked target within Range for ScanTime reveals everything fitted to it,
// as claimed, and is itself an emission the target is warned of and a third party can hear. The fixtures are the
// catalog's: "Scanner" has Range 200 and ScanTime 2, "QuietScanner" the same with intercept factor 4 (heard at 50). A tick
// is 1/8 s, so a scan builds 1/16 a tick and finishes on the sixteenth with no float drift. The scanner's ship keeps
// its track on the target at .5 each tick (above the detection gate, below the one at which gear is resolved, so
// Sense neither loses the track nor perceives a destruction). Every fixture drives the production path, ticking inside
// Zone.Update.
public sealed partial class ContactRevealTests
{
private const float ScanStep = .125f;
private static ScannerData ScannerBehavior(float range, float scanTime, float? interceptFactor = null) => new ScannerData
{
Range = Const(range), ScanTime = Const(scanTime),
InterceptFactor = interceptFactor.HasValue ? Const(interceptFactor.Value) : null
};
private static Scanner ScannerOf(Entity e) => e.Equipment.SelectMany(i => i.Behaviors).OfType<Scanner>().Single();
private static EquippedItem ScannerItemOf(Entity e) => e.Equipment.Single(i => i.Behaviors.Any(b => b is Scanner));
// A scanner ship at the origin, with the named scanner and no sensor (an AI ship with a sensor pings once it loses its
// track, which would paint the target beside the scan), tracking and targeting a ship `distance`
// ahead that carries a reactor, a radiator and a suppressor, none of which ever acts.
private (Ship scanner, Ship target) ScanOn(string scanner = "Scanner", float distance = 100f, float info = .5f)
{
var target = Add(float3(0, 0, distance), tools: new[] { "Reactor", "Radiator", "SuppressorCold" });
var s = Add(float3(0, 0, 0), tools: new[] { scanner });
s.EntityInfoGathered[target] = info;
s.SetTarget(target);
Assert.Same(target, s.Target.Value.Entity); // fixture
return (s, target);
}
// Ticks `ticks` steps, holding the observer's track on each of `tracked` at `info` before each.
private void Hold(Entity observer, int ticks, float info, params Entity[] tracked)
{
for (var i = 0; i < ticks; i++)
{
foreach (var t in tracked) observer.EntityInfoGathered[t] = info;
Tick(ScanStep);
}
}
private void Hold(Entity observer, int ticks, params Entity[] tracked) => Hold(observer, ticks, .5f, tracked);
private static EquippedItem[] FittedBesidesTheHull(Entity e) => e.Equipment.Where(i => i != e.EquippedHull).ToArray();
// ---- AScanRevealsQuietGear ----
[Fact]
public void AScanRevealsQuietGear()
{
var (s, target) = ScanOn();
var quiet = FittedBesidesTheHull(target);
Assert.Equal(3, quiet.Length);
Assert.Empty(s.RevealsOf(target)); // fixture: nothing acts
Hold(s, 15, target);
Assert.Empty(s.RevealsOf(target));
Assert.Equal(15f / 16f, ScannerOf(s).Progress, 4);
Hold(s, 1, target);
foreach (var item in quiet)
{
var reveal = Assert.Single(s.RevealsOf(target), r => r.Item == item);
Assert.Null(reveal.Channel);
AssertBearing(0f, 1f, reveal.Bearing); // normalize((target - scanner).xz)
Assert.Equal(_zone.Time, reveal.Time);
}
Assert.Equal(0f, ScannerOf(s).Progress); // a finished scan starts over
}
// ---- AScanSkipsTheHull ----
[Fact]
public void AScanSkipsTheHull()
{
var (s, target) = ScanOn();
Assert.Contains(target.EquippedHull, target.Equipment); // fixture: the hull is an item of Equipment
Hold(s, 16, target);
Assert.Equal(3, s.RevealsOf(target).Count()); // fixture: the scan finished
Assert.DoesNotContain(s.RevealsOf(target), r => r.Item == target.EquippedHull);
}
// ---- AScanSkipsDestroyedGear ----
[Fact]
public void AScanSkipsDestroyedGear()
{
var (s, target) = ScanOn();
var items = FittedBesidesTheHull(target);
items[0].EquippableItem.Durability = 0f;
Assert.True(items[0].EquippableItem.IsDestroyed);
Hold(s, 16, target);
Assert.DoesNotContain(s.RevealsOf(target), r => r.Item == items[0]);
Assert.Equal(2, s.RevealsOf(target).Count());
}
// ---- AScanRecordsTheClaim ----
[Fact]
public void AScanRecordsTheClaim()
{
var (s, target) = ScanOn();
var reactor = target.Equipment.Single(i => i.Behaviors.Any(b => b is Reactor));
var radiator = DataOf("Radiator");
target.Claim(reactor, radiator);
Hold(s, 16, target);
var reveal = Assert.Single(s.RevealsOf(target), r => r.Item == reactor);
Assert.Same(radiator, reveal.Claimed);
Assert.NotSame(reactor.Data, reveal.Claimed);
}
// ---- AScanNeedsATrackAndRange ----
[Theory]
[InlineData(199f, true, true)]
[InlineData(201f, true, false)]
[InlineData(100f, false, false)]
public void AScanNeedsATrackAndRange(float distance, bool tracked, bool builds)
{
var third = Add(float3(40, 0, 0), new[] { "Eye" }); // within 200 of the scanner: it hears an emission
var info = tracked ? .5f : 0f;
var (s, target) = ScanOn(distance: distance, info: info);
Assert.Equal(tracked, s.VisibleEntities.Contains(target)); // fixture
Hold(s, 4, info, target);
Assert.Equal(builds, ScannerOf(s).Progress > 0f);
Assert.Equal(builds, target.IncomingPaints.Count > 0);
Assert.Equal(builds, target.RevealsOf(s).Any());
Assert.Equal(builds, third.RevealsOf(s).Any());
}
// ---- ABrokenScanDecays ----
// A scan at .5 broken for half of ScanTime (one second) falls to 0, a quarter in half of that: by range (Execute
// runs and does not hold) and by the item switched off (Execute does not run at all).
[Theory]
[InlineData(true)]
[InlineData(false)]
public void ABrokenScanDecays(bool byRange)
{
var (s, target) = ScanOn();
Hold(s, 8, target);
Assert.Equal(.5f, ScannerOf(s).Progress, 4);
if (byRange) target.Position = float3(0, 0, 400);
else ScannerItemOf(s).Enabled.Value = false;
Hold(s, 4, target);
Assert.Equal(.25f, ScannerOf(s).Progress, 4);
Hold(s, 4, target);
Assert.Equal(0f, ScannerOf(s).Progress, 4);
Hold(s, 2, target);
Assert.Equal(0f, ScannerOf(s).Progress, 4); // never below 0
}
// ---- ABrokenScanResumesFromWhatDecayed ----
// A scan at .5 loses a sixteenth for each tick it is broken, and a held tick after the gap builds on what is left (the
// held tick itself is not a decay tick): .5, two broken ticks .375, two held ticks .5.
[Fact]
public void ABrokenScanResumesFromWhatDecayed()
{
var (s, target) = ScanOn();
Hold(s, 8, target);
Assert.Equal(.5f, ScannerOf(s).Progress, 4);
target.Position = float3(0, 0, 400);
Hold(s, 2, target);
Assert.Equal(.375f, ScannerOf(s).Progress, 4);
target.Position = float3(0, 0, 100);
Hold(s, 2, target);
Assert.Equal(.5f, ScannerOf(s).Progress, 4);
}
// ---- ATargetChangeResetsTheScan ----
[Fact]
public void ATargetChangeResetsTheScan()
{
var (s, first) = ScanOn();
var second = Add(float3(100, 0, 0));
Hold(s, 11, first, second);
Assert.Equal(11f / 16f, ScannerOf(s).Progress, 4);
s.SetTarget(second);
Hold(s, 1, first, second);
Assert.Equal(1f / 16f, ScannerOf(s).Progress, 4); // reset, then one tick on the new target
Assert.Empty(s.RevealsOf(first));
}
// ---- TheScannedShipIsWarned ----
// A paint made in a tick is published the next one, so after four ticks the target holds the third tick's paint.
[Fact]
public void TheScannedShipIsWarned()
{
var (s, target) = ScanOn();
Hold(s, 4, target);
var paint = Assert.Single(target.IncomingPaints);
Assert.Equal(PaintMode.Scan, paint.Mode);
Assert.Equal(3f / 16f, paint.Strength, 4);
Assert.Same(DataOf("Scanner"), paint.EmitterClass);
AssertBearing(0f, -1f, paint.Bearing); // normalize((scanner - target).xz)
var warned = Assert.Single(target.RevealsOf(s));
Assert.Same(ScannerItemOf(s), warned.Item);
Assert.Equal(SignatureChannel.Emission, warned.Channel);
}
// ---- AThirdPartyHearsTheScanner ----
[Theory]
[InlineData("QuietScanner", 49f, true)]
[InlineData("QuietScanner", 51f, false)]
[InlineData("Scanner", 199f, true)]
[InlineData("Scanner", 201f, false)]
public void AThirdPartyHearsTheScanner(string scanner, float distance, bool heard)
{
var (s, target) = ScanOn(scanner);
var third = Add(float3(-distance, 0, 0), new[] { "Eye" });
Hold(s, 3, target);
Assert.Empty(third.IncomingPaints); // fixture: only the target is painted
if (!heard)
{
Assert.Empty(third.RevealsOf(s));
return;
}
var reveal = Assert.Single(third.RevealsOf(s));
Assert.Same(ScannerItemOf(s), reveal.Item);
Assert.Equal(SignatureChannel.Emission, reveal.Channel);
AssertBearing(1f, 0f, reveal.Bearing); // normalize((scanner - third).xz)
}
// ---- AFinishedScanMakesTheReactorSelectable ----
[Fact]
public void AFinishedScanMakesTheReactorSelectable()
{
var (s, target) = ScanOn();
var reactor = target.Equipment.Single(i => i.Behaviors.Any(b => b is Reactor));
Hold(s, 15, target);
Assert.False(FireControl.IsRevealed(s, reactor));
Assert.False(s.TrySelectTargetItem(reactor));
Hold(s, 1, target);
Assert.True(FireControl.IsRevealed(s, reactor));
Assert.True(s.TrySelectTargetItem(reactor));
}
// ---- AScanEndsNothing ----
// A gun revealed by firing and then destroyed, while the observer's track stays between the detection and gear
// thresholds (so Sense perceives no destruction): a scan neither ends its reveal nor refreshes it.
[Fact]
public void AScanEndsNothing()
{
var target = Add(float3(0, 0, 100), new[] { "Gun" });
var s = Add(float3(0, 0, 0), new[] { "Eye" }, new[] { "Scanner" });
var gun = Guns(target)[0];
var firedAt = Fire(target, gun);
var before = Assert.Single(s.RevealsOf(target), r => r.Item == gun);
Assert.Equal(firedAt, before.Time); // fixture: the gun is in the book
gun.EquippableItem.Durability = 0f;
s.EntityInfoGathered[target] = .5f;
s.SetTarget(target);
Hold(s, 16, target);
var after = Assert.Single(s.RevealsOf(target), r => r.Item == gun);
Assert.Equal(firedAt, after.Time);
Assert.Equal(SignatureChannel.LaunchFlash, after.Channel);
Assert.Contains(s.RevealsOf(target), r => r.Item != gun && r.Channel == null); // fixture: the scan finished
}
// ---- AScanReadsNoHostility ----
// Ruling ew-hostility-from-belief-ruled: a scan is an act of perception and judges nothing, so it proceeds and records the
// claim whatever the stance between the two ships, hostile or friendly, honest or lying. The stance is set both ways
// through SetIff, which decides IsHostileTo, EntityHostility and VisibleEnemies alike.
[Theory]
[InlineData(true, false)]
[InlineData(true, true)]
[InlineData(false, false)]
[InlineData(false, true)]
public void AScanReadsNoHostility(bool hostile, bool lies)
{
var (s, target) = ScanOn();
var reactor = target.Equipment.Single(i => i.Behaviors.Any(b => b is Reactor));
var radiator = DataOf("Radiator");
if (lies) target.Claim(reactor, radiator);
s.SetIff(target, hostile);
target.SetIff(s, hostile);
Tick(ScanStep);
Assert.Equal(hostile, s.IsHostileTo(target)); // fixture
Assert.Equal(hostile, s.VisibleEnemies.Contains(target)); // fixture: the stance reached the readers a gate would use
Hold(s, 16, target);
Assert.Equal(3, s.RevealsOf(target).Count());
var reveal = Assert.Single(s.RevealsOf(target), r => r.Item == reactor);
Assert.Same(lies ? radiator : reactor.Data, reveal.Claimed);
Assert.NotEmpty(target.IncomingPaints.Where(p => p.Mode == PaintMode.Scan));
}
// ---- AScanTakesTheSamePathForAnyPilot ----
// Ruling same-ship-same-inputs: a ship with an AI agent and one with none (the player's) scan the same target through
// the one Scanner and enter the same reveals in their books, claimed alike. Every reveal in a book comes from
// RecordReveal, whose callers are Sense, PublishInbox and RecordInspection: a second scan path for either pilot would
// leave the two books different (or one empty).
[Fact]
public void AScanTakesTheSamePathForAnyPilot()
{
var target = Add(float3(0, 0, 100), tools: new[] { "Reactor", "Radiator", "SuppressorCold" });
var reactor = target.Equipment.Single(i => i.Behaviors.Any(b => b is Reactor));
target.Claim(reactor, DataOf("Radiator"));
var player = Add(float3(-20, 0, 0), tools: new[] { "Scanner" });
var ai = Add(float3(20, 0, 0), tools: new[] { "Scanner" });
_zone.Agents.Add(new Agent(ai)); // the AI pilot, ticked in Zone.Update beside the scan; a task-less agent needs no orbit to patrol
Assert.Single(_zone.Agents); // fixture: only the second ship has an agent
foreach (var scanner in new[] { player, ai })
{
scanner.EntityInfoGathered[target] = .5f;
scanner.SetTarget(target);
}
void Step(int ticks)
{
for (var i = 0; i < ticks; i++)
{
player.EntityInfoGathered[target] = .5f;
ai.EntityInfoGathered[target] = .5f;
Tick(ScanStep);
}
}
Step(15);
Assert.Empty(player.RevealsOf(target)); // neither pilot has a scan before ScanTime
Assert.Empty(ai.RevealsOf(target));
Step(1);
Assert.Equal(3, player.RevealsOf(target).Count());
Func<Entity, string[]> book = o => o.RevealsOf(target)
.Select(r => r.Item.Data.Name + "|" + r.Claimed.Name + "|" + (r.Channel?.ToString() ?? "scan")).OrderBy(x => x).ToArray();
Assert.Equal(book(player), book(ai));
}
// ---- AConsumableScannerDecaysOnTheSameTick ----
// The two hosts order Execute and the always-updated pass differently (ConsumableItemEffect.Update runs the pass first),
// so the scan's decay must not depend on that order: a scan broken by range loses dt/ScanTime on the tick it breaks, and
// .5 falls to .25 in four ticks, as ABrokenScanDecays has it for gear.
[Fact]
public void AConsumableScannerDecaysOnTheSameTick()
{
var data = _openCache.GetByName<ConsumableItemData>("ScannerCharge");
var target = Add(float3(0, 0, 100), tools: new[] { "Reactor" });
var s = Add(float3(0, 0, 0));
s.ActivateConsumable(Assert.IsType<ConsumableItem>(_items.CreateInstance(_items.CreateLot(data, _maker, .5f))));
var scanner = s.FindActiveConsumable(data).Behaviors.OfType<Scanner>().Single();
s.EntityInfoGathered[target] = .5f;
s.SetTarget(target);
Hold(s, 8, target);
Assert.Equal(.5f, scanner.Progress, 4); // fixture: the consumable scans like gear
target.Position = float3(0, 0, 400);
Hold(s, 4, target);
Assert.Equal(.25f, scanner.Progress, 4);
Hold(s, 4, target);
Assert.Equal(0f, scanner.Progress, 4);
}
// ---- ScannerDataRoundTripsAsUnionKey51 ----
[Fact]
public void ScannerDataRoundTripsAsUnionKey51()
{
var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(ZonePack).Assembly);
var data = new ScannerData { Range = Const(200f), ScanTime = Const(2f), InterceptFactor = Const(4f) };
var bytes = MessagePackSerializer.Serialize<BehaviorData>(data, options);
var reader = new MessagePackReader(bytes);
Assert.Equal(2, reader.ReadArrayHeader());
Assert.Equal(51, reader.ReadInt32()); // sensor-catalog holds 50; a key reused across branches would collide on the wire
Assert.Equal(4, reader.ReadArrayHeader()); // Group is key 0, then the three stats
reader.Skip();
Assert.Equal(200f, MessagePackSerializer.Deserialize<PerformanceStat>(ref reader, options).Min); // key 1 Range
Assert.Equal(2f, MessagePackSerializer.Deserialize<PerformanceStat>(ref reader, options).Min); // key 2 ScanTime
Assert.Equal(4f, MessagePackSerializer.Deserialize<PerformanceStat>(ref reader, options).Min); // key 3 InterceptFactor
var back = Assert.IsType<ScannerData>(MessagePackSerializer.Deserialize<BehaviorData>(bytes, options));
Assert.Equal(200f, back.Range.Min);
Assert.Equal(2f, back.ScanTime.Min);
Assert.Equal(4f, back.InterceptFactor.Min);
var absent = Assert.IsType<ScannerData>(MessagePackSerializer.Deserialize<BehaviorData>(
MessagePackSerializer.Serialize<BehaviorData>(new ScannerData { Range = Const(1f), ScanTime = Const(1f) }, options), options));
Assert.Null(absent.InterceptFactor);
var unions = typeof(BehaviorData).GetCustomAttributes(typeof(UnionAttribute), false).Cast<UnionAttribute>().ToArray();
Assert.Single(unions, u => u.Key == 51);
Assert.Equal(unions.Length, unions.Select(u => u.Key).Distinct().Count());
}
}

View file

@ -537,7 +537,7 @@ public sealed partial class RunStartTests
runs.Add(Stage(Arena(false), new Scripted(false, stage =>
{
var ship = stage.Player(stage.Fit("Djinni", ("Census Fitted", int2(1, 6), ItemRotation.None), ("Store-All Plus", int2(3, 6), ItemRotation.None)), float2(0, 0));
var ship = stage.Player(stage.Fit("Djinni", ("Census Fitted", int2(1, 6), ItemRotation.None), ("Cargo Bay", int2(3, 6), ItemRotation.None)), float2(0, 0));
stage.Cargo(ship, "Census Carried");
})));
Assert.Empty(UnsoldAndUnplaced(runs));
@ -580,4 +580,19 @@ public sealed partial class RunStartTests
Assert.Equal("<Keyboard>/1", Assert.Single(settings.InputSettings.ActionBarInputs));
Assert.Equal((Quality.High, true), (settings.GraphicsSettings.NebulaQuality, settings.GraphicsSettings.ShowAsteroidsInMinimap));
}
// A scenario's Brief is player text (the menu shows it): it names gear by what the catalog sells today. A name a rename retired,
// that no design or product carries any more, would send the player looking for gear that is gone.
[Fact]
public void NoScenarioBriefNamesRetiredGear()
{
var current = _cache.GetAll<EquippableItemData>().Select(design => design.Name)
.Concat(_cache.GetAll<FactionProductData>().Select(product => product.Name)).ToHashSet(StringComparer.Ordinal);
var stale = new List<string>();
foreach (var scenario in EveryScenario)
foreach (var retired in Program.Renames.Select(row => row.Old).Where(name => !current.Contains(name)))
if (System.Text.RegularExpressions.Regex.IsMatch(scenario.Brief, @"(?<!\w)" + System.Text.RegularExpressions.Regex.Escape(retired) + @"s?(?!\w)"))
stale.Add(scenario.Name + " names " + retired);
Assert.True(stale.Count == 0, "scenario briefs naming gear the catalog no longer has: " + string.Join("; ", stale));
}
}

View file

@ -37,7 +37,7 @@ public sealed class SmokeHullCommandTests : IDisposable
var hulls = db.Cache.GetAll<HullData>().Where(h => h.Name == HullName).ToArray();
var keys = hulls.Select(h => db.Cache.RefOf(h).Key).ToArray();
var products = db.Cache.GetAll<FactionProductData>().Count(p => keys.Any(k => p.Design.Key.Equals(k)));
var fitted = new[] { "ChargeBlast SG", "Autocannon" }
var fitted = new[] { "Charged Scatter Blaster", "Autocannon" }
.Select(name => db.Cache.GetAll<EquippableItemData>().Single(d => d.Name == name)).ToArray();
return (hulls, db.Cache.GetAll<HullData>().Single(h => h.Name == "Longinus"), fitted, products);
}

View file

@ -12,7 +12,7 @@ public sealed partial class RunStartTests
private static List<EquippedItem> WeaponMounts(Entity ship) =>
ship.Equipment.Where(item => item.Behaviors.OfType<Weapon>().Any()).ToList();
// Weapon Feel: the player flies the Smoke Test Hull with ChargeBlast SG on the 2x2 Energy hardpoint, Autocannon
// Weapon Feel: the player flies the Smoke Test Hull with Charged Scatter Blaster on the 2x2 Energy hardpoint, Autocannon
// on the 2x2 Ballistic hardpoint and a burst weapon; the bare hull ahead lies in every mount's arc.
[Fact]
public void WeaponFeelConditions()
@ -23,7 +23,7 @@ public sealed partial class RunStartTests
Assert.Equal("Smoke Test Hull", _items.GetData(player.EquippedHull.EquippableItem).Name);
EquippedItem Mount(string design) => Assert.Single(WeaponMounts(player), item => _items.GetData(item.EquippableItem).Name == design);
var charge = Mount("ChargeBlast SG");
var charge = Mount("Charged Scatter Blaster");
var autocannon = Mount("Autocannon");
Assert.Equal((HardpointType.Energy, 2, 2), (charge.Hardpoint.Type, charge.Hardpoint.Shape.Width, charge.Hardpoint.Shape.Height));
Assert.Equal((HardpointType.Ballistic, 2, 2), (autocannon.Hardpoint.Type, autocannon.Hardpoint.Shape.Width, autocannon.Hardpoint.Shape.Height));

View file

@ -43,7 +43,7 @@ public sealed class SmokeRoundsCommandTests : IDisposable
public void Dispose() => Directory.Delete(_root, true);
private (WeaponItemData[] Smoke, WeaponItemData Spectra, WeaponItemData ChargeBlast, int Products) Read()
private (WeaponItemData[] Smoke, WeaponItemData LightLaser, WeaponItemData ChargedScatterBlaster, int Products) Read()
{
var db = AetherDb.Open(root: _root);
try
@ -51,7 +51,7 @@ public sealed class SmokeRoundsCommandTests : IDisposable
var smoke = db.Cache.GetAll<WeaponItemData>().Where(w => Names.Contains(w.Name)).ToArray();
var keys = smoke.Select(w => db.Cache.RefOf(w).Key).ToArray();
var products = db.Cache.GetAll<FactionProductData>().Count(p => keys.Any(k => p.Design.Key.Equals(k)));
return (smoke, db.Cache.GetAll<WeaponItemData>().Single(w => w.Name == "Spectra"), db.Cache.GetAll<WeaponItemData>().Single(w => w.Name == "ChargeBlast SG"), products);
return (smoke, db.Cache.GetAll<WeaponItemData>().Single(w => w.Name == "Light Laser"), db.Cache.GetAll<WeaponItemData>().Single(w => w.Name == "Charged Scatter Blaster"), products);
}
finally { db.Cache.Dispose(); }
}
@ -85,7 +85,7 @@ public sealed class SmokeRoundsCommandTests : IDisposable
Assert.Equal((WeaponFuse.Delayed, 4f, 2f, 2f), (Design("Smoke Delayed").Fuse.Value, Design("Smoke Delayed").BlastRadius.Value, Data("Smoke Delayed").Penetration.Min, Data("Smoke Delayed").Penetration.Max));
Assert.Equal((WeaponFuse.Proximity, 30f, 20f, 20f), (Design("Smoke Refused").Fuse.Value, Design("Smoke Refused").BlastRadius.Value, Data("Smoke Refused").Range.Min, Data("Smoke Refused").Range.Max));
// Spectra clones are energy, 1x2, with the Spectra's own gear; the charged one is a ChargeBlast SG clone on its 2x2 energy mount.
// Light Laser clones are energy, 1x2, with the Light Laser's own gear; the charged one is a Charged Scatter Blaster clone on its 2x2 energy mount.
foreach (var name in new[] { "Smoke Proximity", "Smoke Delayed", "Smoke Refused", "Smoke Refused Beam" })
Assert.Equal((spectra.Hardpoint, spectra.Shape.Width, spectra.Shape.Height, spectra.Mass), (Design(name).Hardpoint, Design(name).Shape.Width, Design(name).Shape.Height, Design(name).Mass));
Assert.Equal((chargeBlast.Hardpoint, chargeBlast.Shape.Width, chargeBlast.Shape.Height), (Design("Smoke Refused Charge").Hardpoint, 2, 2));

View file

@ -34,7 +34,7 @@ public sealed partial class RunStartTests
var proximity = Carried(player, "Smoke Proximity");
var delayed = Carried(player, "Smoke Delayed");
var direct = Carried(player, "DeathCluster");
var direct = Carried(player, "Cluster Cannon");
Assert.Null(player.Target.Value.Entity);
// The bare hull is on the initial aim line, ahead, and inside every weapon mount's arc.

View file

@ -55,11 +55,11 @@ public sealed partial class RunStartTests
Assert.True(taken > 0f, $"the hull ahead took no damage (selected {selected})");
}
// Fused Rounds, nothing selected, the player aiming down the bare hull ahead. The DeathCluster is the control: it fires
// Fused Rounds, nothing selected, the player aiming down the bare hull ahead. The Cluster Cannon is the control: it fires
// in this arena, so a fused weapon that does not is not a harness that cannot fire. A fused round flies slowly enough
// to be in the air when the direct weapon kills the fragile hull (check A.3) and bursts on the first hull on the aim line.
[Theory]
[InlineData("DeathCluster")]
[InlineData("Cluster Cannon")]
[InlineData("Smoke Proximity")]
[InlineData("Smoke Delayed")]
public void EveryWeaponAboardFiresInTheSteppedFusedRoundsArena(string design)
@ -77,7 +77,7 @@ public sealed partial class RunStartTests
for (var i = 0; i < 60; i++) arena.Update(SteppedDt);
Assert.True(fired.Count > 0, $"{design} fired nothing in 3 s; the ship's reactor is {(player.PowerBus.TotalGeneration > 0f ? "running" : "down")}");
if (design == "DeathCluster") return;
if (design == "Cluster Cannon") return;
var (at, burst) = committed.First();
Assert.Equal(ShotResult.Burst, burst.Result);
Assert.True(burst.HasBurstPoint);
@ -86,7 +86,7 @@ public sealed partial class RunStartTests
Assert.InRange(at + burst.ArrivalIn - fired[0], 1f, 5f); // in the air for seconds: not resolved in its firing tick, not minutes of flight
}
// Check A.3 flown: the fragile hull is selected and the DeathCluster, at full damage inside its effective range, starts
// Check A.3 flown: the fragile hull is selected and the Cluster Cannon, at full damage inside its effective range, starts
// killing it; once half its hull is gone a Smoke Proximity round is fired at it, and the hull dies before the round
// lands, so the round never bursts.
[Fact]
@ -107,7 +107,7 @@ public sealed partial class RunStartTests
});
var hullDurability = ((HullData) _items.GetData(fragile.Hull)).Durability;
WeaponOf(Carried(player, "DeathCluster")).Activate();
WeaponOf(Carried(player, "Cluster Cannon")).Activate();
float? deadAt = null;
var fired = false;
for (var i = 0; i < 120 && landed == null; i++)
@ -117,7 +117,7 @@ public sealed partial class RunStartTests
if (deadAt == null && !arena.Entities.Contains(fragile)) deadAt = arena.Time;
}
Assert.True(fired, "the DeathCluster never hurt the fragile hull");
Assert.True(fired, "the Cluster Cannon never hurt the fragile hull");
Assert.NotNull(deadAt);
Assert.NotNull(landed);
Assert.True(deadAt <= landed.Value.At, $"the round landed at {landed.Value.At:F2} s, before the fragile hull died at {deadAt:F2} s");

View file

@ -14,7 +14,7 @@ using float3 = CultMath.float3;
// Flight control allocates thrust (ruling flight-control-allocates-thrust): Ship.Update hands the intent and every
// thruster's live column to one ThrustAllocator, and a ship flies on what that answers. These tests fly the Duel's
// Longinus (two mismatched Large Drives forward, a Talaria on each flank) through the real Ship.Update; a test that reads
// Longinus (two mismatched Large Drives forward, a Rugged Drive on each flank) through the real Ship.Update; a test that reads
// velocity steps the arena, because the zone places the orbits that Ship.Update alone leaves stacked at the spawn.
public sealed partial class RunStartTests
{
@ -307,7 +307,7 @@ public sealed partial class RunStartTests
// Rulings evasion-is-unpredictability and turn-authority-full: the Longinus's Large Drives count toward its turn,
// because the envelope is summed over every live column. Its clockwise is the sum of the positive yaw of its columns
// at live thrust, and exceeds the Talaria's own by the drives'.
// at live thrust, and exceeds the Rugged Drive's own by the drives'.
[Fact]
public void TheEnvelopeCountsTheMains()
{
@ -317,7 +317,7 @@ public sealed partial class RunStartTests
for (var tick = 0; tick < 10; tick++) player.Update(AllocDt);
var thrusters = player.GetBehaviors<Thruster>().Where(t => t.Item.Active.Value).ToArray();
var drives = thrusters.Where(t => t.Item.Data.Name == "Large Drive").ToArray();
var flanks = thrusters.Where(t => t.Item.Data.Name == "Talaria").ToArray();
var flanks = thrusters.Where(t => t.Item.Data.Name == "Rugged Drive").ToArray();
Assert.Equal(2, drives.Length);
Assert.Equal(2, flanks.Length);
float Clockwise(IEnumerable<Thruster> of) => of.Sum(t => max(t.Column(t.Thrust).z, 0f));

View file

@ -18,13 +18,13 @@ public class ThrustAllocatorTests
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).
// TA3, the Duel Longinus: two mismatched drives (0, 1) and two Rugged Drives (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.
// The clockwise Rugged Drive lost.
static float3[] DamagedDuel() => new[]
{
Col(0, 53.94f, 49.24f), Col(0, 61.19f, -55.86f), default, Col(-21.80f, 0, -124.63f),
@ -137,7 +137,7 @@ public class ThrustAllocatorTests
[Fact]
public void TheOnsetMovesWithTheColumns()
{
// Clockwise Talaria lost: the drive serves a clockwise turn from the first touch.
// Clockwise Rugged Drive 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]}");
@ -145,7 +145,7 @@ public class ThrustAllocatorTests
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.
// Clockwise Rugged Drive 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;

View file

@ -0,0 +1,124 @@
#!/usr/bin/env python3
"""Mutation tests for the flow-shader-parity rule (campaign aetheria-fauna, cut fauna-flow-field).
Assets/Scripts/Editor/FlowFieldSceneVerify.cs opens ARPG.unity and drives VolumeSampling and Stardust as the game
does (the keywords, the stardust buffer, CloudShader's keywords); each mutant below names the check that must catch it.
Assets/Scripts/Editor/FlowFieldParityVerify.cs evaluates the HLSL globalFlow and slopeFlow
(Assets/Shaders/Volumetric.cginc, through FlowParity.compute) and FlowField (ServerShared) for the
same positions, scrolls, settings and gradients, after VolumeSampling.LowerFlow has lowered a stepped
Zone's flow into the shader globals. Tests.asmdef cannot see Assembly-CSharp and the check needs a GPU,
so it runs here, in Unity batchmode WITHOUT -nographics (see ShieldPanelCut3Verify.cs).
A control run proves the unmutated tree passes. Then each mutant edits the real source in one way a
rule of the cut forbids, runs the check, asserts it goes red naming the check that owns the rule, and
restores the file byte for byte. A mutant that fails for the wrong reason (a broken harness) cannot
hide behind the control.
Run from the repo root: py -3 tests/mutation_tests_flow_parity.py [--only <label>[,<label>]]
Exit code 0 only if the control passed and every mutant was caught for its reason. Run one Unity at a
time: never start this while another Unity process is running.
"""
from __future__ import annotations
import subprocess
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]
UNITY_EXE = r"C:\Program Files\Unity\Hub\Editor\6000.3.24f1\Editor\Unity.exe"
PARITY = "Aetheria.EditorTools.FlowFieldParityVerify.Run"
SCENE = "Aetheria.EditorTools.FlowFieldSceneVerify.Run"
STARDUST_COMPUTE = "Assets/Shaders/Compute/Stardust/Stardust.compute"
PARITY_COMPUTE = "Assets/Shaders/Compute/FlowParity.compute"
CLOUD_SHADER = "Assets/Shaders/Raymarching/CloudShader.shader"
CGINC = "Assets/Shaders/Volumetric.cginc"
VOLUME_SAMPLING = "Assets/Scripts/Zone Display/VolumeSampling.cs"
FLOW_FIELD = "Assets/Scripts/ServerShared/FlowField.cs"
SETTINGS_ASSET = "Assets/Resources/Settings.asset"
# (label, file, before, after, the failing check the probe must name)
MUTANTS = [
("hlsl-y-halving", CGINC, "flowSample.y *= .5;", "flowSample.y *= .6;", "global"),
("hlsl-y-factor-501", CGINC, "flowSample.y *= .5;", "flowSample.y *= .501;", "global"),
("hlsl-amplitude-1.0005", CGINC, "- float3(0,_FlowScroll.y,0) ) * _FlowAmplitude;", "- float3(0,_FlowScroll.y,0) ) * _FlowAmplitude * 1.0005;", "global"),
("hlsl-scroll-sign", CGINC, "field - float3(0,_FlowScroll.x,0)", "field + float3(0,_FlowScroll.x,0)", "global"),
("hlsl-scroll2-dropped", CGINC, "field * 1.61803398875 - float3(0,_FlowScroll.y,0)", "field * 1.61803398875", "global"),
("hlsl-swirl-flipped", CGINC, "float3(ngrad.y, 0, -ngrad.x)", "float3(-ngrad.y, 0, ngrad.x)", "slope"),
("hlsl-swirl-1.0005", CGINC, "float3(ngrad.y, 0, -ngrad.x) * _FlowSwirlAmplitude", "float3(ngrad.y, 0, -ngrad.x) * _FlowSwirlAmplitude * 1.0005", "slope"),
("hlsl-zero-gradient-guard", CGINC, " if (dot(grad, grad) == 0) return 0;\n", "", "slope"),
("lower-scroll-doubled", VOLUME_SAMPLING, "new Vector4(scroll.x, scroll.y)", "new Vector4(scroll.x * 2f, scroll.y)", "lowered-scroll"),
("lower-scale-halved", VOLUME_SAMPLING, 'Shader.SetGlobalFloat("_FlowScale", flow.GlobalScale);', 'Shader.SetGlobalFloat("_FlowScale", flow.GlobalScale * .5f);', "lowered-settings"),
("lower-frame-clock", VOLUME_SAMPLING, "FlowField.Scroll(flow, flowClock)", "FlowField.Scroll(flow, flowClock + Time.realtimeSinceStartup)", "lowered-scroll"),
("lower-cycle-frame-clock", VOLUME_SAMPLING, "FlowField.Cycle(flowClock, flow.Period)", "FlowField.Cycle(Time.realtimeSinceStartup, flow.Period)", "lowered-cycle"),
("lower-keywords-lookup-only", VOLUME_SAMPLING, 'GlobalKeyword.Create("FLOW_GLOBAL")', 'new GlobalKeyword("FLOW_GLOBAL")', "flow-keywords"),
("csharp-scale-doubled", FLOW_FIELD, "var field = position / settings.GlobalScale;", "var field = position / (settings.GlobalScale * 2f);", "global"),
("asset-amplitude", SETTINGS_ASSET, " GlobalAmplitude: 15\n", " GlobalAmplitude: 14\n", "authored-flow"),
("hlsl-noise-frame-clock", CGINC, "_NebulaNoiseTime * _NebulaNoiseSpeed", "_Time.y * _NebulaNoiseSpeed", "nebula-noise-clock"),
("parity-slope-pragma-removed", PARITY_COMPUTE, "#pragma multi_compile __ FLOW_SLOPE", "", "flow-keywords"),
("scene-stardust-pragma-removed", STARDUST_COMPUTE, "#pragma multi_compile __ FLOW_GLOBAL", "", "scene-stardust", SCENE),
("scene-cloud-include-without-pragmas", CLOUD_SHADER, '#include_with_pragmas "Assets/Shaders/Volumetric.cginc"', '#include "Assets/Shaders/Volumetric.cginc"', "scene-cloud-keywords", SCENE),
("scene-keyword-in-field-initializer", VOLUME_SAMPLING, "static GlobalKeyword? _keywordFlowGlobal;", 'static GlobalKeyword? _keywordFlowGlobal = GlobalKeyword.Create("FLOW_GLOBAL");', "scene-presenter-exception", SCENE),
("scene-noise-time-frame-clock", VOLUME_SAMPLING, '"_NebulaNoiseTime", (float) clock', '"_NebulaNoiseTime", Time.realtimeSinceStartup', "scene-noise-clock", SCENE),
]
def run_probe(log: Path, entry: str = PARITY) -> tuple[int, str]:
log.unlink(missing_ok=True)
proc = subprocess.run(
[UNITY_EXE, "-batchmode", "-projectPath", str(REPO_ROOT),
"-executeMethod", entry, "-logFile", str(log)],
timeout=1800,
)
return proc.returncode, log.read_text(encoding="utf-8", errors="replace")
def main() -> int:
only = set()
if "--only" in sys.argv:
only = set(sys.argv[sys.argv.index("--only") + 1].split(","))
scratch = REPO_ROOT / "tests" / "_scratch_flow_parity"
scratch.mkdir(parents=True, exist_ok=True)
failures: list[str] = []
for entry, name in ((PARITY, "FlowFieldParityVerify"), (SCENE, "FlowFieldSceneVerify")):
print(f"\n=== control: unmutated tree, {name} ===")
code, text = run_probe(scratch / f"control-{name}.log", entry)
if code != 0 or f"[{name}] PASS" not in text:
print("control FAILED: expected exit 0 and PASS on the unmutated tree")
return 1
print("control OK: exit 0, PASS")
for label, rel, before, after, check, *rest in MUTANTS:
entry = rest[0] if rest else PARITY
if only and label not in only:
continue
path = REPO_ROOT / rel
original = path.read_bytes()
text_in = original.decode("utf-8")
newline = "\r\n" if "\r\n" in text_in else "\n"
b, a = before.replace("\n", newline), after.replace("\n", newline)
if text_in.count(b) != 1:
failures.append(f"{label}: anchor occurs {text_in.count(b)} times in {rel}, expected exactly once")
continue
print(f"\n=== mutant {label} ({rel}) ===")
try:
path.write_bytes(text_in.replace(b, a).encode("utf-8"))
code, text = run_probe(scratch / f"{label}.log", entry)
finally:
path.write_bytes(original)
named = f"FAIL {check}" in text or f"-{check}:" in text
if code != 0 and named:
print(f"OK: caught, the probe named {check}")
elif code != 0:
failures.append(f"{label}: red, but not for {check} (compile error or another check)")
else:
failures.append(f"{label}: SURVIVED")
for f in failures:
print("FAIL:", f)
return 1 if failures else 0
if __name__ == "__main__":
sys.exit(main())