Merge remote-tracking branch 'origin/master' into eureka/aetheria-release-mods-in-tree

This commit is contained in:
Meta Vens 2026-10-10 06:46:41 +02:00
commit ff1f5e9ebd
267 changed files with 15509 additions and 7503 deletions

View file

@ -0,0 +1,534 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Linq;
using System.Reflection;
using UniRx;
using Xunit;
using static CultMath.math;
using float2 = CultMath.float2;
using float3 = CultMath.float3;
using int2 = CultMath.int2;
// Ballistic flight: a round's flight is presentation (ruling projectile-flight-is-presentation). The simulation publishes
// the facts (the PendingShot's frozen origin, direction, speed, fire time and arrival, the outcome with its commit tick,
// impact cell and burst point) and DrawAhead's statics draw the round from them: Round the one statement of where a round
// is at a sim time, Impact where a hit lands on the target's drawn pose, RoundEnd and RoundOver when its drawn flight
// ends. FireControl owns none of it (ruling direct-arrival-keep-timing: damage keeps landing at the arrival time, the
// hit is drawn at its cell). Unity's Projectile calls Round and integrates nothing, so these tests pin the drawing
// against first principles (the shooter's position, the aim, the authored velocity and range, the hull's own frame)
// rather than against the code that computes it. Shares the Cut 12.4 engagement fixture.
public sealed partial class FireControlCut124Tests
{
private const float BallisticSpeed = 20f;
// A no-lock proximity round: flies the aim line (2,1) to max range, bursting there.
private Engagement FireBurstRound(out float3 origin)
{
var e = Build(TestSettings(), SolidShape(5, 4), velocity: BallisticSpeed, fuse: WeaponFuse.Proximity, blastRadius: 4f,
damage: 100f, weaponRange: NoLockRange);
Aim(e, float2(2, 1));
e.Shooter.SetTarget(TargetRef.None);
origin = e.Shooter.Position;
FireControl.Fire(e.Weapon, e.WeaponItem, e.Shooter);
return e;
}
// What the sim publishes for a shot, as a presenter holds it: only the result (no impact, no burst point).
private static ShotOutcome Known(in PendingShot shot, ShotResult result) =>
new ShotOutcome { ShotId = shot.ShotId, Result = result, ArrivalIn = max(0f, shot.ArrivalTime - shot.CommitTime) };
// A hit on a cell of the target, committed at `commit`: ArrivalIn is how long after the commit damage lands.
private static ShotOutcome Hit(in PendingShot shot, Entity target, int2 cell, float commit) =>
new ShotOutcome { ShotId = shot.ShotId, Result = ShotResult.Hit, Target = target, Cell = cell, ArrivalIn = shot.ArrivalTime - commit };
// The hull's occupied coordinate farthest from its centre of mass: a cell well off the target's position.
private static int2 FarCell(Engagement e) =>
e.HullData.Shape.Coordinates.OrderByDescending(c => length((float2) c - e.HullData.Shape.CenterOfMass)).First();
[Fact]
public void ARoundIsDrawnOnItsFiredLine()
{
// Burst round: leaves the shooter, is where its own speed puts it a second in, and ends on the burst point.
var e = FireBurstRound(out var origin);
ShotOutcome outcome = null;
PendingShot burst = default;
using var c = e.Zone.ShotCommitted.Subscribe(o =>
{
outcome = o;
e.Zone.TryGetShot(o.ShotId, out burst);
});
e.Zone.Update(.01f);
Assert.NotNull(outcome);
Assert.True(outcome.HasBurstPoint);
var aim = normalize(float2(2, 1));
// The shooter moves on after the round left: the line is the one frozen at Fire, not one drawn from where it is now.
e.Shooter.Position += float3(7, 0, 3);
var start = DrawAhead.Round(burst, null, burst.FireOrigin, 0f, burst.FireTime, 0f);
Assert.Equal(origin.x, start.x, 3);
Assert.Equal(origin.z, start.z, 3);
var second = DrawAhead.Round(burst, null, burst.FireOrigin, 0f, burst.FireTime + 1f, 0f);
Assert.Equal(origin.x + aim.x * BallisticSpeed, second.x, 3);
Assert.Equal(origin.z + aim.y * BallisticSpeed, second.z, 3);
foreach (var known in new[] { null, outcome })
foreach (var later in new[] { 0f, 1f, 50f })
{
var arrival = DrawAhead.Round(burst, known, burst.FireOrigin, 0f, burst.ArrivalTime + later, 0f);
Assert.Equal(burst.BurstPosition.x, arrival.x, 3);
Assert.Equal(burst.BurstPosition.z, arrival.z, 3);
}
// Past the weapon's range it is held at the range point, however late it is asked.
var held = DrawAhead.Round(burst, Known(burst, ShotResult.Miss), burst.FireOrigin, 0f, burst.FireTime + NoLockRange / BallisticSpeed + 50f, 0f);
Assert.Equal(origin.x + aim.x * NoLockRange, held.x, 3);
Assert.Equal(origin.z + aim.y * NoLockRange, held.z, 3);
// Before it was fired it is still at the origin, not behind it.
var before = DrawAhead.Round(burst, null, burst.FireOrigin, 0f, burst.FireTime - 5f, 0f);
Assert.Equal(origin.x, before.x, 3);
Assert.Equal(origin.z, before.z, 3);
// Direct round at a stationary target 100 ahead (+z): arrives on the target, and a miss would fly on to the weapon's range.
var d = Build(TestSettings(), SolidShape(5, 4), velocity: BallisticSpeed, weaponRange: 1000f);
var dOrigin = d.Shooter.Position;
FireControl.Fire(d.Weapon, d.WeaponItem, d.Shooter);
var direct = SafeAssert.OnlyShot(d.Zone);
// A round not known to miss waits at its arrival point however late it is asked.
foreach (var at in new[] { direct.ArrivalTime, direct.FireTime + 99f })
{
var waiting = DrawAhead.Round(direct, null, direct.FireOrigin, 0f, at, 0f);
Assert.Equal(d.Target.Position.x, waiting.x, 2);
Assert.Equal(d.Target.Position.z, waiting.z, 2);
}
Assert.Equal(dOrigin.z + 100f / 2f, DrawAhead.Round(direct, null, direct.FireOrigin, 0f, direct.FireTime + 2.5f, 0f).z, 2);
var heldDirect = DrawAhead.Round(direct, Known(direct, ShotResult.Miss), direct.FireOrigin, 0f, direct.FireTime + 1000f / BallisticSpeed + 99f, 0f);
Assert.Equal(dOrigin.z + 1000f, heldDirect.z, 2);
}
// A round with no speed (the weapon authors Velocity 0, or effectively 0) does not fly: it is at its origin at any
// time, and is not stretched along its line by a vanishing speed over the range it would need forever to cover.
[Fact]
public void ARoundWithNoSpeedStaysAtItsOrigin()
{
var e = Build(TestSettings(), SolidShape(5, 4), velocity: .005f, weaponRange: 1000f);
var origin = e.Shooter.Position;
FireControl.Fire(e.Weapon, e.WeaponItem, e.Shooter);
var shot = SafeAssert.OnlyShot(e.Zone);
var late = DrawAhead.Round(shot, Known(shot, ShotResult.Miss), shot.FireOrigin, 0f, shot.FireTime + 5000f, 0f);
Assert.Equal(origin.x, late.x, 3);
Assert.Equal(origin.z, late.z, 3);
}
[Fact]
public void SpeedIsFrozenAtFire()
{
var e = FireBurstRound(out var origin);
var shot = SafeAssert.OnlyShot(e.Zone);
Assert.Equal(BallisticSpeed, shot.Speed, 4);
// The stat changes after the round left, and the weapon re-reads it.
((InstantWeaponData) e.Weapon.WeaponData).Velocity = Constant(BallisticSpeed * 5f);
e.Weapon.Execute(0f);
Assert.Equal(BallisticSpeed * 5f, e.Weapon.Velocity, 4);
var after = SafeAssert.OnlyShot(e.Zone);
Assert.Equal(BallisticSpeed, after.Speed, 4);
var aim = normalize(float2(2, 1));
var at = DrawAhead.Round(after, null, after.FireOrigin, 0f, after.FireTime + 1f, 0f);
Assert.Equal(origin.x + aim.x * BallisticSpeed, at.x, 3);
Assert.Equal(origin.z + aim.y * BallisticSpeed, at.z, 3);
}
[Fact]
public void ARoundIsPure()
{
var e = FireDirectRound(20f, 1000f);
var shot = SafeAssert.OnlyShot(e.Zone);
e.Target.Direction = normalize(float2(1, 2));
e.Target.TurnRate = 3f;
var time = e.Zone.Time;
var entities = e.Zone.Entities.ToList();
var positions = entities.Select(x => x.Position).ToList();
var velocities = entities.Select(x => x.Velocity).ToList();
var directions = entities.Select(x => x.Direction).ToList();
var turnRates = entities.Select(x => x.TurnRate).ToList();
var barrel = shot.FireOrigin + float3(1, .5f, -2);
var cell = FarCell(e);
foreach (var known in new[] { null, Known(shot, ShotResult.Miss), Hit(shot, e.Target, cell, shot.CommitTime) })
for (var i = 0; i < 25; i++)
{
var at = shot.FireTime + i * .37f;
DrawAhead.Round(shot, known, barrel, .1f, at, .01f);
DrawAhead.RoundOver(shot, known, at, .01f);
DrawAhead.RoundEnd(shot, known?.Result);
DrawAhead.Impact(e.Target, cell, .01f * i);
}
Assert.Equal(time, e.Zone.Time);
Assert.True(e.Zone.PendingShots.Count == 1 && e.Zone.PendingShots[0].Equals(shot), "the pending shot changed");
Assert.True(e.Zone.Entities.SequenceEqual(entities), "the zone's entities changed");
Assert.True(entities.Select(x => x.Position).SequenceEqual(positions), "an entity moved");
Assert.True(entities.Select(x => x.Velocity).SequenceEqual(velocities), "an entity's velocity changed");
Assert.True(entities.Select(x => x.Direction).SequenceEqual(directions), "an entity turned");
Assert.True(entities.Select(x => x.TurnRate).SequenceEqual(turnRates), "an entity's turn rate changed");
}
// The weapon's Range is frozen with the rest: a round that misses flies on to the range it left with, whatever the stat
// becomes after.
[Fact]
public void RangeIsFrozenAtFire()
{
var e = FireBurstRound(out var origin);
var shot = SafeAssert.OnlyShot(e.Zone);
Assert.Equal(NoLockRange, shot.MaxRange, 4);
var endBefore = DrawAhead.RoundEnd(shot, ShotResult.Miss);
// The stat changes after the round left, and the weapon re-reads it.
((InstantWeaponData) e.Weapon.WeaponData).Range = Constant(NoLockRange * 5f);
e.Weapon.Execute(0f);
Assert.Equal(NoLockRange * 5f, e.Weapon.Range, 4);
var after = SafeAssert.OnlyShot(e.Zone);
Assert.Equal(NoLockRange, after.MaxRange, 4);
Assert.Equal(endBefore, DrawAhead.RoundEnd(after, ShotResult.Miss), 4);
var aim = normalize(float2(2, 1));
var held = DrawAhead.Round(after, Known(after, ShotResult.Miss), after.FireOrigin, 0f, after.FireTime + 1000f, 0f);
Assert.Equal(origin.x + aim.x * NoLockRange, held.x, 3);
Assert.Equal(origin.z + aim.y * NoLockRange, held.z, 3);
}
// A direct round at a stationary target `targetRange` ahead (+z) of the shooter, weapon Range `range`, at `speed`;
// or, with atNothing, the same weapon fired along +z at no target.
private Engagement FireDirectRound(float speed, float range, float targetRange = 100f, bool atNothing = false)
{
var e = Build(TestSettings(), SolidShape(5, 4), velocity: speed, weaponRange: range, targetRange: targetRange);
if (atNothing)
{
Aim(e, float2(0, 1));
e.Shooter.SetTarget(TargetRef.None);
}
FireControl.Fire(e.Weapon, e.WeaponItem, e.Shooter);
return e;
}
// A hit, a burst or an outcome not yet known ends at the round's arrival; a miss flies on to the weapon's range and
// never ends short of its own arrival; only a published miss is over by the clock.
[Fact]
public void RoundEndAndRoundOverAreTheOutcomesEnd()
{
foreach (var speed in new[] { 20f, 200f })
{
var d = FireDirectRound(speed, 1000f);
var direct = SafeAssert.OnlyShot(d.Zone);
Assert.Equal(direct.FireTime + 100f / speed, direct.ArrivalTime, 4);
Assert.Equal(direct.FireTime + 100f / speed, DrawAhead.RoundEnd(direct, null), 4);
Assert.Equal(direct.FireTime + 100f / speed, DrawAhead.RoundEnd(direct, ShotResult.Hit), 4);
Assert.Equal(direct.FireTime + 100f / speed, DrawAhead.RoundEnd(direct, ShotResult.Burst), 4);
Assert.Equal(direct.FireTime + 1000f / speed, DrawAhead.RoundEnd(direct, ShotResult.Miss), 4);
Assert.False(DrawAhead.RoundOver(direct, null, direct.FireTime + 10000f, 0f));
foreach (var result in new[] { ShotResult.Hit, ShotResult.Burst })
Assert.False(DrawAhead.RoundOver(direct, Known(direct, result), direct.FireTime + 10000f, 0f));
var missEnd = direct.FireTime + 1000f / speed;
Assert.False(DrawAhead.RoundOver(direct, Known(direct, ShotResult.Miss), missEnd - .01f, 0f));
Assert.True(DrawAhead.RoundOver(direct, Known(direct, ShotResult.Miss), missEnd, 0f));
// A target beyond the weapon's range: a miss never ends short of its own arrival.
var far = FireDirectRound(speed, 100f, targetRange: 150f);
var beyond = SafeAssert.OnlyShot(far.Zone);
Assert.Equal(beyond.FireTime + 150f / speed, beyond.ArrivalTime, 4);
Assert.Equal(beyond.FireTime + 150f / speed, DrawAhead.RoundEnd(beyond, ShotResult.Miss), 4);
// A round fired at nothing arrives where it left, and a miss flies on to the range.
var none = FireDirectRound(speed, 100f, atNothing: true);
var nothing = SafeAssert.OnlyShot(none.Zone);
Assert.Equal(nothing.FireTime, nothing.ArrivalTime, 4);
Assert.Equal(nothing.FireTime, DrawAhead.RoundEnd(nothing, null), 4);
Assert.Equal(nothing.FireTime + 100f / speed, DrawAhead.RoundEnd(nothing, ShotResult.Miss), 4);
}
}
// The frame falls Lead (< one step) after the last step, so a hit or burst is drawn at Zone.Time + Lead; it must stay
// on the arrival point until the sim resolves it, and only a published miss flies on.
[Theory]
[InlineData(20f)]
[InlineData(200f)]
public void ARoundIsDrawnNoFurtherThanItsArrivalUntilItMisses(float speed)
{
var e = FireDirectRound(speed, 1000f);
var shot = SafeAssert.OnlyShot(e.Zone);
var origin = shot.FireOrigin;
const float step = 1f / 30f;
foreach (var lead in new[] { 0f, step / 2f, .999f * step })
{
var waiting = DrawAhead.Round(shot, null, shot.FireOrigin, 0f, shot.ArrivalTime, lead);
Assert.Equal(origin.x, waiting.x, 3);
Assert.Equal(origin.z + 100f, waiting.z, 3);
var missed = DrawAhead.Round(shot, Known(shot, ShotResult.Miss), shot.FireOrigin, 0f, shot.ArrivalTime, lead);
Assert.Equal(origin.x, missed.x, 3);
Assert.Equal(origin.z + 100f + lead * speed, missed.z, 3);
}
for (var time = shot.FireTime; time <= shot.ArrivalTime + 1f; time += 1f / 144f)
{
var drawn = DrawAhead.Round(shot, null, shot.FireOrigin, 0f, time, 0f);
Assert.True(drawn.z - origin.z <= 100f + 1e-3f, "the round was drawn past its arrival point");
}
}
// A no-lock contact round stopped by a hull short of max range has its arrival shortened at the commit; the
// simulation writes the record back before ShotCommitted fires, so a presenter re-reading it there draws the stop
// at the committed arrival, not the fire-time copy's.
[Fact]
public void TheCommittedRecordCarriesTheCommittedArrival()
{
var e = Build(TestSettings(), SolidShape(5, 4), velocity: 20f, fuse: WeaponFuse.Contact, blastRadius: 4f, damage: 100f,
weaponRange: NoLockRange);
e.Shooter.SetTarget(TargetRef.None);
Aim(e, float2(0, 1));
AddShip(e, PointAlong(e, float2(0, 1), 25f), 1f, 300);
ShotOutcome outcome = null;
PendingShot record = default;
var found = false;
using var c = e.Zone.ShotCommitted.Subscribe(o =>
{
outcome = o;
found = e.Zone.TryGetShot(o.ShotId, out record);
});
FireControl.Fire(e.Weapon, e.WeaponItem, e.Shooter);
var fired = SafeAssert.OnlyShot(e.Zone);
Assert.False(fired.Committed);
e.Zone.Update(.01f);
Assert.True(found, "the committed record was not readable when ShotCommitted fired");
Assert.True(record.Committed);
Assert.Equal(fired.FireTime + 3f, fired.ArrivalTime, 2);
Assert.Equal(fired.FireTime + 1.05f, record.ArrivalTime, 2);
Assert.True(record.ArrivalTime < fired.ArrivalTime);
var stop = DrawAhead.Round(record, outcome, record.FireOrigin, 0f, record.ArrivalTime, 0f);
var expected = outcome.HasBurstPoint
? outcome.BurstPoint
: record.FireOrigin.xz + record.TravelDirection * (20f * (record.ArrivalTime - record.FireTime));
Assert.Equal(expected.x, stop.x, 3);
Assert.Equal(expected.y, stop.z, 3);
foreach (var later in new[] { 0f, .5f, 5f })
{
var drawn = DrawAhead.Round(record, outcome, record.FireOrigin, 0f, record.ArrivalTime + later, 0f);
Assert.Equal(expected.x, drawn.x, 3);
Assert.Equal(expected.y, drawn.z, 3);
}
}
// The barrel is only where the round is first seen: its offset from the sim line decays linearly to nothing over
// blendTime sim seconds from FireTime.
[Theory]
[InlineData(.1f)]
[InlineData(.25f)]
public void TheBarrelBlendDecaysOnSimTime(float blend)
{
var e = FireBurstRound(out var origin);
var shot = SafeAssert.OnlyShot(e.Zone);
var aim = normalize(float2(2, 1));
var offset = float3(1, .5f, -2);
var barrel = shot.FireOrigin + offset;
float3 Line(float dt) => float3(origin.x + aim.x * BallisticSpeed * dt, origin.y, origin.z + aim.y * BallisticSpeed * dt);
void Close(float3 want, float3 got)
{
Assert.Equal(want.x, got.x, 3);
Assert.Equal(want.y, got.y, 3);
Assert.Equal(want.z, got.z, 3);
}
Close(barrel, DrawAhead.Round(shot, null, barrel, blend, shot.FireTime, 0f));
Close(Line(blend / 2f) + offset * .5f, DrawAhead.Round(shot, null, barrel, blend, shot.FireTime + blend / 2f, 0f));
Close(Line(blend), DrawAhead.Round(shot, null, barrel, blend, shot.FireTime + blend, 0f));
Close(Line(2f * blend), DrawAhead.Round(shot, null, barrel, blend, shot.FireTime + 2f * blend, 0f));
Close(Line(0f), DrawAhead.Round(shot, null, barrel, 0f, shot.FireTime, 0f));
}
// Placement depends on sim time alone: any history of frames walked to a checkpoint draws what a fresh call draws, which
// is the frozen line at the frozen speed.
[Theory]
[InlineData(20f)]
[InlineData(200f)]
public void ARoundIsAFunctionOfSimTime(float speed)
{
var e = FireDirectRound(speed, 1000f);
var shot = SafeAssert.OnlyShot(e.Zone);
var checkpoints = new[] { .05f, .3f, 1f, 3f };
var histories = new[] { new[] { 1f / 144f }, new[] { 1f / 30f }, new[] { 1f / 144f, 1f / 30f, 1f / 90f } };
var miss = Known(shot, ShotResult.Miss);
foreach (var frames in histories)
{
var elapsed = 0f;
var frame = 0;
foreach (var checkpoint in checkpoints)
{
while (elapsed + 1e-4f < checkpoint)
{
elapsed = min(checkpoint, elapsed + frames[frame++ % frames.Length]);
DrawAhead.Round(shot, miss, shot.FireOrigin, .1f, shot.FireTime + elapsed, 0f);
}
var drawn = DrawAhead.Round(shot, miss, shot.FireOrigin, .1f, shot.FireTime + checkpoint, 0f);
var fresh = DrawAhead.Round(shot, miss, shot.FireOrigin, .1f, shot.FireTime + checkpoint, 0f);
// A frame that falls `lead` after the step draws what the sim time lead later would.
foreach (var lead in new[] { 1f / 60f, 1f / 90f })
{
var ahead = DrawAhead.Round(shot, miss, shot.FireOrigin, .1f, shot.FireTime + checkpoint - lead, lead);
Assert.Equal(fresh.x, ahead.x, 3);
Assert.Equal(fresh.y, ahead.y, 3);
Assert.Equal(fresh.z, ahead.z, 3);
}
Assert.Equal(fresh.z, drawn.z, 3);
Assert.Equal(shot.FireOrigin.z + speed * min(checkpoint, 1000f / speed), drawn.z, 3);
Assert.Equal(shot.FireOrigin.x, drawn.x, 3);
Assert.Equal(shot.FireOrigin.y, drawn.y, 3);
}
}
}
// A hit ends at its impact cell on the target's drawn pose when damage lands, not at the arrival point of the line
// frozen at Fire (ruling direct-arrival-keep-timing): the target has moved and turned since, and is drawn ahead by its
// last step's velocity and turn. The expected point is computed apart from DrawAhead, by moving the entity itself and
// asking its own schematic frame (Entity.ToWorldPoint) where the cell is.
[Theory]
[InlineData(20f)]
[InlineData(200f)]
public void AHitEndsAtItsImpactCellOnTheTargetsDrawnPose(float speed)
{
var e = Build(TestSettings(), SolidShape(5, 4), velocity: speed, weaponRange: 1000f);
e.Target.Velocity = float2(10, 0);
FireControl.Fire(e.Weapon, e.WeaponItem, e.Shooter);
var shot = SafeAssert.OnlyShot(e.Zone);
Assert.True(shot.TravelDirection.x > 0f, "the round did not lead the target");
const float step = 1f / 30f;
e.Target.Position += float3(40, 0, 0);
e.Target.Direction = normalize(float2(1, 2));
e.Target.TurnRate = 3f;
var cell = FarCell(e);
var hit = Hit(shot, e.Target, cell, shot.CommitTime);
var arrivalOnTheLine = DrawAhead.Round(shot, null, shot.FireOrigin, 0f, shot.ArrivalTime, 0f);
var cellSize = e.Items.GameplaySettings.SchematicCellSize;
foreach (var lead in new[] { 0f, step / 2f, .999f * step })
{
var position = e.Target.Position;
var direction = e.Target.Direction;
e.Target.Position += float3(e.Target.Velocity.x, 0, e.Target.Velocity.y) * lead;
e.Target.Direction = mul(e.Target.Direction, CultMath.float2x2.Rotate(e.Target.TurnRate * lead));
var cellPoint = e.Target.ToWorldPoint((float2) cell);
var expected = float3(cellPoint.x, e.Target.Position.y, cellPoint.y);
e.Target.Position = position;
e.Target.Direction = direction;
Assert.True(length((expected - arrivalOnTheLine).xz) > cellSize, "the fixture put the cell on the frozen line's arrival point");
var impact = DrawAhead.Impact(e.Target, cell, lead);
Assert.Equal(expected.x, impact.x, 3);
Assert.Equal(expected.y, impact.y, 3);
Assert.Equal(expected.z, impact.z, 3);
foreach (var simTime in new[] { shot.ArrivalTime, shot.ArrivalTime + .5f })
{
var drawn = DrawAhead.Round(shot, hit, shot.FireOrigin, .1f, simTime, lead);
Assert.Equal(expected.x, drawn.x, 3);
Assert.Equal(expected.y, drawn.y, 3);
Assert.Equal(expected.z, drawn.z, 3);
}
}
}
// A hit leaves its frozen line at the commit tick and steers onto its end by the time damage lands: before the commit it
// is on the line, half way through the steer it is half way to the impact cell, and a frame drawn ahead by the clock's
// lead places the round where the sim time that much later would.
[Fact]
public void ASteeredRoundLeavesItsLineAtTheCommit()
{
var e = FireDirectRound(20f, 1000f);
var shot = SafeAssert.OnlyShot(e.Zone);
Assert.Equal(shot.FireTime + 5f, shot.ArrivalTime, 3);
var cell = FarCell(e);
var commit = shot.ArrivalTime - 2f;
var hit = Hit(shot, e.Target, cell, commit);
foreach (var t in new[] { commit - 1f, commit })
{
var steered = DrawAhead.Round(shot, hit, shot.FireOrigin, 0f, t, 0f);
var line = DrawAhead.Round(shot, null, shot.FireOrigin, 0f, t, 0f);
Assert.Equal(line.x, steered.x, 3);
Assert.Equal(line.y, steered.y, 3);
Assert.Equal(line.z, steered.z, 3);
}
var m = commit + 1f;
var onTheLine = DrawAhead.Round(shot, null, shot.FireOrigin, 0f, m, 0f);
var end = DrawAhead.Impact(e.Target, cell, 0f);
Assert.True(length((end - onTheLine).xz) > 1f, "the fixture put the impact cell on the line");
var halfway = DrawAhead.Round(shot, hit, shot.FireOrigin, 0f, m, 0f);
Assert.Equal(onTheLine.x + (end.x - onTheLine.x) * .5f, halfway.x, 3);
Assert.Equal(onTheLine.y + (end.y - onTheLine.y) * .5f, halfway.y, 3);
Assert.Equal(onTheLine.z + (end.z - onTheLine.z) * .5f, halfway.z, 3);
var ahead = DrawAhead.Round(shot, hit, shot.FireOrigin, 0f, m - .02f, .02f);
Assert.Equal(halfway.x, ahead.x, 3);
Assert.Equal(halfway.y, ahead.y, 3);
Assert.Equal(halfway.z, ahead.z, 3);
}
// The sim states facts and draws nothing: no drawing function, and no lead, blend or barrel, lives in FireControl;
// those belong to DrawAhead, the presentation statics.
[Fact]
public void FireControlHasNoDrawingFunctions()
{
const BindingFlags all = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
var methods = typeof(FireControl).GetMethods(all).Cast<MethodBase>().Concat(typeof(FireControl).GetConstructors(all)).ToList();
Assert.NotEmpty(methods);
foreach (var method in methods)
{
Assert.False(method.Name.StartsWith("Round") || method.Name.StartsWith("Draw"), "FireControl has a drawing function: " + method.Name);
foreach (var parameter in method.GetParameters())
Assert.False(new[] { "lead", "blendTime", "barrel" }.Contains(parameter.Name), "FireControl takes a drawing parameter: " + parameter.Name);
}
foreach (var name in new[] { "Round", "Impact", "RoundOver", "RoundEnd" })
Assert.NotNull(typeof(DrawAhead).GetMethod(name, BindingFlags.Public | BindingFlags.Static));
}
// A proximity round at a target that recedes faster than the round closes bursts at the weapon's range, pulled back
// along its line, while it arrives when it has flown the distance the target was fired at: its burst point is not
// the line at its arrival. The end is the sim's burst point, so a presenter that ended at the arrival line would
// end the tracer short of where the round burst.
[Fact]
public void ABurstRoundEndsAtItsBurstPointNotItsArrivalLine()
{
var e = Build(TestSettings(), SolidShape(5, 4), velocity: BallisticSpeed, fuse: WeaponFuse.Proximity, blastRadius: 4f,
damage: 100f, weaponRange: NoLockRange, targetRange: 50f);
e.Target.Velocity = float2(0, 15);
ShotOutcome outcome = null;
using var c = e.Zone.ShotCommitted.Subscribe(o => outcome = o);
FireControl.Fire(e.Weapon, e.WeaponItem, e.Shooter);
var origin = SafeAssert.OnlyShot(e.Zone).FireOrigin;
for (var i = 0; i < 100 && outcome == null; i++) e.Zone.Update(.05f);
Assert.NotNull(outcome);
Assert.True(outcome.HasBurstPoint);
Assert.True(e.Zone.TryGetShot(outcome.ShotId, out var record));
Assert.Equal(origin.x, outcome.BurstPoint.x, 3);
Assert.Equal(origin.z + NoLockRange, outcome.BurstPoint.y, 3);
Assert.Equal(origin.z + 50f, DrawAhead.Round(record, null, record.FireOrigin, 0f, record.ArrivalTime, 0f).z, 3);
var stop = DrawAhead.Round(record, outcome, record.FireOrigin, 0f, record.ArrivalTime, 0f);
Assert.Equal(outcome.BurstPoint.x, stop.x, 3);
Assert.Equal(outcome.BurstPoint.y, stop.z, 3);
}
}

View file

@ -10,7 +10,7 @@ using static CultMath.math;
// Cut 7 (docs/stats-and-power-target.md): "Continuous consumers brown out through a power supply curve on
// their performance stats. An exponent is enough." Cut 6 wired the curve itself (PowerCurveTests.cs) and the
// bus already writes a real fractional grant (PowerBusTests.cs, PowerTierTests.cs), but every continuous
// consumer still gated its own effect on Item.PowerSupply >= 1f (Thruster.Execute, AetherDrive.Execute,
// consumer still gated its own effect on Item.PowerSupply >= 1f (Thruster.Execute,
// Radiator.Execute, ConstantWeapon.Execute, EnergyDraw.Execute) -- so a partial grant read exactly like none,
// the flicking-off bug the ruling names. This file pins each behaviour's own gate removal: a partial grant now
// produces a reduced effect, a full grant is unchanged, a zero grant still produces nothing, the degradation
@ -18,12 +18,11 @@ using static CultMath.math;
// rule, Cut 4) is untouched by any of it. Each rule has a matching mutation in
// tests/mutation_tests_stats_power_cut7.py.
//
// F6 (docs/stats-and-power-cut.md, Soul pass 2026-09-19) surfaced a real conflict this file's Radiator and
// AetherDrive fixtures happened to sit on top of, unnoticed because the pre-F6 registry only named each
// F6 (docs/stats-and-power-cut.md, Soul pass 2026-09-19) surfaced a real conflict this file's Radiator
// fixture happened to sit on top of, unnoticed because the pre-F6 registry only named each
// consumer's own top-level request field. Radiator.PowerRequest's own early-out reads PumpedHeat AND WasteHeat
// (to decide whether the pump can keep up this tick); AetherDrive.PowerRequest's spin-up arithmetic reads
// Torque, LambdaMultiplier, MaximumRpm and PassiveCoupling. Cut 7 asks for the brownout curve to live on exactly
// the stats these two behaviours actually curve (PumpedHeat, Torque), but F6 forbade a PowerSupply term on any
// (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).
// The six tests below that authored one were marked Skip rather than deleted or silently reworked to hide the
@ -32,8 +31,8 @@ using static CultMath.math;
//
// Nominal-request ruling (docs/stats-and-power-cut.md, operator ruling 2026-09-19) is that future pass: a power
// request is evaluated nominally -- what the item wants at full supply, not what it is currently managing
// (EquippedItem.EvaluateNominalPower, Entity.cs). Radiator.PowerRequest and AetherDrive.PowerRequest now read
// PumpedHeat/Torque (and every other field in StatValidation.PowerRequestFields) through that nominal read, so
// (EquippedItem.EvaluateNominalPower, Entity.cs). Radiator.PowerRequest now reads
// PumpedHeat (and every other field in StatValidation.PowerRequestFields) through that nominal read, so
// the same stat can carry a PowerSupply term (curved for Execute's real effect) AND be a request field, without
// the request depending on its own answer -- there is no more oscillation to reproduce, because the request no
// longer reads the live grant at all. StatValidation.ValidateNoPowerSupplyOnRequest (the static check F6 added
@ -64,14 +63,6 @@ public sealed class BrownoutTests : IDisposable
private static PerformanceStat Curved(float max, float exponent) =>
new PerformanceStat { Min = 0, Max = max, Terms = { new StatTerm { Source = StatSource.PowerSupply, Exponent = exponent } } };
// A flat Bezier (two keys, equal value, zero tangents): AetherDrive's TorqueProfile multiplies potential
// torque by this curve's value at the current rpm ratio -- flat at 1 keeps that multiplier out of the way of
// the PowerSupply curve under test.
private static BezierCurve FlatCurve(float value) => new BezierCurve
{
Keys = new[] { new float4(0, value, 0, 0), new float4(1, value, 0, 0) }
};
private static EquippableItem Mint(CultCache cache, ItemManager items, ItemData design) => new EquippableItem
{
Data = cache.RefOf<ItemData>(design),
@ -180,55 +171,6 @@ public sealed class BrownoutTests : IDisposable
Assert.Equal(.025f, half, 3);
}
// --- AetherDrive: PassiveCoupling = 1 engages the rotor regardless of axis input, so the drive can be
// --- exercised without threading Ship's own movement/torque classification -- Axis stays at Ship.Update's
// --- own default (0,0,Turn), and Turn is 0 by default. Rpm starts at 0,
// --- so decay(0, ...) contributes nothing and the whole tick's Rpm gain is exactly this behaviour's own
// --- spin-up under test. ---
private (float rpmGain, AetherDrive drive) RunAetherDrive(float reactorCharge, float exponent = 1)
{
using var cache = OpenCatalog(new AetherDriveData
{
RotorDiameter = float3(1, 1, 1), RotorMass = float3(1, 1, 1),
MaximumRpm = Constant(100), CouplingLambda = float3(1, 1, 1), LambdaMultiplier = Constant(1),
CouplingEfficiency = Constant(1), Torque = Curved(30, exponent), TorqueProfile = FlatCurve(1),
EnergyDraw = Constant(50), PassiveCoupling = Constant(1)
});
var ship = BuildShip(cache, reactorCharge);
ship.Update(1f);
var drive = ship.GetBehavior<AetherDrive>();
return (drive.Rpm.x, drive);
}
// Nominal-request ruling (docs/stats-and-power-cut.md, operator ruling 2026-09-19, see file header): Torque
// is a registered AetherDrive request field (PowerRequest's spin-up arithmetic reads it), but PowerRequest now
// reads it through EvaluateNominalPower (full-supply, undegraded), so Curved(...) on Torque is a legal
// catalog shape again -- Execute's own real, curved Evaluate is what actually degrades the spin-up below.
[Fact]
public void AetherDriveAtHalfGrantProducesReducedNotZeroNotFullSpinUp()
{
var (full, _) = RunAetherDrive(reactorCharge: 1000); // demand ~50, generation far exceeds it -> ratio 1
var (half, _) = RunAetherDrive(reactorCharge: 25); // demand ~50, generation 25 -> ratio .5
Assert.True(half > 0f && half < full, $"half={half} should sit strictly between 0 and full={full}");
}
[Fact]
public void AetherDriveAtFullGrantIsUnchangedFromToday()
{
var (full, drive) = RunAetherDrive(reactorCharge: 1000);
Assert.Equal(1f, drive.Item.PowerSupply, 3);
Assert.True(full > 0f);
}
[Fact]
public void AetherDriveAtZeroGrantProducesNothing()
{
var (zero, drive) = RunAetherDrive(reactorCharge: 0);
Assert.Equal(0f, drive.Item.PowerSupply, 3);
Assert.Equal(0f, zero, 4);
}
// --- Radiator: no explicit power gate survives Cut 7 at all -- PumpedHeat above is a plain Evaluate() read,
// --- so a curved PumpedHeat already pumps less under a partial grant, and waste heat is unaffected, so a
// --- starved radiator falls behind (the reduced-performance failure the ruling asks for) instead of the
@ -383,10 +325,10 @@ public sealed class BrownoutTests : IDisposable
// --- Nominal-request ruling (docs/stats-and-power-cut.md, operator ruling 2026-09-19): a direct probe of
// --- EquippedItem.EvaluateNominalPower itself, decoupled from any behaviour's own physical state (Radiator's
// --- temperature, AetherDrive's Rpm) so the only thing that can make it diverge from the ordinary Evaluate
// --- temperature) so the only thing that can make it diverge from the ordinary Evaluate
// --- is the item's own PowerSupply grant. Thruster's EnergyUsage carries the term here purely as a probe --
// --- not a shape BrownoutTests' other fixtures author -- because Thruster has no other tick-to-tick state
// --- that could confound the comparison the way Radiator's RadiatorTemperature or AetherDrive's Rpm would.
// --- that could confound the comparison the way Radiator's RadiatorTemperature would.
// --- Backs tests/mutation_tests_stats_power_nominal_request.py's own mutation of this exact method. ---
[Fact]
public void EvaluateNominalPowerIgnoresTheItemsCurrentPowerSupplyGrant()
@ -444,16 +386,4 @@ public sealed class BrownoutTests : IDisposable
$"expected tick 2's gate to stay open on the nominal PumpedHeat/WasteHeat ratio, got demand {secondDemand}");
}
// --- The same wiring check attempted on AetherDrive.PowerRequest's own Torque read does not carry over
// --- cleanly: torqueRatio (actualRpmDelta/potentialRpmDelta) self-cancels Torque's own magnitude whenever
// --- the rotor is not yet rpm-capped (both numerator and denominator scale with Torque, so the ratio -- and
// --- so the final draw -- comes out identical whether Torque is read nominally or through the curved
// --- Evaluate; verified empirically while building this fixture: reverting AetherDrive.PowerRequest to
// --- Evaluate produced byte-identical TotalDemand across two ticks, including once the rotor was pushed
// --- into its rpm cap). A black-box demand comparison cannot discriminate this call site the way it can
// --- Radiator's binary gate above. Its correctness rests instead on the identical pattern to Radiator's
// --- (same EvaluateNominalPower call, same EquippedItem mechanism EvaluateNominalPowerIgnoresTheItemsCurrent
// --- PowerSupplyGrant already pins) and on AetherDriveAtHalfGrantProducesReducedNotZeroNotFullSpinUp/
// --- AtFullGrantIsUnchangedFromToday/AtZeroGrantProducesNothing above, which exercise the real end-to-end
// --- Execute path this ruling exists to keep legal. Not part of the mutation harness for that reason.
}

View file

@ -0,0 +1,185 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
// Aetheria release, cut roles-backfill, rule CB-R1: a crafted design declares roles iff a stat varies with quality,
// every declared role is read by a non-flat stat, and every seller authors one ProductRole per role. These tests read
// the shipped catalog through the real reader.
public sealed class CatalogRoleTests
{
internal static IEnumerable<(string Name, PerformanceStat Stat)> StatsOf(EquippableItemData design) =>
design.Behaviors.Where(b => b != null)
.SelectMany(b => b.GetType().GetFields().Where(f => f.FieldType == typeof(PerformanceStat))
.Select(f => ($"{b.GetType().Name}.{f.Name}", (PerformanceStat)f.GetValue(b))))
.Where(s => s.Item2?.Terms != null);
private static PerformanceStat Stat(EquippableItemData design, string field) =>
Assert.Single(design.Behaviors.SelectMany(b => b.GetType().GetFields().Where(f => f.Name == field && f.FieldType == typeof(PerformanceStat)).Select(f => (PerformanceStat)f.GetValue(b))));
internal static string[] NamedQualityRoles(PerformanceStat stat) =>
stat.Terms.Where(t => t.Source == StatSource.Quality && !string.IsNullOrEmpty(t.Role)).Select(t => t.Role).ToArray();
// CB-R1 for one stat. A non-flat stat carries exactly one Quality term, it names a declared role, and its exponent is
// positive (a role that cannot move the stat is not read). A flat stat carries no Quality term that names a role.
// Returns the fault, or null.
internal static string StatFault(PerformanceStat stat, string[] declared)
{
var quality = stat.Terms.Where(t => t.Source == StatSource.Quality).ToArray();
if (stat.Min == stat.Max)
return quality.Any(t => !string.IsNullOrEmpty(t.Role)) ? $"is flat but a Quality term names [{string.Join(", ", NamedQualityRoles(stat))}]" : null;
if (quality.Length != 1)
return $"is non-flat with {quality.Length} Quality terms, not one";
if (string.IsNullOrEmpty(quality[0].Role) || !declared.Contains(quality[0].Role))
return $"is non-flat and reads [{quality[0].Role}], not one of its declared roles [{string.Join(", ", declared)}]";
return quality[0].Exponent > 0f ? null : $"is non-flat but its role \"{quality[0].Role}\" has exponent {quality[0].Exponent}";
}
// The whole of CB-R1 over every design in the catalog: each non-flat stat reads exactly one declared role, every
// declared role is read, and every seller authors each role once. Weapons, and designs of a kind the tool keeps a role
// map for, must also carry a non-flat stat (a design with no stat at all has nothing for quality to vary).
[Fact]
public void ShippedCatalogRolesAreLive()
{
using var cache = RestoredHullsTests.OpenCatalog();
var products = cache.GetAll<FactionProductData>().ToArray();
var broken = new List<string>();
foreach (var design in cache.GetAll<EquippableItemData>().OrderBy(i => i.Name, StringComparer.Ordinal))
{
var stats = StatsOf(design).ToArray();
var varying = stats.Where(s => s.Stat.Min != s.Stat.Max).ToArray();
var declared = (design.Roles ?? new List<ItemRole>()).Select(r => r.Name).OrderBy(r => r, StringComparer.Ordinal).ToArray();
foreach (var (name, stat) in stats)
{
var fault = StatFault(stat, declared);
if (fault != null) broken.Add($"{design.Name}: {name} {fault}");
}
var read = varying.SelectMany(s => NamedQualityRoles(s.Stat)).Distinct().OrderBy(r => r, StringComparer.Ordinal).ToArray();
if (!read.SequenceEqual(declared))
broken.Add($"{design.Name}: declares [{string.Join(", ", declared)}] but non-flat stats read [{string.Join(", ", read)}]");
if (varying.Length == 0 && stats.Length > 0 && (design is WeaponItemData || Program.HasRoleMap(design)))
broken.Add($"{design.Name}: every stat is flat");
foreach (var product in products.Where(p => p.Design.Key.Equals(cache.RefOf(design).Key)))
{
var authored = (product.Roles ?? new List<ProductRole>()).Select(r => r.Role).OrderBy(r => r, StringComparer.Ordinal).ToArray();
if (!authored.SequenceEqual(declared))
broken.Add($"{design.Name}: product \"{product.Name}\" authors [{string.Join(", ", authored)}], not each of [{string.Join(", ", declared)}] once");
}
}
Assert.True(broken.Count == 0, string.Join("\n", broken));
}
private static PerformanceStat Ranged(params StatTerm[] terms) => new PerformanceStat { Min = 1f, Max = 2f, Terms = terms.ToList() };
private static StatTerm Quality(string role, float exponent = 1f) => new StatTerm { Source = StatSource.Quality, Role = role, Exponent = exponent };
// The stat check refuses what the shipped catalog does not hold but a later content cut could author.
[Fact]
public void TheStatCheckRefusesGenericQualityDeadRolesAndNamedFlatStats()
{
var declared = new[] { "barrel" };
Assert.Null(StatFault(Ranged(Quality("barrel")), declared));
Assert.Null(StatFault(new PerformanceStat { Min = 3f, Max = 3f, Terms = new List<StatTerm>() }, declared));
Assert.NotNull(StatFault(Ranged(Quality("barrel"), Quality(null)), declared));
Assert.NotNull(StatFault(Ranged(Quality("barrel", 0f)), declared));
Assert.NotNull(StatFault(Ranged(Quality(null)), declared));
Assert.NotNull(StatFault(Ranged(Quality("bogus")), declared));
Assert.NotNull(StatFault(new PerformanceStat { Min = 3f, Max = 3f, Terms = new List<StatTerm> { Quality("bogus") } }, declared));
}
// A product with no maker would title as its design and take no maker profile for its roles.
[Fact]
public void EveryShippedProductHasAMaker()
{
using var cache = RestoredHullsTests.OpenCatalog();
var makerless = cache.GetAll<FactionProductData>().Where(p => cache.Get(p.Manufacturer) == null).Select(p => p.Name).OrderBy(n => n, StringComparer.Ordinal).ToArray();
Assert.True(makerless.Length == 0, "products with no maker: " + string.Join(", ", makerless));
}
// 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)
{
var stat = Stat(design, field);
Assert.Equal(cost ? 2f / 3f : 1.5f, stat.Max / stat.Min, 3);
Assert.Equal(new[] { role }, NamedQualityRoles(stat));
}
// Stats that already varied before the backfill keep their range; only their unnamed Quality term gains the role.
private static void AssertNamed(EquippableItemData design, string field, string role) =>
Assert.Equal(new[] { role }, NamedQualityRoles(Stat(design, field)));
[Fact]
public void RolesBackfillIsAuthored()
{
using var cache = RestoredHullsTests.OpenCatalog();
EquippableItemData Design(string name) => Assert.Single(cache.GetAll<EquippableItemData>(), i => i.Name == name);
string[] Roles(EquippableItemData d) => d.Roles.Select(r => r.Name).OrderBy(r => r, StringComparer.Ordinal).ToArray();
var autocannon = Design("Autocannon");
Assert.Equal(new[] { "barrel", "feed mechanism" }, Roles(autocannon));
AssertRange(autocannon, "Damage", false, "barrel");
AssertRange(autocannon, "Range", false, "barrel");
AssertRange(autocannon, "Penetration", false, "barrel");
var lrm = Design("LRMM72");
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");
Assert.Equal(new[] { "guidance system", "thruster", "warhead" }, Roles(srm));
AssertRange(srm, "Damage", false, "warhead");
AssertRange(srm, "Cooldown", true, "guidance system");
var mine = Design("Mine Launcher");
Assert.Equal(new[] { "dispenser", "warhead" }, Roles(mine));
AssertRange(mine, "Damage", false, "warhead");
AssertRange(mine, "Range", false, "dispenser");
AssertRange(mine, "Cooldown", true, "dispenser");
AssertRange(mine, "Spread", true, "dispenser");
var layer = Assert.Single(mine.Behaviors.OfType<MineLayerData>());
Assert.Equal(2f, layer.ArmingDelay);
Assert.Equal(2f, layer.FuseDelay);
Assert.Equal(30f, layer.Lifetime);
var drive = Design("Large Drive");
Assert.Equal(new[] { "injector", "nozzle" }, Roles(drive));
AssertRange(drive, "Thrust", false, "nozzle");
AssertRange(drive, "Visibility", true, "nozzle");
AssertRange(drive, "Heat", true, "injector");
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("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");
// 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)>
{
["Zhestokost"] = (.50f, .08f), ["R&D"] = (.60f, .15f), ["DME"] = (.55f, .20f), ["Lightsail"] = (.55f, .10f), ["Pirates"] = (.45f, .22f),
};
foreach (var design in new[] { autocannon, lrm, srm, mine, drive })
{
var sellers = cache.GetAll<FactionProductData>().Where(p => p.Design.Key.Equals(cache.RefOf(design).Key)).ToArray();
Assert.NotEmpty(sellers);
foreach (var product in sellers)
{
var maker = cache.Get(product.Manufacturer);
var (mean, dev) = profiles[maker.ShortName];
Assert.Equal(Roles(design), product.Roles.Select(r => r.Role).OrderBy(r => r, StringComparer.Ordinal).ToArray());
Assert.All(product.Roles, r =>
{
Assert.Equal(mean, r.Mean, 3);
Assert.Equal(dev, r.StandardDeviation, 3);
});
}
}
Assert.Contains(cache.GetAll<FactionProductData>(), p => p.Design.Key.Equals(cache.RefOf(autocannon).Key) && cache.Get(p.Manufacturer).ShortName == "Pirates");
}
}

View file

@ -12,7 +12,7 @@ using static CultMath.math;
// Should multiply that by actual performance." EquippedItem.ConditionRatio (Entity.cs) is the one number that
// answers "how healthy does this item actually look": the item's resolved value for a stat against what the
// same item, same lot, same modifiers would produce with Heat/Durability/PowerSupply pinned to their identity.
// Thruster.Condition and AetherDrive.Condition (Thruster.cs/AetherDrive.cs) are that ratio read against each
// Thruster.Condition (Thruster.cs) is that ratio read against each
// behaviour's own governing stat (Thrust, Torque); ShipInstance.cs (Unity-side, not covered here) multiplies
// presentation intent by it instead of recomputing any durability/heat/power arithmetic of its own.
// Each rule here has a matching mutation in tests/mutation_tests_condition_ratio_cut8.py.

View file

@ -0,0 +1,266 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CultMath;
using GameCult.Caching;
using Xunit;
// A consumable is a cargo item with a timed effect (aetheria-release CS-R1). Its modifiers exist in the resolver
// exactly while its effect is active: the host (Entity) initialises the effect's behaviours at activation and
// disposes them at expiry, and ItemManager.CreateInstance is the one way a lot becomes a ConsumableItem.
public sealed class ConsumableTests : IDisposable
{
private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-consumable-" + Guid.NewGuid().ToString("N"));
private string Catalog => Path.Combine(_root, "Aetheria.cc");
private static readonly int2 EngineCell = new int2(0, 0);
private static readonly int2 HoldCell = new int2(1, 1);
public ConsumableTests() => Directory.CreateDirectory(_root);
public void Dispose() => Directory.Delete(_root, true);
private sealed class Rig
{
public CultCache Cache;
public ItemManager Items;
public Ship Ship;
public EquippedItem Engine;
public PerformanceStat Thrust;
public ConsumableItemData Consumable;
public ConsumableItemData Other; // a second, unrelated non-stackable design
public Func<EquippableItem> NewEngine;
public CultRecordKey Key;
public CultRecordRef<Faction> Maker;
public ConsumableItem Mint(ConsumableItemData design = null) =>
Assert.IsType<ConsumableItem>(Items.CreateInstance(Items.CreateLot(design ?? Consumable, Maker, .5f)));
public EquippedCargoBay Hold => Ship.CargoBays.Single();
public int InCargo => Hold.Cargo.Keys.Count(i => i is ConsumableItem);
}
// A ship with a thruster (Thrust 10) and a hold; the consumable doubles ThrusterData.Thrust for one second.
private Rig Build(bool stackable = false)
{
var thrust = new PerformanceStat { Min = 10, Max = 10 };
var cache = AetheriaStores.Open(Catalog, catalogWritable: true);
cache.Upsert(new TestCatalogGlobal { Name = "Temperament" });
cache.Upsert(new Faction { Name = "Maker", ShortName = "MKR" });
var hullShape = new Shape(3, 3);
foreach (var cell in hullShape.AllCoordinates) hullShape[cell] = true;
var hullRef = cache.Upsert(new HullData
{
Name = "Skiff", HullType = HullType.Ship, Shape = hullShape, Durability = 10,
Hardpoints = { new HardpointData { Type = HardpointType.Sensors, Position = EngineCell, Shape = new Shape() } }
});
var engineRef = cache.Upsert(new GearData
{
Name = "Engine", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 10,
Behaviors = { new ThrusterData { Thrust = thrust } }
});
var interior = new Shape(2, 1); // room for two consumables
foreach (var cell in interior.AllCoordinates) interior[cell] = true;
var holdRef = cache.Upsert(new CargoBayData { Name = "Hold", Shape = new Shape(), InteriorShape = interior, Durability = 10 });
var consumableRef = cache.Upsert(new ConsumableItemData
{
Name = "Overdrive", Duration = 1f, Stackable = stackable, Shape = new Shape(),
Behaviors =
{
new StatModifierData
{
Stat = new StatReference { Target = nameof(ThrusterData), Stat = nameof(ThrusterData.Thrust) },
Modifier = new PerformanceStat { Min = 2, Max = 2 },
Type = StatModifierType.Multiplier
}
}
});
var otherRef = cache.Upsert(new ConsumableItemData { Name = "Flare", Duration = 1f, Shape = new Shape() });
cache.FlushAsync().Wait();
var items = new ItemManager(cache, new ProvenanceLedger(), RunSaveTests.TestSettings(), _ => { });
var makerRef = cache.RefOf(cache.GetByName<Faction>("Maker"));
EquippableItem Gear(EquippableItemData design) => (EquippableItem) items.CreateInstance(items.CreateLot(design, makerRef, .5f));
var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null);
var ship = new Ship(items, zone, Gear(cache.Get(hullRef)), new EntitySettings());
Assert.True(ship.TryEquip(Gear(cache.Get(engineRef)), EngineCell));
Assert.True(ship.TryEquip(Gear(cache.Get(holdRef)), HoldCell));
zone.Entities.Add(ship);
ship.Activate();
var data = cache.Get(consumableRef);
return new Rig
{
Cache = cache, Items = items, Ship = ship, Thrust = thrust, Consumable = data, Other = cache.Get(otherRef),
NewEngine = () => Gear(cache.Get(engineRef)),
Key = items.ItemData.RefOf<ItemData>(data).Key,
Engine = ship.Equipment.Single(e => e.Data.Name == "Engine"),
Maker = makerRef
};
}
// Two ticks after activation the modifier has attached (the first tick executes it, the second applies it).
private static void Tick(Rig rig, int times, float dt)
{
for (var i = 0; i < times; i++) rig.Ship.Update(dt);
}
// The rule: a consumable's modifiers exist in the resolver exactly while its effect is active, never after.
// Observed at the resolved stat and at the resolver's modifier entry count, not at a flag.
[Fact]
public void AConsumableModifierBoostsUntilExpiry()
{
var rig = Build();
using var _ = rig.Cache;
var resolver = rig.Ship.Resolver;
Assert.Equal(10f, rig.Engine.Evaluate(rig.Thrust), 3);
var baseline = resolver.ModifierEntryCount;
rig.Ship.ActivateConsumable(rig.Mint());
Tick(rig, 2, .3f); // 0.4s of the 1s remain; the modifier has attached
Assert.Equal(20f, rig.Engine.Evaluate(rig.Thrust), 3);
Assert.True(resolver.ModifierEntryCount > baseline);
Tick(rig, 3, .3f); // 1.5s elapsed in all: the effect ran out on the fourth tick
Assert.Equal(10f, rig.Engine.Evaluate(rig.Thrust), 3);
Assert.Equal(baseline, resolver.ModifierEntryCount);
}
// A lot minted through the one production path is a ConsumableItem, and a hold holding it activates it.
[Fact]
public void ABoughtConsumableActivates()
{
var rig = Build();
using var _ = rig.Cache;
Assert.True(rig.Hold.TryStore(rig.Mint()));
Assert.Equal(1, rig.InCargo);
Assert.True(rig.Ship.TryActivateConsumable(rig.Consumable));
Assert.Equal(0, rig.InCargo);
Assert.NotNull(rig.Ship.FindActiveConsumable(rig.Consumable));
}
// CS-R1: a non-stackable design allows one active effect at a time, so its Duration is its cooldown.
[Fact]
public void ANonStackableConsumableRefusesASecondActivation()
{
var rig = Build();
using var _ = rig.Cache;
Assert.True(rig.Hold.TryStore(rig.Mint()));
Assert.True(rig.Hold.TryStore(rig.Mint()));
Assert.True(rig.Ship.TryActivateConsumable(rig.Consumable));
Assert.False(rig.Ship.TryActivateConsumable(rig.Consumable));
Assert.Equal(1, rig.InCargo);
Tick(rig, 5, .3f); // the first effect has run out
Assert.True(rig.Ship.TryActivateConsumable(rig.Consumable));
Assert.Equal(0, rig.InCargo);
}
// The expiry boundary: Duration 1 with 0.3 s ticks leaves 0.1 s after the third tick (still active) and
// -0.2 s after the fourth (gone). An expiry one tick early or one tick late changes one of these two reads.
[Fact]
public void AConsumableLivesForItsDurationAndNoLonger()
{
var rig = Build();
using var _ = rig.Cache;
rig.Ship.ActivateConsumable(rig.Mint());
Tick(rig, 3, .3f);
Assert.Equal(20f, rig.Engine.Evaluate(rig.Thrust), 3);
Tick(rig, 1, .3f);
Assert.Equal(10f, rig.Engine.Evaluate(rig.Thrust), 3);
}
// An effect runs for exactly its Duration: Duration 1 with 0.25 s ticks (exact in floats) executes its
// behaviours on four ticks and is gone when the fourth ends, not on a fifth.
[Fact]
public void AConsumableRunsForExactlyItsDurationInTicks()
{
var rig = Build();
using var _ = rig.Cache;
rig.Ship.ActivateConsumable(rig.Mint());
Tick(rig, 3, .25f);
Assert.NotNull(rig.Ship.FindActiveConsumable(rig.Consumable));
Assert.Equal(20f, rig.Engine.Evaluate(rig.Thrust), 3);
Tick(rig, 1, .25f); // the fourth tick spends the last of the Duration
Assert.Null(rig.Ship.FindActiveConsumable(rig.Consumable));
Assert.Equal(10f, rig.Engine.Evaluate(rig.Thrust), 3);
}
// CS-R1, the stackable side: a stackable design activates again while its first effect runs, and every
// multiplier on the stat multiplies.
[Fact]
public void TwoStackableConsumablesOverlapAndMultiply()
{
var rig = Build(stackable: true);
using var _ = rig.Cache;
Assert.True(rig.Hold.TryStore(rig.Mint()));
Assert.True(rig.Hold.TryStore(rig.Mint()));
Assert.True(rig.Ship.TryActivateConsumable(rig.Consumable));
Assert.True(rig.Ship.TryActivateConsumable(rig.Consumable));
Assert.Equal(0, rig.InCargo);
Tick(rig, 2, .3f);
Assert.Equal(40f, rig.Engine.Evaluate(rig.Thrust), 3);
}
// Two modifiers share one resolver entry, both attached. The first expires while the second still runs: the
// second's boost stays, and when it expires too nothing is left behind.
[Fact]
public void AnExpiringConsumableLeavesAnOverlappingOnesBoost()
{
var rig = Build(stackable: true);
using var _ = rig.Cache;
var resolver = rig.Ship.Resolver;
var baseline = resolver.ModifierEntryCount;
Assert.True(rig.Hold.TryStore(rig.Mint()));
Assert.True(rig.Hold.TryStore(rig.Mint()));
Assert.True(rig.Ship.TryActivateConsumable(rig.Consumable));
Tick(rig, 1, .3f);
Assert.True(rig.Ship.TryActivateConsumable(rig.Consumable));
Tick(rig, 2, .3f); // both attached: the first has 0.1 s left, the second 0.4 s
Assert.Equal(40f, rig.Engine.Evaluate(rig.Thrust), 3);
Tick(rig, 1, .3f); // the first ran out; the second's boost is still on the shared entry
Assert.Equal(20f, rig.Engine.Evaluate(rig.Thrust), 3);
Assert.True(resolver.ModifierEntryCount > baseline);
Tick(rig, 1, .3f); // and now the second
Assert.Equal(10f, rig.Engine.Evaluate(rig.Thrust), 3);
Assert.Equal(baseline, resolver.ModifierEntryCount);
}
// CS-R1: the cooldown is per design. A running effect of one design does not refuse another design.
[Fact]
public void ADesignsCooldownDoesNotBlockAnotherDesign()
{
var rig = Build();
using var _ = rig.Cache;
Assert.True(rig.Hold.TryStore(rig.Mint()));
Assert.True(rig.Hold.TryStore(rig.Mint(rig.Other)));
Assert.True(rig.Ship.TryActivateConsumable(rig.Consumable));
Assert.True(rig.Ship.TryActivateConsumable(rig.Other));
Assert.Equal(0, rig.InCargo);
}
// Docking: an effect still running when the entity deactivates, is refitted and activates again boosts the
// items now fitted, as gear modifiers do, not the thruster that was swapped out.
[Fact]
public void AConsumableActiveAcrossARefitBoostsTheNewItems()
{
var rig = Build();
using var _ = rig.Cache;
rig.Ship.ActivateConsumable(rig.Mint());
Tick(rig, 2, .3f);
Assert.Equal(20f, rig.Engine.Evaluate(rig.Thrust), 3);
rig.Ship.Deactivate();
Assert.NotNull(rig.Ship.TryUnequip(rig.Engine));
Assert.True(rig.Ship.TryEquip(rig.NewEngine(), EngineCell));
rig.Ship.Activate();
Tick(rig, 2, .1f); // 0.2 s more: the effect still has 0.2 s of its second
var fitted = rig.Ship.Equipment.Single(e => e.Data.Name == "Engine");
Assert.NotSame(rig.Engine, fitted);
Assert.Equal(20f, fitted.Evaluate(rig.Thrust), 3);
}
}

View file

@ -9,30 +9,16 @@ using CultMath;
using Xunit;
// The demo scenario (aetheria-release, cut demo-galaxy): a prelude galaxy of a fixed cast whose antagonist's home is the
// boss zone and the exit. The shipped catalog holds no Pirates faction yet, so each test that needs one adds it to its
// scratch copy of the catalog.
// boss zone and the exit. The cast, the Pirates included, is in the shipped catalog.
public sealed partial class RunStartTests
{
private static readonly uint[] DemoSeeds = { 1, 2, 3, 4, 5 };
// The catalog record the demo's protagonist needs, until the shipped catalog has one. Zone names need a name file,
// and the entrance's station needs a faction whose allegiance reaches some manufacturer, so it reaches every one.
private void AddPirates()
{
var pirates = new Faction
{
Name = "Pirates", ShortName = "Pirates", GeonameFile = _cache.RefOf(_cache.GetAll<NameFile>().First())
};
foreach (var faction in _cache.GetAll<Faction>().ToArray()) pirates.Allegiance[_cache.RefOf(faction)] = 1;
_cache.Upsert(pirates);
}
private Galaxy DemoGalaxy(uint seed) => RunStart.Generate(new DemoTerminus(), Inputs(() => seed));
[Fact]
public void DemoTerminus_fixed_cast()
{
AddPirates();
foreach (var seed in DemoSeeds)
Assert.Equal(new[] { "Pirates", "Zhestokost", "Lucent Media", "Aeronautics Unlimited" },
DemoGalaxy(seed).Factions.Select(faction => faction.Name));
@ -41,7 +27,6 @@ public sealed partial class RunStartTests
[Fact]
public void DemoTerminus_gate_at_antagonist_home()
{
AddPirates();
foreach (var seed in DemoSeeds)
{
var galaxy = DemoGalaxy(seed);
@ -60,7 +45,6 @@ public sealed partial class RunStartTests
[Fact]
public void DemoTerminus_standing_survives_continue()
{
AddPirates();
var (galaxy, arena, staged, failures) = Launch(new DemoTerminus(), Inputs(() => 1));
Assert.True(failures.Count == 0, string.Join("; ", failures));
galaxy.Entrance.Contents = arena;
@ -83,11 +67,16 @@ public sealed partial class RunStartTests
restored.BossZones.Select(boss => (boss.Key.Name, Array.IndexOf(restored.Zones, boss.Value))));
}
// On the shipped catalog, which has no Pirates, the run does not start: the galaxy refuses, naming the cast field,
// and the scenario never reaches staging.
// A catalog without the Pirates (the shipped record and its products removed from this scratch copy) does not start the
// run: the galaxy refuses, naming the cast field, and the scenario never reaches staging.
[Fact]
public void DemoTerminus_missing_cast_refused()
{
var pirates = _cache.GetAll<Faction>().Single(faction => faction.Name == "Pirates");
var piratesRef = _cache.RefOf(pirates);
foreach (var product in _cache.GetAll<FactionProductData>().Where(product => product.Manufacturer.Equals(piratesRef)).ToArray())
Assert.True(_cache.Remove(_cache.RefOf(product).Key));
Assert.True(_cache.Remove(piratesRef.Key));
Assert.DoesNotContain(_cache.GetAll<Faction>(), faction => faction.Name.StartsWith("Pirates", StringComparison.Ordinal));
var refusal = Assert.Throws<InvalidOperationException>(() => DemoGalaxy(1));
Assert.Contains("Pirates", refusal.Message);
@ -108,7 +97,6 @@ public sealed partial class RunStartTests
[Fact]
public void DemoTerminus_player_flies_a_non_pirates_brand_hull_the_longinus()
{
AddPirates();
foreach (var seed in DemoSeeds)
{
var (galaxy, _, staged, failures) = Launch(new DemoTerminus(), Inputs(() => seed));
@ -130,7 +118,6 @@ public sealed partial class RunStartTests
[Fact]
public void DemoTerminus_player_carries_the_longinus_default_fit()
{
AddPirates();
string Fit(Entity ship) => string.Join(";", ship.Equipment
.Select(item => $"{item.Data.Name}@{item.Position}/{item.EquippableItem.Rotation}")
.OrderBy(entry => entry, StringComparer.Ordinal));
@ -151,7 +138,6 @@ public sealed partial class RunStartTests
[Fact]
public void DemoTerminus_region_is_sixty_four_zones_linked_at_half_density()
{
AddPirates();
string Links(Galaxy g) => string.Join(";", g.Zones.Select(zone =>
string.Join(",", zone.AdjacentZones.Select(adjacent => Array.IndexOf(g.Zones, adjacent)).OrderBy(index => index))));
Galaxy Reference(uint seed, float density)
@ -177,7 +163,6 @@ public sealed partial class RunStartTests
[Fact]
public void ACastNamingNoQuestFactionPlacesNoQuestZone()
{
AddPirates();
var galaxy = DemoGalaxy(1);
Assert.Equal(4, galaxy.HomeZones.Count);
Assert.Equal(4, galaxy.Factions.Length);
@ -235,7 +220,7 @@ public sealed partial class RunStartTests
" | zones " + g.Zones.Length +
" | owners " + string.Join(",", g.Zones.Select(z => z.Owner == null ? "-" : z.Owner.ShortName));
// Measured on 228f241e, before the demo cut, at seed 1.
// Measured at seed 1 under CultMath 0.3.0 (cultmath-unity-v0.3.0); the noise kernel changed there, which re-rolled the galaxy.
private const string TutorialSeed1 =
"Miss Terri’s Sugariffic Snack Company,Zhestokost,Lucent Media,Adrasteia,Aeronautics Unlimited,Finch Cybernetics | homes 47,10,17,49,35,1 | entrance 25 | zones 64 | owners Zhestokost,Finch,Lucent,Zhestokost,Finch,Adrasteia,Zhestokost,Adrasteia,Zhestokost,Zhestokost,Zhestokost,Zhestokost,Finch,Lucent,Adrasteia,Adrasteia,Zhestokost,Lucent,Finch,Finch,Lucent,Lucent,Finch,AU,Adrasteia,-,-,Adrasteia,Lucent,-,AU,Lucent,Zhestokost,Lucent,Lucent,AU,Adrasteia,AU,Lucent,AU,Finch,Finch,-,Lucent,Zhestokost,Zhestokost,Miss Terri's,Miss Terri's,Miss Terri's,Adrasteia,Finch,-,-,Miss Terri's,Lucent,AU,Miss Terri's,Zhestokost,Lucent,Lucent,Lucent,Finch,-,-";
"Miss Terri’s Sugariffic Snack Company,Zhestokost,Lucent Media,Adrasteia,Aeronautics Unlimited,Finch Cybernetics | homes 3,44,40,19,0,30 | entrance 12 | zones 64 | owners AU,AU,Finch,Miss Terri's,Lucent,Zhestokost,-,Lucent,AU,AU,Lucent,Adrasteia,-,Finch,Zhestokost,-,Adrasteia,-,AU,Adrasteia,AU,Zhestokost,Miss Terri's,-,AU,Finch,Miss Terri's,-,Zhestokost,-,Finch,-,-,AU,-,-,-,-,Miss Terri's,AU,Lucent,-,Finch,-,Zhestokost,AU,-,Zhestokost,Adrasteia,Adrasteia,AU,Miss Terri's,Finch,AU,Finch,-,Lucent,Zhestokost,-,AU,Miss Terri's,Zhestokost,-,Lucent";
}

View file

@ -283,7 +283,17 @@ public sealed partial class RunStartTests
[Fact]
public void TheEnvelopeComesFromTheGear()
{
var (_, longinus, _) = EvFleet();
// The Longinus is fitted by name, not generated: what the generator picks follows the item stream, and every role a
// product authors draws from it (roles-backfill), so a generated hull would stop carrying these drives.
Ship longinus = null;
var scenario = new Scripted(false, stage =>
{
stage.Player(stage.Bare("Djinni"), float2(-50000, -50000));
longinus = stage.Place(EvLonginus(stage), float2(-30000, -30000), facing: float2(0, 1)) as Ship;
});
var (_, _, _, failures) = Launch(scenario, Inputs(() => GalaxySeed));
Assert.True(failures.Count == 0, string.Join("; ", failures));
Assert.NotNull(longinus);
EvSettle(longinus);
// A thruster's Thrust property is refreshed only while it fires: turn each way so the flank thrusters hold what
// they push with, then read the envelope at rest.
@ -306,11 +316,18 @@ public sealed partial class RunStartTests
var envelope = longinus.Envelope;
var mass = longinus.Mass;
Assert.InRange(envelope.Forward, 500000f / mass * .99f, 500000f / mass * 1.01f);
// The shipped Large Drive's Thrust is a range its lot's roll moves it through, so each drive pushes within the catalog's
// range and the envelope forward is what the two push together.
var catalogThrust = _cache.GetAll<GearData>().Single(gear => gear.Name == "Large Drive").Behaviors.OfType<ThrusterData>().Single().Thrust;
Assert.All(largeDrives, t => Assert.InRange(t.Thrust, catalogThrust.Min * .99f, catalogThrust.Max * 1.01f));
var forward = largeDrives.Sum(t => t.Thrust) / mass;
Assert.InRange(envelope.Forward, forward * .99f, forward * 1.01f);
Assert.Equal(0f, envelope.Reverse);
var flankAcceleration = flanks.Max(t => t.Thrust) / mass;
Assert.InRange(envelope.Left, flankAcceleration * .99f, flankAcceleration * 1.01f);
Assert.InRange(envelope.Right, flankAcceleration * .99f, flankAcceleration * 1.01f);
// One Talaria 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);
Assert.InRange(sides[1], flankAccelerations[1] * .99f, flankAccelerations[1] * 1.01f);
var clockwise = thrusters.Where(t => t.Torque > settings.TorqueFloor).Sum(t => t.Torque * t.Thrust) * settings.TorqueMultiplier / mass;
var counterClockwise = thrusters.Where(t => t.Torque < -settings.TorqueFloor).Sum(t => -t.Torque * t.Thrust) * settings.TorqueMultiplier / mass;
Assert.InRange(envelope.Clockwise, clockwise * .99f, clockwise * 1.01f);
@ -485,7 +502,7 @@ public sealed partial class RunStartTests
}
// Two shooters on opposite sides of the same target, 200 m away: one with a projectile gun and one with a laser
// (a beam's authored velocity is 0, a flight time of zero). The target is the generated Djinni, the catalog's one ship that strafes.
// (a beam's authored velocity is 0, a flight time of zero). The target is the fitted Djinni, the catalog's one ship that strafes.
private sealed class EvRange
{
public Zone Arena;
@ -493,6 +510,18 @@ 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
// 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));
private EvRange EvRangeLaunch()
{
Ship gunner = null, lasing = null, target = null;
@ -500,7 +529,7 @@ public sealed partial class RunStartTests
{
stage.Player(stage.Bare("Djinni"), float2(-50000, -50000));
gunner = stage.Place(EvLonginus(stage, "FastBlast+-", "ColdFire"), float2(0, 0), facing: float2(0, 1)) as Ship;
target = stage.Place(stage.Generated("Djinni"), float2(0, 200), 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;
});
var (_, arena, _, failures) = Launch(scenario, Inputs(() => GalaxySeed));
@ -555,6 +584,10 @@ public sealed partial class RunStartTests
return (hits, price);
}
// The two volleys' hit counts are rolls, so their gap is the price gap plus noise. At the price gap this fixture
// has (about .06 on .44) 200 shots flip the comparison one seed in eight; this many keeps it near four standard deviations.
private const int EvVolleySize = 2000;
// The evasion term is in the live price, the HUD's forecast and the roll: a ship crossing at 150 m/s that has been
// jinking is harder to hit than the same ship coasting, for a projectile gun.
[Fact]
@ -568,7 +601,7 @@ public sealed partial class RunStartTests
EvCross(range, jinking: false);
var coastingDiagnostic = FireControl.Inspect(gun, shooter, target);
var coastingPrice = FireControl.HitProbability(gun, shooter, target);
var coasting = EvVolley(range, gun, shooter, 200);
var coasting = EvVolley(range, gun, shooter, EvVolleySize);
Assert.Equal(0f, coastingDiagnostic.Evasion);
Assert.Equal(1f, coastingDiagnostic.PEvasion);
Assert.True(coastingPrice > .2f, $"fixture: a coasting target is hittable ({coastingPrice})");
@ -576,10 +609,10 @@ public sealed partial class RunStartTests
EvCross(range, jinking: true);
var jinkingDiagnostic = FireControl.Inspect(gun, shooter, target);
var jinkingPrice = FireControl.HitProbability(gun, shooter, target);
var jinking = EvVolley(range, gun, shooter, 200);
Console.WriteLine($"EVASION price: coasting {coastingPrice:F3} hits {coasting.hits}/200 committed {coasting.price:F3}; " +
var jinking = EvVolley(range, gun, shooter, EvVolleySize);
Console.WriteLine($"EVASION price: coasting {coastingPrice:F3} hits {coasting.hits}/{EvVolleySize} committed {coasting.price:F3}; " +
$"jinking {jinkingPrice:F3} (evasion {jinkingDiagnostic.Evasion:F2} m, tracking {jinkingDiagnostic.Tracking:F1}, PEvasion {jinkingDiagnostic.PEvasion:F3}) " +
$"hits {jinking.hits}/200 committed {jinking.price:F3}");
$"hits {jinking.hits}/{EvVolleySize} committed {jinking.price:F3}");
Assert.True(jinkingDiagnostic.Evasion > 0f);
Assert.True(jinkingDiagnostic.PEvasion < 1f);

View file

@ -313,6 +313,147 @@ public sealed partial class RunStartTests
}
}
private WeaponItemData PdDesign(string name) => _cache.GetAll<WeaponItemData>().Single(w => w.Name == name);
// Data check, not a behaviour test: cut pd-gear's authored catalog (ruling catalog-grows-generic-designs-branded-products):
// three generic designs, each with several products, no maker twice on one design, and no brand on a design.
[Fact]
public void PdGearIsAuthored()
{
var expected = new (string design, HardpointType hardpoint, int width, int height, float tracking)[]
{
("Point Defense Gun", HardpointType.Ballistic, 1, 1, 40f),
("Point Defense Laser", HardpointType.Energy, 1, 1, 40f),
("Flak Gun", HardpointType.Ballistic, 1, 2, 20f),
};
var products = _cache.GetAll<FactionProductData>().ToArray();
foreach (var (name, hardpoint, width, height, tracking) in expected)
{
var design = PdDesign(name);
Assert.Equal(hardpoint, design.HardpointType);
Assert.Equal(width, design.Shape.Width);
Assert.Equal(height, design.Shape.Height);
Assert.True(design.Shape.Cells.Cast<bool>().All(cell => cell), $"{name} occupies every cell of its shape");
var rate = design.Behaviors.OfType<WeaponData>().Single().Tracking;
Assert.Equal(tracking, rate.Min);
Assert.Equal(tracking, rate.Max);
var key = _cache.RefOf(design).Key;
var sold = products.Where(p => p.Design.Key.Equals(key)).ToArray();
Assert.True(sold.Length >= 3, $"{name} has at least three products, not {sold.Length}");
var makers = sold.Select(p => _cache.Get(p.Manufacturer)).ToArray();
Assert.DoesNotContain(null, makers);
Assert.Equal(makers.Length, makers.Select(m => m.ShortName).Distinct().Count());
Assert.DoesNotContain(makers, m => m.ShortName == "Miss Terri's");
Assert.All(sold, p => Assert.NotEqual(design.Name, p.Name));
Assert.All(sold, p => Assert.Equal(design.Roles.Select(r => r.Name).OrderBy(n => n), p.Roles.Select(r => r.Role).OrderBy(n => n)));
}
}
private static void PdStat(string design, string stat, PerformanceStat actual, float min, float max) =>
Assert.True(actual.Min == min && actual.Max == max, $"{design} {stat} is {min}-{max}, not {actual.Min}-{actual.Max}");
// Data check: the authored numbers of the three designs, read from the shipped catalog through the production load path
// (addenda "Catalog growth: generic designs, branded products", the Derivation of the PD stats). Each is a lever the
// operator tunes, so each is pinned; the ammunition is the commodity Autocannon's rounds are.
[Fact]
public void PdGearStatsAreAuthored()
{
var ammunition = PdDesign("Autocannon").Behaviors.OfType<InstantWeaponData>().Single().AmmoType.Key;
var expected = new (string name, float mass, int price, float durability, WeaponModifiers modifiers, (float min, float max) damage,
(float min, float max) count, (float min, float max) range, (float min, float max) cooldown, (float min, float max) spread,
(float min, float max) velocity, (float min, float max) energy, (float min, float max) heat, (float min, float max) visibility,
bool ammo, int magazine, float reload)[]
{
("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),
("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),
};
foreach (var e in expected)
{
var design = PdDesign(e.name);
var data = design.Behaviors.OfType<InstantWeaponData>().Single();
Assert.Equal(e.mass, design.Mass);
Assert.Equal(e.price, design.Price);
Assert.Equal(e.durability, design.Durability);
Assert.Equal(e.modifiers, design.WeaponModifiers);
PdStat(e.name, "damage", data.Damage, e.damage.min, e.damage.max);
PdStat(e.name, "count", data.Count, e.count.min, e.count.max);
PdStat(e.name, "range", data.Range, e.range.min, e.range.max);
PdStat(e.name, "min range", data.MinRange, 0f, 0f);
PdStat(e.name, "cooldown", data.Cooldown, e.cooldown.min, e.cooldown.max);
PdStat(e.name, "spread", data.Spread, e.spread.min, e.spread.max);
PdStat(e.name, "velocity", data.Velocity, e.velocity.min, e.velocity.max);
PdStat(e.name, "energy", data.Energy, e.energy.min, e.energy.max);
PdStat(e.name, "heat", data.Heat, e.heat.min, e.heat.max);
PdStat(e.name, "visibility", data.Visibility, e.visibility.min, e.visibility.max);
Assert.Equal(e.magazine, data.MagazineSize);
Assert.Equal(e.reload, data.ReloadTime);
if (e.ammo) Assert.True(data.AmmoType.Key.Equals(ammunition), $"{e.name} draws the ammunition commodity");
else Assert.False(data.AmmoType.IsSet(), $"{e.name} draws no ammunition");
}
Assert.Equal("Close-in defence gun: a hose of light rounds.", PdDesign("Point Defense Gun").Description);
Assert.Equal("Close-in defence beam: quick, light, instant.", PdDesign("Point Defense Laser").Description);
Assert.Equal("Small flak gun: a short-range pellet volley.", PdDesign("Flak Gun").Description);
}
// Rule test (ruling catalog-grows-generic-designs-branded-products): branding lives in the products, so no PD design's
// name or description carries any maker's name or short name. The makers are enumerated from the catalog.
[Fact]
public void PdDesignsCarryNoMakerName()
{
var makers = _cache.GetAll<Faction>().SelectMany(f => new[] { f.Name, f.ShortName }).Where(n => !string.IsNullOrWhiteSpace(n)).Distinct().ToArray();
Assert.True(makers.Length > 10, $"fixture: the catalog lists its makers ({makers.Length})");
foreach (var name in new[] { "Point Defense Gun", "Point Defense Laser", "Flak Gun" })
{
var design = PdDesign(name);
foreach (var maker in makers)
{
var word = new System.Text.RegularExpressions.Regex($@"(?<!\w){System.Text.RegularExpressions.Regex.Escape(maker)}(?!\w)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
Assert.False(word.IsMatch(design.Name ?? ""), $"{name}'s name carries the maker {maker}");
Assert.False(word.IsMatch(design.Description ?? ""), $"{name}'s description carries the maker {maker}");
}
}
}
// Data check: a design is offered only if some hull has a hardpoint that takes it (LoadoutGenerator.HasHome), so these
// guns are stocked and fitted only while a catalog hull takes them (body fact CG6).
[Fact]
public void PdGunsHaveHomes()
{
var djinni = _cache.GetAll<HullData>().Single(h => h.Name == "Djinni");
var longinus = _cache.GetAll<HullData>().Single(h => h.Name == "Longinus");
foreach (var name in new[] { "Point Defense Gun", "Flak Gun" })
Assert.Contains(djinni.Hardpoints, hardpoint => hardpoint.Type == HardpointType.Ballistic && hardpoint.Takes(PdDesign(name)));
Assert.Contains(longinus.Hardpoints, hardpoint => hardpoint.Type == HardpointType.Energy && hardpoint.Takes(PdDesign("Point Defense Laser")));
}
// Ruling weapon-tracking-authored, in play: a PD gun follows a speed demon crossing close in, and the machine gun does not.
[Fact]
public void PdGunHoldsASpeedDemon()
{
var range = EvMountRange(40f, 3f);
EvCross(range, jinking: false, float2(150, 0));
var shooter = range.Gunner;
var omega = FireControl.AngularVelocity(shooter, range.Target);
Assert.InRange(omega, degrees(150f / 200f) * .999f, degrees(150f / 200f) * 1.001f);
var gear = FireControl.Tracking(shooter) / _items.GameplaySettings.UnaidedTracking;
Assert.True(gear > 1.2f, $"fixture: the shooter's targeting gear tracks better than unaided ({gear})");
// The rate the production path reads: the catalog design's authored Tracking on the weapon, times the shooter's gear.
float RateOf(string design)
{
EvSetRate(range.Gun, range.Gunner, PdDesign(design).Behaviors.OfType<WeaponData>().Single().Tracking.Max);
return FireControl.TrackingRate(range.Gun, range.Gunner);
}
var pd = FireControl.PMount(omega, RateOf("Point Defense Gun"));
var clearPath = FireControl.PMount(omega, RateOf("ClearPath"));
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.
[Fact]
public void PlightHasItsRuledShape()

View file

@ -469,10 +469,9 @@ public sealed partial class FireControlCut124Tests : IDisposable
}
// The same rule on the shipped hulls: a blast just grazing the corner farthest from the centre of mass. The
// corners of the shipped Longinus and LonginusX reach past the old cull's box-half-diagonal bound.
// corner of the shipped Longinus reaches past the old cull's box-half-diagonal bound.
[Theory]
[InlineData("Longinus")]
[InlineData("LonginusX")]
public void AGrazingBlastAtAShippedHullsFarthestCornerLands(string hullName)
{
Shape shape;

View file

@ -1324,7 +1324,7 @@ public sealed class FireControlCut12Tests : IDisposable
}
// S3 fix batch (Hands, 2026-09-25): Lane's own comment ("never allocates on its own") and Silhouette's
// pooled path are pinned directly, instead of trusting the comment. Measured (Release, LonginusX-shaped
// pooled path are pinned directly, instead of trusting the comment. Measured (Release, Longinus-shaped
// fixture unavailable to this test file -- a 7x9 solid hull is used instead): Lane and Silhouette (given a
// caller-supplied buffer) allocate exactly 0 bytes over 1000 calls, confirming the S3 change itself
// (Array.Sort(T[], int, int) resolving Interval/LaneCell's own IComparable<T> at JIT time, not the

View file

@ -231,9 +231,9 @@ public sealed class FireControlCut6cTests : IDisposable
var cache = AetheriaStores.Open(Catalog, Run(), Player());
_openCaches.Add(cache);
// A minimal one-zone galaxy whose faction roster excludes Targeting Maker entirely, the same
// SavedGame/Galaxy round trip RunSaveTests uses to build a real Galaxy without standing up full
// procedural generation.
// A minimal one-zone galaxy the same SavedGame/Galaxy round trip RunSaveTests uses builds, without standing
// up full procedural generation. Its generator's faction is Maker, whose allegiance does not name
// Targeting Maker, so IsAvailable rejects Targeting Maker's products by allegiance.
var game = new SavedGame
{
Factions = new[] { maker },
@ -250,13 +250,14 @@ public sealed class FireControlCut6cTests : IDisposable
};
RunSave.Commit(cache, game, zones, new ProvenanceLedger());
var galaxy = new Galaxy(cache, cache.GetGlobal<SavedGame>(), _ => { });
Assert.False(galaxy.ContainsFaction(targetingMaker));
var makerFaction = cache.Get(maker);
Assert.False(makerFaction.Allegiance.ContainsKey(targetingMaker));
var random = new Random(1u);
var settings = TestSettings();
var log = new List<string>();
var items = new ItemManager(cache, new ProvenanceLedger(), settings, log.Add);
var generator = new LoadoutGenerator(ref random, items, galaxy, null, null, .5f);
var generator = new LoadoutGenerator(ref random, items, galaxy, null, makerFaction, .5f);
var pack = generator.GenerateShipLoadout(candidate => candidate.Name == "Armed");

View file

@ -212,7 +212,7 @@ public sealed class FireControlCut7Tests : IDisposable
Assert.NotEmpty(equippable);
Assert.Contains(equippable, e => e is WeaponItemData);
var hull = cache.GetByName<HullData>("LonginusX");
var hull = cache.GetByName<HullData>("Longinus");
Assert.NotNull(hull);
var settings = new GameplaySettings

View file

@ -374,7 +374,7 @@ public sealed class FireControlCut9Tests : IDisposable
// Even extents: CenterOfMass is the raw mean of integer cell coordinates (ItemData.cs), with no
// +0.5 cell-centre offset -- an odd extent's mean lands exactly on an occupied cell (no cliff to
// reproduce), while an even one lands on the half-cell boundary between two cells, the same
// off-integer shape every shipped hull's real (irregular) footprint produces (LonginusX 2.5/6.697,
// off-integer shape every shipped hull's real (irregular) footprint produces (Longinus 2.5/6.697,
// Zenith 5.5/5.5, Turret 3.5/3.5).
var hullShape = SolidShape(6, 12);

View file

@ -6,13 +6,15 @@ using GameCult.Caching;
using Xunit;
// Items are titled by their product (ruling catalog-grows-generic-designs-branded-products): ItemManager.Title reads
// Brand, so the lot's maker picks which of a design's products names the unit, and nothing else carries a name.
// Brand, so the lot's own product names the unit (a maker may sell several products of one design), and nothing
// else carries a name.
public sealed class ItemTitleTests : IDisposable
{
private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-itemtitle-" + Guid.NewGuid().ToString("N"));
private readonly CultCache _cache;
private readonly ItemManager _items;
private readonly FactionProductData _panopticon, _clapBack, _spiceBlend;
private readonly FactionProductData _panopticon, _zulu, _clapBack, _spiceBlend;
private readonly CultRecordRef<Faction> _finch;
private readonly CultRecordRef<Faction> _stranger;
private readonly CompoundCommodityData _spice;
private readonly GearData _array;
@ -25,13 +27,16 @@ public sealed class ItemTitleTests : IDisposable
_array = new GearData { Name = "Array", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Price = 10, Durability = 5 };
_cache.Upsert(_array);
_cache.Upsert(new SimpleCommodityData { Name = "Ore", Shape = new Shape(), Price = 7, MaxStack = 100 });
var finch = _cache.Upsert(new Faction { Name = "Finch", ShortName = "FIN" });
var finch = _finch = _cache.Upsert(new Faction { Name = "Finch", ShortName = "FIN" });
var lucent = _cache.Upsert(new Faction { Name = "Lucent", ShortName = "LUC" });
_stranger = _cache.Upsert(new Faction { Name = "Stranger", ShortName = "STR" });
_spice = new CompoundCommodityData { Name = "Spice", Shape = new Shape(), Price = 3 };
_cache.Upsert(_spice);
var design = _cache.RefOf<CraftedItemData>(_cache.GetByName<GearData>("Array"));
_panopticon = new FactionProductData { Name = "Panopticon Prime", Design = design, Manufacturer = finch };
// Finch's second Array product, keyed to sort after the first: a key-order lookup would hand its units the first.
_zulu = new FactionProductData { Name = "Zulu Prime", Design = design, Manufacturer = finch };
_cache.Commit(batch => batch.Upsert(typeof(FactionProductData), _zulu, new CultRecordKey("array-finch-zulu")));
_clapBack = new FactionProductData { Name = "ClapBack Ultra", Design = design, Manufacturer = lucent };
_cache.Commit(batch => batch.Upsert(typeof(FactionProductData), _panopticon, new CultRecordKey("array-finch")));
_cache.Commit(batch => batch.Upsert(typeof(FactionProductData), _clapBack, new CultRecordKey("array-lucent")));
@ -64,6 +69,41 @@ public sealed class ItemTitleTests : IDisposable
Assert.Equal("ClapBack Ultra", _items.Title(lucent));
}
[Fact]
public void A_makers_second_product_titles_and_brands_as_itself()
{
var zulu = (CraftedItemInstance) _items.CreateInstance(_items.CreateLot(_zulu));
Assert.Equal("Zulu Prime", _items.Title(zulu));
var (maker, product) = _items.Brand(zulu);
Assert.Equal("Finch", maker.Name);
Assert.Equal("Zulu Prime", product.Name);
var panopticon = _items.CreateInstance(_items.CreateLot(_panopticon));
Assert.Equal("Panopticon Prime", _items.Title(panopticon));
}
[Fact]
public void A_lot_without_a_product_brands_its_maker_only()
{
var unit = (CraftedItemInstance) _items.CreateInstance(_items.CreateLot(_array, _finch, .5f));
var (maker, product) = _items.Brand(unit);
Assert.Equal("Finch", maker.Name);
Assert.Null(product);
Assert.Equal("Array", _items.Title(unit));
}
[Fact]
public void A_lot_whose_product_left_the_catalog_brands_its_maker_only()
{
var lot = _items.CreateLot(_panopticon);
_items.Lots[lot].Product = new CultRecordRef<FactionProductData>(new CultRecordKey("removed-product"));
var unit = (CraftedItemInstance) _items.CreateInstance(lot);
var (maker, product) = _items.Brand(unit);
Assert.Equal("Finch", maker.Name);
Assert.Null(product);
Assert.Equal("Array", _items.Title(unit));
}
[Fact]
public void Unbranded_units_are_titled_by_design()
{

View file

@ -313,8 +313,8 @@ public sealed class LoadoutTests : IDisposable
}
// Two new makers, each with one Lamp product, upserted into the live cache so its enumeration order (z before a)
// disagrees with record-key order; a reopened snapshot could already hand them back sorted. Brand() requires at
// most one product per (maker, design), so each gets its own maker rather than sharing "Maker".
// disagrees with record-key order; a reopened snapshot could already hand them back sorted. Each gets its own
// maker rather than sharing "Maker".
[Fact]
public void FirstAvailableProductInKeyOrderBuildsTheSlot()
{
@ -372,30 +372,6 @@ public sealed class LoadoutTests : IDisposable
Assert.Equal("slot 0,0: no available product of Lamp", Assert.Single(failures));
}
// Census's duplicate (maker, design) detector exists precisely because this should never happen in an
// authored catalog; Brand()'s tie-break is what a runtime item falls back on if it ever does, so it must stay
// deterministic rather than however the cache happens to enumerate.
[Fact]
public void BrandPicksFirstProductInKeyOrderForSameMakerAndDesign()
{
using var cache = AetheriaStores.Open(Catalog, catalogWritable: true);
var maker = cache.Upsert(new Faction { Name = "TieBreaker", ShortName = "TIE" });
var lamp = new CultRecordRef<CraftedItemData>(cache.RefOf(cache.GetByName<GearData>("Lamp")).Key);
cache.Commit(batch => batch.Upsert(typeof(FactionProductData), new FactionProductData { Name = "lamp-b", Design = lamp, Manufacturer = maker }, new CultRecordKey("lamp-b")));
cache.Commit(batch => batch.Upsert(typeof(FactionProductData), new FactionProductData { Name = "lamp-a", Design = lamp, Manufacturer = maker }, new CultRecordKey("lamp-a")));
var items = new ItemManager(cache, new ProvenanceLedger(), RunSaveTests.TestSettings(), _ => { });
var lotId = items.Lots.Add(new Lot
{
Design = cache.RefOf<ItemData>(cache.GetByName<GearData>("Lamp")),
Origin = new Produced { Faction = maker, Station = 1, Facility = 2, Inputs = Array.Empty<int>() },
Quality = .5f, Roles = new List<RoleFill>()
});
var instance = (EquippableItem) items.CreateInstance(lotId);
var (_, product) = items.Brand(instance);
Assert.Equal("lamp-a", product.Name);
}
// F2: this test must not enumerate reloaded instances through EntitySerializer.Items, the GC root walk under
// test. It hand-mints one real lot per EntityPack root (Hull, Equipment, CargoBays, DockingBays, CargoContents,
// Children, DockingBayContents) so the expected lot ids are known independently of any enumerator, and reads
@ -784,11 +760,7 @@ public sealed class LoadoutTests : IDisposable
var items = new ItemManager(cache, new ProvenanceLedger(), RunSaveTests.TestSettings(), _ => { });
var hullItem = (EquippableItem) items.CreateInstance(items.CreateLot(hullData, maker, .5f));
var ship = new Ship(items, null, hullItem, new EntitySettings());
// ItemManager.CreateInstance has no ConsumableItemData branch (it only special-cases EquippableItemData,
// falling back to CompoundCommodity otherwise); build the instance directly, as that method does for
// EquippableItem.
var consumableLot = items.CreateLot(consumableData, maker, .5f);
var consumableItem = new ConsumableItem { Data = cache.RefOf<ItemData>(consumableData), Lot = consumableLot };
var consumableItem = (ConsumableItem) items.CreateInstance(items.CreateLot(consumableData, maker, .5f));
var effect = new ConsumableItemEffect(consumableItem, ship);
effect.Update(5f); // half the duration elapsed -> progress .5 -> effectiveness .5 on a linear ramp

View file

@ -0,0 +1,155 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
using Xunit;
// AetherDb's pirates-faction command (aetheria-release, cut pirates-record), run on a scratch copy of the shipped catalog
// with the Pirates removed from it.
public sealed class PiratesFactionCommandTests : IDisposable
{
private readonly string _root = Path.Combine(Path.GetTempPath(), "pirates-command-" + Guid.NewGuid().ToString("N"));
private string CatalogPath => Path.Combine(_root, "GameData", "Aetheria.cc");
public PiratesFactionCommandTests()
{
Directory.CreateDirectory(Path.Combine(_root, "GameData"));
File.Copy(Path.Combine(AetherDb.FindRoot(), "GameData", "Aetheria.cc"), CatalogPath);
// AetherDb.Open composes the process-wide registry, which in this test host also sees this assembly's TestCatalogGlobal
// (see FireControlCut7Tests). So the copy is stripped through a registry scoped to the shipped assembly and then given
// the record that registry's shared sibling demands, as AetheriaStoresTests does.
var registry = CultDocumentRegistry.ForTypes(typeof(ItemData).Assembly.GetTypes()
.Where(t => t is { IsAbstract: false, IsInterface: false })
.Where(t => t.GetCustomAttribute<CultDocumentAttribute>() != null));
using (var cache = new CultCache(registry))
{
cache.AddBackingStore(new SingleFileMessagePackBackingStore(CatalogPath), AetheriaStores.CatalogTypes);
var pirates = cache.GetAll<Faction>().Single(faction => faction.Name == "Pirates");
var ours = cache.RefOf(pirates);
foreach (var product in cache.GetAll<FactionProductData>().Where(product => product.Manufacturer.Equals(ours)).ToArray())
Assert.True(cache.Remove(cache.RefOf(product).Key));
Assert.True(cache.Remove(ours.Key));
cache.FlushAsync().Wait();
}
using (var cache = new CultCache())
{
cache.AddBackingStore(new SingleFileMessagePackBackingStore(CatalogPath), AetheriaStores.CatalogTypes);
cache.Upsert(new TestCatalogGlobal { Name = "Temperament" });
cache.FlushAsync().Wait();
}
}
public void Dispose() => Directory.Delete(_root, true);
private (Faction[] Pirates, FactionProductData[] Products) Read()
{
var db = AetherDb.Open(root: _root);
try
{
var pirates = db.Cache.GetAll<Faction>().Where(faction => faction.Name == "Pirates").ToArray();
var products = pirates.Length == 0 ? new FactionProductData[0]
: db.Cache.GetAll<FactionProductData>().Where(product => product.Manufacturer.Equals(db.Cache.RefOf(pirates[0]))).ToArray();
return (pirates, products);
}
finally { db.Cache.Dispose(); }
}
[Fact]
public void A_dry_run_writes_nothing_and_apply_lands_the_record_once()
{
var before = File.ReadAllBytes(CatalogPath);
Assert.Equal(0, Program.PiratesFaction(apply: false, root: _root));
Assert.Equal(before, File.ReadAllBytes(CatalogPath));
Assert.Empty(Read().Pirates);
Assert.Equal(0, Program.PiratesFaction(apply: true, root: _root));
var landed = File.ReadAllBytes(CatalogPath);
var (pirates, products) = Read();
var faction = Assert.Single(pirates);
Assert.Equal("Pirates", faction.ShortName);
Assert.StartsWith("A loose coalition of crews and hidden docks", faction.Description);
Assert.Equal(3, faction.InfluenceDistance);
Assert.Equal(new CultMath.float3(.42f, .40f, .37f), faction.PrimaryColor);
Assert.Equal(new CultMath.float3(1f, .45f, .05f), faction.SecondaryColor);
Assert.Equal(12, faction.Allegiance.Count);
Assert.All(faction.Allegiance.Values, value => Assert.Equal(1f, value));
var db = AetherDb.Open(root: _root);
try
{
Assert.Equal("pleiades", db.Cache.Get(faction.GeonameFile).Name);
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."),
("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."),
};
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)
{
var product = products.Single(p => p.Name == name);
var design = (CraftedItemData) db.Cache.Get(product.Design);
Assert.Equal(designName, design.Name);
Assert.Equal(description, product.Description);
Assert.Equal((design.Roles ?? new List<ItemRole>()).Select(role => role.Name), (product.Roles ?? new List<ProductRole>()).Select(role => role.Role));
Assert.All(product.Roles, role => { Assert.Equal(.45f, role.Mean); Assert.Equal(.22f, role.StandardDeviation); });
}
}
finally { db.Cache.Dispose(); }
// A second apply finds the faction and changes nothing.
Assert.Equal(0, Program.PiratesFaction(apply: true, root: _root));
Assert.Equal(landed, File.ReadAllBytes(CatalogPath));
}
[Fact]
public void An_existing_Pirates_faction_is_left_as_it_is()
{
var db = AetherDb.Open(catalogWritable: true, root: _root);
db.Cache.Commit(batch => batch.Upsert(typeof(Faction), new Faction { Name = "Pirates", ShortName = "Mine", Description = "authored by hand" }));
db.Cache.Dispose();
Assert.Equal(0, Program.PiratesFaction(apply: true, root: _root));
var (pirates, products) = Read();
Assert.Equal("authored by hand", Assert.Single(pirates).Description);
Assert.Empty(products);
}
[Fact]
public void A_missing_design_refuses_and_lands_nothing()
{
var db = AetherDb.Open(catalogWritable: true, root: _root);
var autocannon = db.Cache.GetAll<WeaponItemData>().Single(weapon => weapon.Name == "Autocannon");
autocannon.Name = "Autocannon (renamed)";
db.Cache.Commit(batch => batch.Upsert(typeof(WeaponItemData), autocannon, db.Cache.RefOf(autocannon).Key));
db.Cache.Dispose();
Assert.Throws<InvalidOperationException>(() => Program.PiratesFaction(apply: true, root: _root));
Assert.Empty(Read().Pirates);
}
[Fact]
public void A_missing_name_file_refuses_and_lands_nothing()
{
var db = AetherDb.Open(catalogWritable: true, root: _root);
var pleiades = db.Cache.GetAll<NameFile>().Single(file => file.Name == "pleiades");
Assert.True(db.Cache.Remove(db.Cache.RefOf(pleiades).Key));
db.Cache.FlushAsync().Wait();
db.Cache.Dispose();
Assert.Throws<InvalidOperationException>(() => Program.PiratesFaction(apply: true, root: _root));
Assert.Empty(Read().Pirates);
}
}

View file

@ -0,0 +1,83 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Linq;
using Xunit;
// The Pirates record (aetheria-release, cut pirates-record): the shipped catalog's faction of rebrands, named in emoji.
public sealed partial class RunStartTests
{
private Faction ShippedPirates() => _cache.GetAll<Faction>().Single(faction => faction.Name == "Pirates");
private FactionProductData[] PiratesProducts()
{
var pirates = _cache.RefOf(ShippedPirates());
return _cache.GetAll<FactionProductData>().Where(product => product.Manufacturer.Equals(pirates)).ToArray();
}
// The demo's allied faction exists as catalog data with eight generatable rebrands of other makers' designs.
[Fact]
public void PiratesAreInTheShippedCatalog()
{
var pirates = ShippedPirates();
var others = _cache.GetAll<Faction>().Where(faction => faction != pirates).Select(faction => _cache.RefOf(faction)).ToArray();
Assert.NotEmpty(others);
Assert.All(others, other => Assert.True(pirates.Allegiance.ContainsKey(other)));
Assert.NotNull(_cache.Get(pirates.GeonameFile));
var products = PiratesProducts();
Assert.Equal(8, products.Length);
var hulls = _cache.GetAll<HullData>().ToArray();
foreach (var product in products)
{
var design = _cache.Get(product.Design) as EquippableItemData;
Assert.NotNull(design);
Assert.True(LoadoutGenerator.HasHome(design, hulls), $"{design.Name} has no home");
Assert.True(design.Price > 0, $"{design.Name} has no price");
Assert.Contains(_cache.GetAll<FactionProductData>(), other =>
other.Design.Key.Equals(product.Design.Key) && !other.Manufacturer.Equals(product.Manufacturer));
}
}
// The Pirates' products are named in emoji and nothing else: no ASCII letter or digit survives in a name.
[Fact]
public void PiratesProductsAreNamedInEmoji()
{
foreach (var product in PiratesProducts())
{
Assert.False(string.IsNullOrEmpty(product.Name));
Assert.DoesNotContain(product.Name, character => character < 128 && char.IsLetterOrDigit(character));
Assert.Contains(product.Name.EnumerateRunes(), rune => rune.Value >= 0x1F000);
}
}
// Brand finds a lot's product by (maker, design), so a maker may sell one product per design.
[Fact]
public void NoMakerSellsTwoProductsOfOneDesign()
{
var twice = _cache.GetAll<FactionProductData>()
.GroupBy(product => (Maker: product.Manufacturer.Key.Value, Design: product.Design.Key.Value))
.Where(group => group.Count() > 1)
.Select(group => string.Join(", ", group.Select(product => product.Name)))
.ToArray();
Assert.Empty(twice);
}
// A unit minted from a Pirates rebrand titles and brands as that rebrand: the lot records its product, so the
// emoji name shows although the same design is also sold by its original maker.
[Fact]
public void PiratesRebrandUnitsTitleAsTheirOwnProduct()
{
var pirates = ShippedPirates();
foreach (var product in PiratesProducts())
{
var unit = _items.CreateInstance(_items.CreateLot(product));
Assert.Equal(product.Name, _items.Title(unit));
var brand = _items.Brand((CraftedItemInstance) unit);
Assert.Same(product, brand.Product);
Assert.Same(pirates, brand.Maker);
}
}
}

View file

@ -116,6 +116,56 @@ public sealed class RestoredHullsTests
return planetOrbits.Count(o => o.Parent.IsSet() && o.Parent.Key.Equals(orbit.Parent.Key) && abs(o.Distance - orbit.Distance) < .1f) > 1;
}
// The zone a test needs is chosen by the property its claim is about, from the galaxy the generator rolled, because
// which zone has that property follows the noise kernel (CultMath 0.3.0 re-rolled "EAC-7089" and "EAC-2733" away).
// A planet orbit is a genuine Lagrange candidate when it is the only planet at its distance under its parent --
// exactly what ZoneGenerator's potentialLagrangePoints filter keeps.
private static OrbitData[] ParentedPlanetOrbits(CultCache cache, ZonePack pack) =>
pack.Planets.Select(p => cache.Get(cache.Get(p).Orbit)).Where(o => o.Parent.IsSet()).ToArray();
private static bool HasGenuineLagrangeCandidate(OrbitData[] planetOrbits) =>
planetOrbits.Any(o => planetOrbits.Count(c => c.Parent.Key.Equals(o.Parent.Key) && abs(c.Distance - o.Distance) < .1f) == 1);
// The first seed, and in its tutorial galaxy the first non-entrance zone, that has planets every one of which is a
// rosette member: no genuine Lagrange candidate, so only the entrance's widened candidate set can seat a station
// there. Such a zone is rare, so seeds are tried in order until one has it.
// The scan is the cost (tens of seconds), and it depends only on the generator, so both tests share one result
// through a lazy computed under its own scratch run store.
private static readonly Lazy<(uint seed, string zoneName)> NoLagrangeCandidateZoneScan = new(ScanForNoLagrangeCandidateZone);
private static (uint seed, string zoneName) NoLagrangeCandidateZone() => NoLagrangeCandidateZoneScan.Value;
private static (uint seed, string zoneName) ScanForNoLagrangeCandidateZone()
{
var scratchRun = Path.Combine(Path.GetTempPath(), $"aetheria-nolagrange-scan-{Guid.NewGuid():N}.cc");
try
{
using var cache = OpenReadOnlyRealCatalogWithScratchRun(Path.Combine(FindRepoRoot(), "GameData", "Aetheria.cc"), scratchRun);
return ScanForNoLagrangeCandidateZone(cache);
}
finally
{
if (File.Exists(scratchRun)) File.Delete(scratchRun);
}
}
private static (uint seed, string zoneName) ScanForNoLagrangeCandidateZone(CultCache cache)
{
var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { });
for (var seed = 1u; seed <= 64u; seed++)
{
var galaxy = new Galaxy(TutorialGalaxySettings(), TutorialBackgroundSettings(), TutorialNameSettings(),
cache, new PlayerSettings(), new DirectoryInfo(Path.GetTempPath()), _ => { }, null, seed);
foreach (var zone in galaxy.Zones.Where(z => !ReferenceEquals(z, galaxy.Entrance)))
{
var orbits = ParentedPlanetOrbits(cache, ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), galaxy, zone, isTutorial: false, ambient: false));
if (orbits.Length > 0 && !HasGenuineLagrangeCandidate(orbits)) return (seed, zone.Name);
}
}
Assert.Fail("fixture: no tutorial galaxy at seeds 1-64 has a zone whose planets are all rosette members.");
return default;
}
// ZoneGenerator.GenerateZone writes OrbitData/BodyData (run-store types, AetheriaStores.RunTypes), so a
// catalog-only cache has no home for them. A scratch run file, deleted after the seed that used it.
private static CultCache OpenReadOnlyRealCatalogWithScratchRun(string catalogPath, string runPath)
@ -201,6 +251,23 @@ public sealed class RestoredHullsTests
}
}
// The dock intro dereferences the ship's VelocityLimit unguarded (ActionGameManager), so every ship hull the catalog
// ships carries exactly one, with a top speed that is a finite positive number. After the retirement
// (ruling retire-longinusx) the shipped ship hulls are the Longinus and the Djinni.
[Fact]
public void EveryShippedShipHullHasATopSpeed()
{
using var cache = OpenCatalog();
var ships = cache.GetAll<HullData>().Where(h => h.HullType == HullType.Ship).OrderBy(h => h.Name, StringComparer.Ordinal).ToArray();
Assert.Equal(new[] { "Djinni", "Longinus" }, ships.Select(h => h.Name));
foreach (var hull in ships)
{
Assert.Single(hull.Behaviors.OfType<VelocityLimitData>());
var limit = BuildThrustedShip(cache, hull.Name).GetBehavior<VelocityLimit>().Limit;
Assert.True(float.IsFinite(limit) && limit > 0f, $"{hull.Name}'s top speed is {limit}");
}
}
// A restored hull with every thruster hardpoint (and its reactor) filled, activated and warmed up: the
// rotation thrusters the helm tests need. The caller owns the cache.
internal static Ship BuildThrustedShip(CultCache cache, string name)
@ -635,8 +702,8 @@ public sealed class RestoredHullsTests
return new Galaxy(cache, game, _ => { });
}
// Cut 1 fix batch 2 (Soul's finding #2): the tutorial entrance's widened candidate set. Seed 3's real tutorial
// galaxy has a zone, "EAC-7089", whose planets are entirely one rosette with no captured satellites at all: 4
// Cut 1 fix batch 2 (Soul's finding #2): the tutorial entrance's widened candidate set. A real tutorial
// galaxy has a zone (NoLagrangeCandidateZone finds one; under CultMath 0.2.x it was seed 3's "EAC-7089"), whose planets are entirely one rosette with no captured satellites at all: 4
// planets sharing one Distance under one Parent, and nothing else -- potentialLagrangePoints is empty for it
// (verified directly against this exact fixture, not carried over from Soul's own forced-fallback probe, whose
// own candidate check undercounted planet orbits by using pack.Planets.Count -- which excludes Empty rosette
@ -661,7 +728,8 @@ public sealed class RestoredHullsTests
try
{
using var cache = OpenReadOnlyRealCatalogWithScratchRun(gameData, scratchRun);
var galaxy = BuildGalaxyWithForcedEntrance(cache, seed: 3u, "EAC-7089");
var (seed, zoneName) = NoLagrangeCandidateZone();
var galaxy = BuildGalaxyWithForcedEntrance(cache, seed, zoneName);
var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { });
var pack = ZoneGenerator.GenerateZone(items, TutorialZoneSettings(), galaxy, galaxy.Entrance, isTutorial: true);
@ -699,7 +767,7 @@ public sealed class RestoredHullsTests
// Cut 1 fix batch 2 (Soul's finding #2, leak check): the entrance override must not leak to (a) other
// tutorial zones or (b) a non-tutorial game's own entrance zone. Both are pinned against a seed-1 galaxy --
// the widened-candidate test above uses a different fixture, seed 3's "EAC-7089" -- so this test and the one
// the widened-candidate test above uses a different fixture, NoLagrangeCandidateZone's -- so this test and the one
// below it stand or fall on this one known fixture, not that one.
[Fact]
public void EntranceOverrideDoesNotLeakToOtherTutorialZonesOrNonTutorialGames()
@ -720,7 +788,8 @@ public sealed class RestoredHullsTests
// (a) A non-entrance tutorial zone that naturally rolls zero stations keeps that roll under
// isTutorial: true -- the floor must not leak past the galaxy.Entrance reference check.
var otherZone = galaxy.Zones.Single(z => z.Name == "EAC-2733");
// The zone is chosen by its natural roll: zero stations without the tutorial floor (isTutorial: false).
var otherZone = galaxy.Zones.First(z => !ReferenceEquals(z, galaxy.Entrance) && StationCount(z, isTutorial: false) == 0);
Assert.NotSame(galaxy.Entrance, otherZone);
Assert.Equal(0, StationCount(otherZone, isTutorial: true));
@ -775,7 +844,7 @@ public sealed class RestoredHullsTests
}
// Cut 1 fix batch 3 (F6, N2): the entrance-only widening must not leak to a non-entrance zone that would
// otherwise get zero stations. Seed 3's "EAC-7089" (the same no-Lagrange fixture the widened-candidate test
// otherwise get zero stations. NoLagrangeCandidateZone's zone (the same no-Lagrange fixture the widened-candidate test
// above uses, this time NOT retargeted as Entrance) rolls a real, nonzero station count on its own -- forced
// here by boosting one faction's presence there (HomeZone distance 0, InfluenceDistance 50, so the roll's
// floor(rand * (factionPresence+1)) is overwhelmingly likely nonzero) via the same public SavedGame round
@ -831,8 +900,9 @@ public sealed class RestoredHullsTests
try
{
using var cache = OpenReadOnlyRealCatalogWithScratchRun(gameData, scratchRun);
var galaxy = BuildGalaxyWithBoostedPresence(cache, seed: 3u, "EAC-7089");
var zone = galaxy.Zones.Single(z => z.Name == "EAC-7089");
var (seed, zoneName) = NoLagrangeCandidateZone();
var galaxy = BuildGalaxyWithBoostedPresence(cache, seed, zoneName);
var zone = galaxy.Zones.Single(z => z.Name == zoneName);
Assert.NotSame(galaxy.Entrance, zone);
var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { });
@ -840,8 +910,7 @@ public sealed class RestoredHullsTests
// Confirms this fixture still has no genuine (non-rosette) Lagrange candidate -- a regression here
// would mean the fixture no longer probes what this test claims to probe.
var planetOrbits = pack.Planets.Select(p => cache.Get(cache.Get(p).Orbit)).Where(o => o.Parent.IsSet()).ToArray();
var hasGenuineCandidate = planetOrbits.Any(o => planetOrbits.Count(c => c.Parent.Key.Equals(o.Parent.Key) && abs(c.Distance - o.Distance) < .1f) == 1);
var hasGenuineCandidate = HasGenuineLagrangeCandidate(ParentedPlanetOrbits(cache, pack));
Assert.False(hasGenuineCandidate, "the entrance-adjacent fixture zone now has a genuine Lagrange candidate; it no longer tests the no-Lagrange leak path.");
var stationCount = pack.Entities.OfType<OrbitalEntityPack>().Count(e => (cache.Get(e.Hull.Data) as HullData)?.HullType == HullType.Station);

View file

@ -0,0 +1,228 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
using Xunit;
// AetherDb's roles-backfill command (aetheria-release, cut roles-backfill) run on a scratch copy of the shipped catalog,
// with the designs it backfills put back to the state they shipped in before it: flat stats at the middle of their range,
// no roles, no seller quality, and the unnamed Quality terms of the stats that already varied. The shipped catalog is the
// 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" };
// 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"),
};
private readonly string _root = Path.Combine(Path.GetTempPath(), "roles-backfill-" + Guid.NewGuid().ToString("N"));
private string CatalogPath => Path.Combine(_root, "GameData", "Aetheria.cc");
private readonly Dictionary<string, string> _shipped = new Dictionary<string, string>();
public RolesBackfillCommandTests()
{
Directory.CreateDirectory(Path.Combine(_root, "GameData"));
File.Copy(Path.Combine(AetherDb.FindRoot(), "GameData", "Aetheria.cc"), CatalogPath);
using var cache = new CultCache(ScopedRegistry());
cache.AddBackingStore(new SingleFileMessagePackBackingStore(CatalogPath), AetheriaStores.CatalogTypes);
var products = cache.GetAll<FactionProductData>().ToArray();
foreach (var design in cache.GetAll<EquippableItemData>().Where(d => Flattened.Contains(d.Name) || Unnamed.Any(u => u.Design == d.Name)))
_shipped[design.Name] = Describe(cache, design, products);
}
// A registry scoped to the shipped assembly, so this test assembly's own documents never reach the real catalog.
private static CultDocumentRegistry ScopedRegistry() => CultDocumentRegistry.ForTypes(typeof(ItemData).Assembly.GetTypes()
.Where(t => t is { IsAbstract: false, IsInterface: false })
.Where(t => t.GetCustomAttribute<CultDocumentAttribute>() != null));
// Puts the named designs back to the state they shipped in before the backfill, through a registry scoped to the shipped
// assembly (as PiratesFactionCommandTests strips its faction).
private void Reset(bool flattened, bool unnamed)
{
using var cache = new CultCache(ScopedRegistry());
cache.AddBackingStore(new SingleFileMessagePackBackingStore(CatalogPath), AetheriaStores.CatalogTypes);
var designs = cache.GetAll<EquippableItemData>().ToArray();
var products = cache.GetAll<FactionProductData>().ToArray();
var changed = new List<object>();
if (flattened)
foreach (var design in designs.Where(d => Flattened.Contains(d.Name)))
{
foreach (var (_, stat) in CatalogRoleTests.StatsOf(design))
{
if (stat.Min != stat.Max) stat.Min = stat.Max = (stat.Min + stat.Max) / 2f;
// The drives shipped with unnamed Quality terms on their flat stats (roles-migrate); the command keeps those
// exponents and names them. The other four shipped with no term at all.
if (design.Name.EndsWith(" Drive", StringComparison.Ordinal)) foreach (var term in stat.Terms.Where(t => t.Source == StatSource.Quality)) term.Role = null;
else stat.Terms.RemoveAll(t => t.Source == StatSource.Quality);
}
design.Roles = new List<ItemRole>();
changed.Add(design);
// Small Drive shipped with its sellers' quality already authored (roles-migrate); only its stats were flat.
foreach (var product in products.Where(p => design.Name != "Small Drive" && p.Design.Key.Equals(cache.RefOf(design).Key)))
{
product.Roles = new List<ProductRole>();
changed.Add(product);
}
}
if (unnamed)
foreach (var (name, field) in Unnamed)
{
var design = designs.Single(d => d.Name == name);
foreach (var term in Stat(design, field).Terms.Where(t => t.Source == StatSource.Quality)) term.Role = null;
changed.Add(design);
}
if (changed.Count > 0)
cache.Commit(batch =>
{
foreach (var document in changed) batch.Upsert(document.GetType(), document, cache.RefOf(document).Key);
});
cache.FlushAsync().Wait();
// Then the record AetherDb's process-wide registry demands in this test host (as PiratesFactionCommandTests).
using (var plain = new CultCache())
{
plain.AddBackingStore(new SingleFileMessagePackBackingStore(CatalogPath), AetheriaStores.CatalogTypes);
plain.Upsert(new TestCatalogGlobal { Name = "Temperament" });
plain.FlushAsync().Wait();
}
}
public void Dispose() => Directory.Delete(_root, true);
private static PerformanceStat Stat(EquippableItemData design, string field) =>
Assert.Single(CatalogRoleTests.StatsOf(design), s => s.Name.EndsWith("." + field)).Stat;
// Everything the command decides about one design: its roles, each stat's range, role and exponent, and its sellers' role quality.
private static string Describe(CultCache cache, EquippableItemData design, FactionProductData[] products)
{
static string F(float v) => float.IsInfinity(v) ? v.ToString() : ((double) v).ToString("G5");
var stats = CatalogRoleTests.StatsOf(design).Select(s =>
$"{s.Name} {F(s.Stat.Min)}..{F(s.Stat.Max)} {string.Join("+", s.Stat.Terms.Where(t => t.Source == StatSource.Quality && !string.IsNullOrEmpty(t.Role)).Select(t => $"{t.Role}^{F(t.Exponent)}"))}");
var sellers = products.Where(p => p.Design.Key.Equals(cache.RefOf(design).Key)).OrderBy(p => p.Name, StringComparer.Ordinal)
.Select(p => $"{p.Name}: " + string.Join(", ", (p.Roles ?? new List<ProductRole>()).OrderBy(r => r.Role, StringComparer.Ordinal)
.Select(r => $"{r.Role} {F(r.Mean)}/{F(r.StandardDeviation)}")));
var roles = "roles " + string.Join(", ", (design.Roles ?? new List<ItemRole>()).Select(r => r.Name).OrderBy(r => r, StringComparer.Ordinal));
return string.Join("\n", new[] { roles }.Concat(stats).Concat(sellers));
}
private Dictionary<string, string> Read()
{
var db = AetherDb.Open(root: _root);
try
{
var products = db.Cache.GetAll<FactionProductData>().ToArray();
return db.Cache.GetAll<EquippableItemData>().Where(d => _shipped.ContainsKey(d.Name))
.ToDictionary(d => d.Name, d => Describe(db.Cache, d, products));
}
finally { db.Cache.Dispose(); }
}
[Fact]
public void A_dry_run_writes_nothing_and_apply_lands_what_the_catalog_ships_and_replays_as_a_no_op()
{
Reset(flattened: true, unnamed: true);
var before = File.ReadAllBytes(CatalogPath);
var start = Read();
Assert.All(_shipped.Keys, name => Assert.NotEqual(_shipped[name], start[name]));
Assert.Equal(0, Program.RolesBackfill(apply: false, root: _root));
Assert.Equal(before, File.ReadAllBytes(CatalogPath));
Assert.Equal(0, Program.RolesBackfill(apply: true, root: _root));
var landed = File.ReadAllBytes(CatalogPath);
Assert.NotEqual(before, landed);
var after = Read();
foreach (var name in _shipped.Keys.OrderBy(n => n, StringComparer.Ordinal))
Assert.Equal(_shipped[name], after[name]);
// A second apply finds every stat ranged and named and every seller authored, and writes nothing.
Assert.Equal(0, Program.RolesBackfill(apply: true, root: _root));
Assert.Equal(landed, File.ReadAllBytes(CatalogPath));
}
// Only unnamed Quality terms to name: no seller and no range changes, and apply must still land the designs.
[Fact]
public void Naming_an_unnamed_term_alone_lands_without_touching_ranges_or_sellers()
{
Reset(flattened: false, unnamed: true);
var before = File.ReadAllBytes(CatalogPath);
var start = Read();
Assert.All(Unnamed.Select(u => u.Design), name => Assert.NotEqual(_shipped[name], start[name]));
Assert.Equal(0, Program.RolesBackfill(apply: true, root: _root));
Assert.NotEqual(before, File.ReadAllBytes(CatalogPath));
var after = Read();
foreach (var (name, _) in Unnamed) Assert.Equal(_shipped[name], after[name]);
}
// The exponents a first apply authors do not depend on which designs it targets: applied to the base-shaped catalog, the
// command reproduces the shipped exponents of Autocannon and LRMM72, which differ across stats (the mode is not one value).
[Fact]
public void Apply_on_the_base_shaped_catalog_reproduces_the_shipped_exponents()
{
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" };
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());
Assert.All(designs, name => Assert.True(shipped[name].Values.Distinct().Count() > 1, name + " exponents are one value; the test would not tell a mode from a default"));
Reset(flattened: true, unnamed: true);
Assert.Equal(0, Program.RolesBackfill(apply: true, root: _root));
var db = AetherDb.Open(root: _root);
Dictionary<string, Dictionary<string, float>> after;
try { after = Read(db.Cache.GetAll<EquippableItemData>().ToArray()); }
finally { db.Cache.Dispose(); }
foreach (var name in designs) Assert.Equal(shipped[name].OrderBy(x => x.Key, StringComparer.Ordinal), after[name].OrderBy(x => x.Key, StringComparer.Ordinal));
}
// A seller that authors one of a design's two roles gets only the other one added, and keeps the one it authored.
[Fact]
public void A_seller_with_one_of_two_roles_authored_gains_only_the_missing_role()
{
Reset(flattened: false, unnamed: false);
var db = AetherDb.Open(catalogWritable: true, root: _root);
var autocannon = db.Cache.GetAll<WeaponItemData>().Single(weapon => weapon.Name == "Autocannon");
var seller = db.Cache.GetAll<FactionProductData>().OrderBy(p => p.Name, StringComparer.Ordinal).First(p => p.Design.Key.Equals(db.Cache.RefOf(autocannon).Key) && p.Roles.Count == 2);
var kept = seller.Roles.OrderBy(r => r.Role, StringComparer.Ordinal).First();
kept.Mean = .91f;
seller.Roles = new List<ProductRole> { kept };
var sellerName = seller.Name;
var keptRole = kept.Role;
db.Cache.Commit(batch => batch.Upsert(typeof(FactionProductData), seller, db.Cache.RefOf(seller).Key));
db.Cache.Dispose();
Assert.Equal(0, Program.RolesBackfill(apply: true, root: _root));
db = AetherDb.Open(root: _root);
try
{
var after = db.Cache.GetAll<FactionProductData>().Single(p => p.Name == sellerName);
Assert.Equal(new[] { "barrel", "feed mechanism" }, after.Roles.Select(r => r.Role).OrderBy(r => r, StringComparer.Ordinal).ToArray());
Assert.Equal(.91f, after.Roles.Single(r => r.Role == keptRole).Mean, 3);
}
finally { db.Cache.Dispose(); }
}
[Fact]
public void A_design_the_catalog_does_not_hold_refuses_and_lands_nothing()
{
Reset(flattened: false, unnamed: false);
var db = AetherDb.Open(catalogWritable: true, root: _root);
var autocannon = db.Cache.GetAll<WeaponItemData>().Single(weapon => weapon.Name == "Autocannon");
autocannon.Name = "Autocannon (renamed)";
db.Cache.Commit(batch => batch.Upsert(typeof(WeaponItemData), autocannon, db.Cache.RefOf(autocannon).Key));
db.Cache.Dispose();
var before = File.ReadAllBytes(CatalogPath);
Assert.Throws<InvalidOperationException>(() => Program.RolesBackfill(apply: true, root: _root));
Assert.Equal(before, File.ReadAllBytes(CatalogPath));
}
}

View file

@ -41,7 +41,6 @@ public sealed partial class RunStartTests
[Fact]
public void Boss_spawns_once_in_boss_zone()
{
AddPirates();
foreach (var seed in DemoSeeds.Take(3))
{
var galaxy = DemoGalaxy(seed);
@ -65,7 +64,6 @@ public sealed partial class RunStartTests
[Fact]
public void Boss_spawns_in_a_zone_that_is_not_ambient()
{
AddPirates();
var galaxy = DemoGalaxy(1);
var pack = BossZonePack(galaxy, _items, galaxy.Exit, ambient: false);
Assert.Single(pack.Entities, entity => entity.Boss);
@ -75,7 +73,6 @@ public sealed partial class RunStartTests
[Fact]
public void Boss_hull_from_BossHull_else_fallback()
{
AddPirates();
var galaxy = DemoGalaxy(1);
var antagonist = Zhestokost(galaxy);
var hulls = SoldShipHulls().OrderByDescending(hull => hull.Price).ThenBy(hull => hull.Name, StringComparer.Ordinal).ToArray();
@ -103,7 +100,6 @@ public sealed partial class RunStartTests
[Fact]
public void Boss_hull_nobody_sells_falls_back()
{
AddPirates();
var galaxy = DemoGalaxy(1);
var antagonist = Zhestokost(galaxy);
var sold = SoldShipHulls();
@ -121,7 +117,6 @@ public sealed partial class RunStartTests
[Fact]
public void Exit_sealed_until_boss_dies()
{
AddPirates();
var galaxy = DemoGalaxy(1);
var exit = ZoneOf(galaxy, galaxy.Exit);
var boss = Assert.Single(exit.Entities, entity => entity.IsBoss);
@ -143,7 +138,6 @@ public sealed partial class RunStartTests
[Fact]
public void Boss_mark_survives_continue()
{
AddPirates();
var (galaxy, arena, staged, failures) = Launch(new DemoTerminus(), Inputs(() => 1));
Assert.True(failures.Count == 0, string.Join("; ", failures));
galaxy.Entrance.Contents = arena;
@ -185,7 +179,6 @@ public sealed partial class RunStartTests
[Fact]
public void Exit_sealed_and_logged_when_the_boss_cannot_be_generated()
{
AddPirates();
var galaxy = DemoGalaxy(1);
galaxy.BossZones.Clear();
var log = new List<string>();
@ -201,7 +194,6 @@ public sealed partial class RunStartTests
[Fact]
public void Exit_open_after_save_of_a_slain_boss()
{
AddPirates();
var galaxy = DemoGalaxy(1);
var exit = ZoneOf(galaxy, galaxy.Exit);
Assert.Single(exit.Entities, entity => entity.IsBoss).HeatstrokeDeath.OnNext(Unit.Default);
@ -215,7 +207,6 @@ public sealed partial class RunStartTests
[Fact]
public void Exit_gate_shares_no_point_with_a_wormhole()
{
AddPirates();
var ratio = float.Parse(File.ReadLines(Path.Combine(FindRepoRoot(), "Assets", "Resources", "Settings.asset"))
.Select(line => Regex.Match(line, @"^ WormholeDistanceRatio: (.+)$")).First(match => match.Success).Groups[1].Value.Trim(),
System.Globalization.CultureInfo.InvariantCulture);
@ -244,7 +235,6 @@ public sealed partial class RunStartTests
[InlineData(new[] { 0.0, 45.0, 90.0, 135.0, 180.0, -135.0, -90.0, -45.0 })]
public void Exit_gate_sits_in_the_widest_gap_at_the_wormhole_radius(double[] neighbourDegrees)
{
AddPirates();
var galaxy = DemoGalaxy(1);
var zone = ZoneOf(galaxy, galaxy.Exit);
const float ratio = 0.75f;

View file

@ -360,6 +360,48 @@ public sealed class RunSaveTests : IDisposable
}
}
// A lot's product is what names its units, so it must come back from the run file as the same product key; a lot
// minted without one reads unset.
[Fact]
public void ALotsProductSurvivesTheRunSave()
{
CultRecordRef<FactionProductData> product;
using (var cache = AetheriaStores.Open(Catalog, catalogWritable: true))
{
var lamp = new CultRecordRef<CraftedItemData>(cache.Upsert(new GearData { Name = "Lamp" }).Key);
var maker = cache.RefOf(cache.GetAll<Faction>().Single());
product = new CultRecordRef<FactionProductData>(cache.Upsert(
new FactionProductData { Name = "Lamp Prime", Design = lamp, Manufacturer = maker }).Key);
cache.FlushAsync().Wait();
}
using (var cache = Open())
{
var design = cache.RefOf<ItemData>(cache.GetByName<GearData>("Lamp"));
var lots = new ProvenanceLedger { NextLot = 3 };
lots.Lots[1] = new Lot { Design = design, Origin = new Attributed(), Product = product };
lots.Lots[2] = new Lot { Design = design, Origin = new Attributed() };
var zone = new SavedZone
{
Name = "Zone 0", AdjacentZones = Array.Empty<int>(), Factions = Array.Empty<int>(), Owner = -1,
Contents = new ZonePack
{
Entities = new List<EntityPack>
{
BarePack(hull: new EquippableItem { Data = design, Lot = 1 }),
BarePack(hull: new EquippableItem { Data = design, Lot = 2 })
}
}
};
RunSave.Commit(cache, Game(cache), new[] { zone }, lots);
}
using (var cache = Open())
{
var stored = RunSave.Lots(cache);
Assert.Equal(product.Key, stored[1].Product.Key);
Assert.False(stored[2].Product.IsSet());
}
}
// MQ4: Continue refuses a run that names a design the catalog no longer holds, naming the missing mod ships, and
// never edits the save. A design can be named by an item in a zone or only by a minted lot, so each is covered.
[Theory]

View file

@ -0,0 +1,134 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System.Collections.Generic;
using System.Linq;
using GameCult.Caching;
using Xunit;
// Gear does not need its maker present: LoadoutGenerator.IsAvailable reaches by allegiance alone, and an absent
// maker only weighs less (operator, 2026-10-06: a faction need not be present in the galaxy for its gear to be
// available). Every galaxy reaches the same way, the prelude included.
public sealed partial class RunStartTests
{
// A maker the galaxy does not carry, with one product made from a real design, and a generator for a fresh
// faction whose allegiance names exactly the makers given (the absent one among them, or not).
private (FactionProductData product, Faction absent) AbsentMaker(string name)
{
var absent = new Faction { Name = name, ShortName = name };
_cache.Upsert(absent);
var design = _cache.GetAll<FactionProductData>().First(p => p.Manufacturer.IsSet()).Design;
var product = new FactionProductData { Name = name + " Product", Design = design, Manufacturer = _cache.RefOf(absent) };
_cache.Upsert(product);
return (product, absent);
}
private LoadoutGenerator GeneratorFor(Galaxy galaxy, string name, params Faction[] allies)
{
var faction = new Faction { Name = name, ShortName = name };
_cache.Upsert(faction);
foreach (var ally in allies) faction.Allegiance[_cache.RefOf(ally)] = 1;
return new LoadoutGenerator(ref _items.Random, _items, galaxy, galaxy.Entrance, faction, .5f);
}
[Fact]
public void AnAbsentMakersGearIsAvailableThroughAllegiance()
{
var galaxy = MainSectorGalaxy();
var (product, absent) = AbsentMaker("AbsentAlly");
Assert.DoesNotContain(galaxy.Factions, f => f == absent);
Assert.True(GeneratorFor(galaxy, "Friend", absent).IsAvailable(product));
}
[Fact]
public void AnAbsentMakerOutsideAllegianceIsNot()
{
var galaxy = MainSectorGalaxy();
var (product, _) = AbsentMaker("AbsentStranger");
Assert.False(GeneratorFor(galaxy, "Loner").IsAvailable(product));
}
[Fact]
public void AFactionlessGeneratorReachesEveryMaker()
{
var galaxy = MainSectorGalaxy();
AbsentMaker("AbsentToAll");
var generator = new LoadoutGenerator(ref _items.Random, _items, galaxy, galaxy.Entrance, null, .5f);
var products = _cache.GetAll<FactionProductData>().Where(p => p.Manufacturer.IsSet()).ToArray();
Assert.NotEmpty(products);
Assert.All(products, product => Assert.True(generator.IsAvailable(product), product.Name));
}
[Fact]
public void AnAbsentMakerWeighsAsTheFarthest()
{
var galaxy = MainSectorGalaxy();
var (product, absent) = AbsentMaker("AbsentFar");
var zone = galaxy.Entrance;
var farthest = galaxy.Factions
.Where(f => galaxy.HomeZones.TryGetValue(f, out var home) && zone.Distance.ContainsKey(home))
.OrderByDescending(f => zone.Distance[galaxy.HomeZones[f]]).First();
var generator = GeneratorFor(galaxy, "Trader", absent, farthest);
var absentWeight = generator.ManufacturerPreference(product.Manufacturer);
var farthestWeight = generator.ManufacturerPreference(_cache.RefOf(farthest));
Assert.True(absentWeight > 0, "an absent ally is reachable");
Assert.True(absentWeight < farthestWeight, $"absent {absentWeight} must weigh below the farthest present maker {farthestWeight}");
Assert.Equal(1f / (2 + zone.Distance.Values.Max()), absentWeight);
}
[Fact]
public void APreludeNoLongerOffersEverything()
{
Assert.True(_galaxy.IsPrelude);
var (absentProduct, _) = AbsentMaker("AbsentToPrelude");
var generator = GeneratorFor(_galaxy, "PreludeLoner");
Assert.False(generator.IsAvailable(absentProduct));
var present = _cache.GetAll<FactionProductData>().Where(p => p.Manufacturer.IsSet() &&
_galaxy.Factions.Any(f => _cache.RefOf(f).Key.Equals(p.Manufacturer.Key))).ToArray();
Assert.NotEmpty(present);
Assert.All(present, product => Assert.False(generator.IsAvailable(product), product.Name));
}
// Preference only weighs by distance when there is a galaxy and a faction to weigh for.
[Fact]
public void PreferenceIsNeutralWithoutAGalaxyOrAFaction()
{
var galaxy = MainSectorGalaxy();
var (product, absent) = AbsentMaker("AbsentNeutral");
var faction = galaxy.Factions.First();
var noGalaxy = new LoadoutGenerator(ref _items.Random, _items, null, null, faction, .5f);
var noFaction = new LoadoutGenerator(ref _items.Random, _items, galaxy, galaxy.Entrance, null, .5f);
Assert.Equal(1f, noGalaxy.ManufacturerPreference(product.Manufacturer));
Assert.Equal(1f, noFaction.ManufacturerPreference(product.Manufacturer));
}
// A maker the generator's faction does not name weighs nothing, present or not.
[Fact]
public void AMakerOutsideAllegianceWeighsNothing()
{
var galaxy = MainSectorGalaxy();
var (product, _) = AbsentMaker("AbsentUnnamed");
var generator = GeneratorFor(galaxy, "Hermit");
var stranger = galaxy.Factions.First();
Assert.Equal(0f, generator.ManufacturerPreference(product.Manufacturer));
Assert.Equal(0f, generator.ManufacturerPreference(_cache.RefOf(stranger)));
}
// The distance table decides: a present maker whose home the table does not reach adds no distance, an absent
// maker is one jump past the table's farthest zone, and an empty table adds none either way.
[Fact]
public void ADistanceTableOnlyDistancesTheMakersItNames()
{
var galaxy = MainSectorGalaxy();
var (product, absent) = AbsentMaker("AbsentOffTable");
var present = galaxy.Factions.First(f => galaxy.HomeZones.TryGetValue(f, out var home) && home != galaxy.Entrance);
var friend = GeneratorFor(galaxy, "Ally", absent, present);
var table = new GalaxyZone { Distance = new Dictionary<GalaxyZone, int> { { galaxy.Entrance, 0 } } };
var generator = new LoadoutGenerator(ref _items.Random, _items, galaxy, table, friend.Faction, .5f);
Assert.Equal(1f, generator.ManufacturerPreference(_cache.RefOf(present))); // home not in the table: distance 0
Assert.Equal(.5f, generator.ManufacturerPreference(product.Manufacturer)); // absent: 0 + 1
var empty = new LoadoutGenerator(ref _items.Random, _items, galaxy, new GalaxyZone { Distance = new Dictionary<GalaxyZone, int>() }, friend.Faction, .5f);
Assert.Equal(1f, empty.ManufacturerPreference(product.Manufacturer));
}
}

View file

@ -119,8 +119,8 @@ public sealed partial class RunStartTests : IDisposable
private const float Freezing = 273.15f;
// A main-sector galaxy (not the prelude, which offers every product): each station's gear must come from
// manufacturers its faction can reach, the galaxy's factions its allegiance names.
// A main-sector galaxy: each station's gear must come from manufacturers its faction can reach, the makers its
// allegiance names, present in the galaxy or not.
private Galaxy MainSectorGalaxy()
{
var authored = AuthoredSettings.Load(FindRepoRoot());
@ -670,7 +670,7 @@ public sealed partial class RunStartTests : IDisposable
public void TheRealHullsMaterializeBareFromABrandedProduct()
{
var available = new LoadoutGenerator(ref _items.Random, _items, _galaxy, _galaxy.Entrance, null, 2);
foreach (var hull in new[] { Hull("Djinni"), Hull("LonginusX"), TurretHull() })
foreach (var hull in new[] { Hull("Djinni"), Hull("Longinus"), TurretHull() })
{
var failures = new List<string>();
var entity = Loadouts.Materialize(_items, null, BareLoadout(hull), available.IsAvailable, failures);

View file

@ -96,7 +96,6 @@ public sealed partial class RunStartTests
[Fact]
public void EveryScenarioStages()
{
AddPirates();
Assert.Equal(EveryScenario.Count(), EveryScenario.Select(scenario => scenario.Name).Distinct().Count());
foreach (var scenario in EveryScenario)
{
@ -130,7 +129,7 @@ public sealed partial class RunStartTests
[Fact]
public void ModesMatchOldNewGame()
{
Assert.Equal("LonginusX", _startingHull);
Assert.Equal("Longinus", _startingHull);
var tutorial = Launch(new TutorialGalaxy(), Inputs(() => GalaxySeed));
Assert.Empty(tutorial.failures);
@ -286,8 +285,8 @@ public sealed partial class RunStartTests
var failures = Refused(Arena(true), new Scripted(true, stage =>
{
stage.Player(stage.Bare("Djinni"), float2(0, 0));
stage.Place(stage.Generated("LonginusX"), float2(300, 0), stance: ScenarioStance.Hostile, piloted: true);
stage.Place(stage.Fit("LonginusX", ("No Such Gun", int2(1, 8), ItemRotation.None)), float2(-300, 0));
stage.Place(stage.Generated("Longinus"), float2(300, 0), stance: ScenarioStance.Hostile, piloted: true);
stage.Place(stage.Fit("Longinus", ("No Such Gun", int2(1, 8), ItemRotation.None)), float2(-300, 0));
}));
Assert.Contains("No Such Gun", Assert.Single(failures));
}
@ -302,8 +301,8 @@ public sealed partial class RunStartTests
var staged = Stage(zone, new Scripted(true, stage =>
{
stage.Player(stage.Bare("Djinni"), float2(0, 0));
stage.Place(stage.Generated("LonginusX"), float2(300, 0), stance: ScenarioStance.Hostile, piloted: true);
stage.Place(stage.Bare("LonginusX"), float2(-300, 0), stance: ScenarioStance.Neutral, piloted: false);
stage.Place(stage.Generated("Longinus"), float2(300, 0), stance: ScenarioStance.Hostile, piloted: true);
stage.Place(stage.Bare("Longinus"), float2(-300, 0), stance: ScenarioStance.Neutral, piloted: false);
}));
var player = staged.Player;
var hostile = staged.Entities[0];
@ -337,8 +336,8 @@ public sealed partial class RunStartTests
var staged = Stage(zone, new Scripted(true, stage =>
{
stage.Player(stage.Bare("Djinni"), float2(0, 0));
stage.Place(stage.Bare("LonginusX"), float2(300, 0), stance: ScenarioStance.Hostile);
stage.Place(stage.Bare("LonginusX"), float2(-300, 0), stance: ScenarioStance.Hostile);
stage.Place(stage.Bare("Longinus"), float2(300, 0), stance: ScenarioStance.Hostile);
stage.Place(stage.Bare("Longinus"), float2(-300, 0), stance: ScenarioStance.Hostile);
}));
var player = staged.Player;
var hostile = staged.Entities[0];
@ -523,7 +522,6 @@ public sealed partial class RunStartTests
[Fact]
public void EveryUnsoldDesignIsAScenarioTestDesign()
{
AddPirates();
var runs = EveryScenario.Select(scenario => Launch(scenario, Inputs(() => GalaxySeed)).staged).ToList();
Assert.Empty(UnsoldAndUnplaced(runs));

View file

@ -251,7 +251,7 @@ public sealed class ShipAuthoringTests
[Theory]
[InlineData(HardpointType.Hull), InlineData(HardpointType.Tool), InlineData(HardpointType.Thermal), InlineData(HardpointType.WarpDrive),
InlineData(HardpointType.Reactor), InlineData(HardpointType.Shield), InlineData(HardpointType.Sensors),
InlineData(HardpointType.ControlModule), InlineData(HardpointType.AetherDrive)]
InlineData(HardpointType.ControlModule)]
public void AnInternalHardpointCarriesNoAnchor(HardpointType type)
{
WithOnly(type).Validate();

View file

@ -33,7 +33,7 @@ public sealed class ShipValidationTests
var ship = ShipAuthoringTests.Fixture();
ship.Hull.Hardpoints[0].Armor = 5;
ship.Hull.Hardpoints[0].FiringArc = 360;
ship.Hull.Hardpoints[0].Type = HardpointType.AetherDrive;
ship.Hull.Hardpoints[0].Type = HardpointType.ControlModule;
ship.Visual.Anchors.RemoveAll(anchor => anchor.Id == "thruster.port");
ship.Hull.Hardpoints[0].Rotation = ItemRotation.Clockwise;
ship.Validate();

View file

@ -2,7 +2,7 @@ using System.Linq;
using Xunit;
// A weapon is thermally online only while its performance exceeds the shutdown threshold (Entity.UpdatePerformance
// compares against EntitySettings.ShutdownPerformance), and wear runs at full rate below it. Hull cells
// compares against the catalog settings' DefaultEntitySettings.ShutdownPerformance, which production clones), and wear runs at full rate below it. Hull cells
// start at Entity.StartingCellTemperature, so every shipped weapon must perform there, or a ship fitted with it
// can never fire it. The catalog comes from the shipped GameData/Aetheria.cc and the temperature from the
// constant Entity builds its cells with, so a unit slip in authoring (celsius for kelvin) fails here.
@ -15,7 +15,7 @@ public sealed class ShippedWeaponOperabilityTests
var weapons = cache.GetAll<GearData>().OfType<WeaponItemData>().ToArray();
Assert.NotEmpty(weapons);
var threshold = new EntitySettings().ShutdownPerformance;
var threshold = RestoredHullsTests.Settings().DefaultEntitySettings.ShutdownPerformance;
Assert.True(threshold > 0f);
var dead = weapons.Where(weapon => weapon.Performance(Entity.StartingCellTemperature) <= threshold)

View file

@ -0,0 +1,357 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using CultMath;
using UniRx;
using Xunit;
using static CultMath.math;
using float2 = CultMath.float2;
using float3 = CultMath.float3;
// SimClock owns sim time's relation to real time: frames of real seconds in, whole fixed steps out. Nothing here hands
// a clock to a presenter; DrawAhead is pure reads of the latest state.
public sealed class SimClockTests
{
private static readonly float[] Irregular = { 1f / 144, 1f / 30, 1f / 90 };
// Runs frames cycling through the lengths until the clock has run the steps; returns the step values it passed.
private static List<float> Drive(SimClock clock, float[] frames, long steps)
{
var passed = new List<float>();
for (var frame = 0; clock.Steps < steps; frame++)
clock.Advance(frames[frame % frames.Length], dt => passed.Add(dt));
return passed;
}
[Fact]
public void TheStepNeverChanges()
{
foreach (var frames in new[] { new[] { 1f / 60 }, Irregular, new[] { .09f, .004f, 0f, 3f } })
{
var clock = new SimClock(1f / 60f);
var passed = Drive(clock, frames, 500);
Assert.True(passed.Count >= 500);
Assert.All(passed, dt => Assert.Equal(clock.Step, dt));
}
var slow = new SimClock(.1f, 6);
Assert.All(Drive(slow, Irregular, 50), dt => Assert.Equal(.1f, dt));
}
[Fact]
public void StepsFollowRealTime()
{
// Ten real seconds of irregular frames.
var clock = new SimClock(1f / 60f);
var elapsed = 0.0;
for (var frame = 0; elapsed < 10.0; frame++)
{
var seconds = Irregular[frame % Irregular.Length];
elapsed += seconds;
clock.Advance(seconds, _ => { });
}
Assert.InRange(elapsed, 10.0, 10.1);
Assert.InRange(clock.Steps, Math.Round(elapsed * 60) - 1, Math.Round(elapsed * 60) + 1);
// A frame that pays for exactly one step runs it (binary-exact seconds, so nothing rounds).
var exact = new SimClock(.25f, 16);
Assert.Equal(1, exact.Advance(.0625f, _ => { }));
Assert.Equal(0f, exact.Lead);
var slow = new SimClock(1f / 60f, 30);
for (var frame = 0; frame < 600; frame++) slow.Advance(1f / 60, _ => { });
Assert.InRange(slow.Steps, 299, 301);
}
[Fact]
public void AHitchIsClamped()
{
var clock = new SimClock(1f / 60f);
var ran = clock.Advance(5f, _ => { });
Assert.Equal(6, ran);
Assert.Equal(6, clock.Steps);
}
[Fact]
public void AStepCannotResetItsClock()
{
var clock = new SimClock(1f / 60f);
Assert.Throws<InvalidOperationException>(() => clock.Advance(1f / 60f, _ => clock.Reset()));
clock.Advance(.005f, _ => { });
Assert.True(clock.Lead > 0);
clock.Reset();
Assert.Equal(0f, clock.Lead);
Assert.Equal(1, clock.Advance(1f / 60f, _ => { }));
}
[Fact]
public void PauseFeedsNothing()
{
var clock = new SimClock(1f / 60f);
clock.Advance(.025f, _ => { });
var lead = clock.Lead;
var steps = clock.Steps;
Assert.True(lead > 0);
foreach (var seconds in new[] { 0f, -1f })
{
Assert.Equal(0, clock.Advance(seconds, _ => throw new InvalidOperationException()));
Assert.Equal(lead, clock.Lead);
Assert.Equal(steps, clock.Steps);
}
}
[Fact]
public void LeadIsHonest()
{
var clock = new SimClock(.1f, 6);
double sinceLastStep = 0;
for (var frame = 0; frame < 400; frame++)
{
// The real time since the last step: what was left over plus this frame, less the steps it paid for.
sinceLastStep += Irregular[frame % Irregular.Length];
var seconds = Irregular[frame % Irregular.Length];
clock.Advance(seconds, _ => sinceLastStep -= 1.0 / clock.StepsPerRealSecond);
Assert.InRange(clock.Lead, 0f, clock.Step * .99999f);
Assert.Equal(sinceLastStep * clock.StepsPerRealSecond * clock.Step, clock.Lead, 4);
}
}
[Fact]
public void ABadClockIsRefusedByFieldName()
{
Assert.Equal("step", Assert.Throws<ArgumentOutOfRangeException>(() => new SimClock(0f)).ParamName);
Assert.Equal("stepsPerRealSecond", Assert.Throws<ArgumentOutOfRangeException>(() => new SimClock(1f, 0f)).ParamName);
}
}
public sealed partial class RunStartTests
{
private const float ClockFrame = 1f / 60f;
private const int HistorySteps = 1800;
// The Duel launched as the game launches it, its item random reseeded so play draws the same numbers every time.
private (Zone arena, Ship player) LaunchDuel()
{
var launched = Launch(new Duel());
Assert.Empty(launched.failures);
_items.Random = new CultMath.Random(0xC0FFEE);
launched.staged.Player.MovementDirection = float2(0, 1);
launched.staged.Player.Turn = .5f;
foreach (var ship in launched.arena.Entities.OfType<Ship>())
ship.SetTarget(launched.arena.Entities.OfType<Ship>().First(other => other != ship));
return (launched.arena, launched.staged.Player);
}
private static string R(float value) => value.ToString("R", CultureInfo.InvariantCulture);
// Everything the step decides, as text: the zone clock, each entity's pose and condition, and each shot resolved.
private static string Snapshot(Zone zone, List<string> shots)
{
var text = new StringBuilder(R(zone.Time));
foreach (var entity in zone.Entities)
{
text.Append($"|{entity.Name} {R(entity.Position.x)},{R(entity.Position.z)} v{R(entity.Velocity.x)},{R(entity.Velocity.y)} " +
$"d{R(entity.Direction.x)},{R(entity.Direction.y)} w{R(entity.TurnRate)} h{R(entity.Hull.Durability)}");
if (entity.Shield != null) text.Append($" s{R(entity.Shield.Progress)}");
if (entity.Temperature != null)
{
var heat = 0f;
foreach (var cell in entity.Temperature) heat += cell;
text.Append($" t{R(heat)}");
}
}
text.Append($"|shots {string.Join(",", shots)}");
shots.Clear();
return text.ToString();
}
// Feeds the zone through one SimClock with the frames cycled, snapshotting every step until HistorySteps have run.
private static List<string> History(Zone zone, float[] frames)
{
var clock = new SimClock(1f / 60f);
var shots = new List<string>();
using var _ = zone.ShotResolved.Subscribe(outcome => shots.Add($"{outcome.ShotId}:{outcome.Result}"));
var history = new List<string>();
for (var frame = 0; history.Count < HistorySteps; frame++)
clock.Advance(frames[frame % frames.Length], dt =>
{
// Both ships open fire every 90th step, on the step count, so the fight is the same fight whatever
// the frames were.
if (history.Count % 90 == 0)
foreach (var ship in zone.Entities.OfType<Ship>())
foreach (var weapon in ship.GetBehaviors<Weapon>())
FireControl.Fire(weapon, weapon.Item, ship);
zone.Update(dt);
history.Add(Snapshot(zone, shots));
});
return history.Take(HistorySteps).ToList();
}
// Control: the same launch driven twice the same way is the same history. If this fails the simulation is
// nondeterministic before the clock is involved, and FrameTimesDoNotChangeHistory proves nothing.
[Fact]
public void OneHistoryTwice()
{
var first = History(LaunchDuel().arena, new[] { ClockFrame });
var second = History(LaunchDuel().arena, new[] { ClockFrame });
Assert.Equal(first, second);
Assert.Contains(first, line => !line.EndsWith("|shots ")); // shots were fired and resolved
}
[Fact]
public void FrameTimesDoNotChangeHistory()
{
var steady = History(LaunchDuel().arena, new[] { ClockFrame });
var irregular = History(LaunchDuel().arena, new[] { 1f / 144, 1f / 30, 1f / 90 });
Assert.Equal(steady.Count, irregular.Count);
for (var step = 0; step < steady.Count; step++)
Assert.True(steady[step] == irregular[step], $"step {step}: {steady[step]} != {irregular[step]}");
}
private static float SignedTurn(float2 before, float2 after) =>
atan2(before.x * after.y - before.y * after.x, dot(before, after));
[Fact]
public void TurnRateIsTheActuatorsTurn()
{
var (arena, player) = LaunchDuel();
Assert.Equal(0f, player.TurnRate); // staged: nothing has turned it
var turned = 0;
for (var step = 0; step < 240; step++)
{
var before = player.Direction;
arena.Update(ClockFrame);
var angle = SignedTurn(before, player.Direction);
Assert.InRange(abs(abs(angle) - abs(player.TurnRate * ClockFrame)), 0f, 1e-6f);
// A positive turn demand turns clockwise, and TurnRate is signed the way the step turned Direction.
if (abs(player.TurnRate) > 1e-4f)
{
turned++;
Assert.True(player.TurnRate > 0 == dot(player.Direction, before.Rotate(ItemRotation.Clockwise)) > 0);
}
}
Assert.True(turned > 60, "the held turn turned the ship");
// A write to Direction between steps (staging, a load, a wormhole exit) is not a turn.
player.Turn = 0;
player.MovementDirection = float2(0, 0); // two backfilled drives differ in quality, so a held thrust is a net torque
for (var step = 0; step < 600 && abs(player.TurnRate) > 0; step++) arena.Update(ClockFrame);
player.Direction = normalize(float2(3, -4));
arena.Update(ClockFrame);
Assert.Equal(0f, player.TurnRate);
}
[Fact]
public void DrawAheadIsTheStateAtZeroLead()
{
var (arena, player) = LaunchDuel();
for (var step = 0; step < 120; step++) arena.Update(ClockFrame);
var before = Snapshot(arena, new List<string>());
var zero = DrawAhead.Position(player, 0);
Assert.Equal(player.Position.x, zero.x);
Assert.Equal(player.Position.y, zero.y);
Assert.Equal(player.Position.z, zero.z);
var rotation = DrawAhead.Rotation(player, 0);
Assert.Equal(1f, abs(rotation.x * player.Rotation.x + rotation.y * player.Rotation.y + rotation.z * player.Rotation.z + rotation.w * player.Rotation.w), 5);
const float lead = .007f;
var ahead = DrawAhead.Position(player, lead);
Assert.Equal(player.Position.x + player.Velocity.x * lead, ahead.x, 6);
Assert.Equal(player.Position.y, ahead.y);
Assert.Equal(player.Position.z + player.Velocity.y * lead, ahead.z, 6);
Assert.Equal(before, Snapshot(arena, new List<string>()));
}
// A pose the step scripts (the wormhole animation) is drawn where the step put it, at any lead.
[Fact]
public void ScriptedPosesAreNotDrawnAhead()
{
var (arena, player) = LaunchDuel();
for (var step = 0; step < 120; step++) arena.Update(ClockFrame);
player.EnterWormhole(player.Position.xz + float2(50, 0));
arena.Update(ClockFrame);
Assert.True(player.WormholeAnimationInProgress);
Assert.True(length(player.Velocity) > .01f, "the ship carries speed into the animation");
var position = DrawAhead.Position(player, ClockFrame);
Assert.Equal(player.Position.x, position.x);
Assert.Equal(player.Position.y, position.y);
Assert.Equal(player.Position.z, position.z);
var rotation = DrawAhead.Rotation(player, ClockFrame);
Assert.Equal(player.Rotation.x, rotation.x);
Assert.Equal(player.Rotation.y, rotation.y);
Assert.Equal(player.Rotation.z, rotation.z);
Assert.Equal(player.Rotation.w, rotation.w);
}
// The turn a presenter draws ahead is the turn the next step makes: a ship held in a steady turn, drawn one whole
// step ahead of the pose it was last given, is where the sim puts that pose next.
[Fact]
public void DrawnRotationFollowsTheTurn()
{
var (arena, player) = LaunchDuel();
player.Turn = 1f;
for (var step = 0; step < 300; step++) arena.Update(ClockFrame);
var rate = player.TurnRate;
Assert.True(abs(rate) > .05f, "the ship is turning");
var drawn = DrawAhead.Rotation(player, ClockFrame);
arena.Update(ClockFrame);
Assert.True(abs(player.TurnRate - rate) < 1e-3f * abs(rate), "the turn is steady");
var next = player.Rotation;
var error = 2 * acos(min(1f, abs(drawn.x * next.x + drawn.y * next.y + drawn.z * next.z + drawn.w * next.w)));
var turn = abs(rate * ClockFrame);
Assert.True(turn > .005f, "the step turns the ship enough to tell its sense");
Assert.True(error < .2f * turn, $"drawn one step ahead is where the sim puts the pose next (off by {error} of a {turn} turn)");
}
// Thrusters turn the same way: a Longinus held in a turn, settled, turns each step by exactly its TurnRate.
[Fact]
public void ThrustersReportTheirTurn()
{
var (_, longinus, _) = EvFleet();
EvSettle(longinus);
longinus.Turn = 1f;
var turned = 0;
for (var step = 0; step < 120; step++)
{
var before = longinus.Direction;
longinus.Update(ClockFrame);
Assert.InRange(abs(abs(SignedTurn(before, longinus.Direction)) - abs(longinus.TurnRate * ClockFrame)), 0f, 1e-6f);
if (abs(longinus.TurnRate) > 1e-4f)
{
turned++;
Assert.True(longinus.TurnRate > 0 == dot(longinus.Direction, before.Rotate(ItemRotation.Clockwise)) > 0);
}
}
Assert.True(turned > 30, "the thrusters turned the ship");
}
// The draw-ahead turn on a pose that is not flat: the up axis stays the pose's up, and the forward axis swings about
// it by the angle (Rodrigues' rotation, written out apart from DrawAhead's quaternion product).
[Fact]
public void TheDrawnTurnIsAboutThePosesOwnUp()
{
var up = normalize(float3(.3f, .8f, -.2f));
var pose = quaternion.LookRotation(normalize(cross(float3(1, 0, .4f), up)), up);
const float angle = .6f;
var turned = DrawAhead.Turned(pose, angle);
float3 Axis(quaternion q, float3 v)
{
var u = float3(q.x, q.y, q.z);
return v + 2 * (q.w * cross(u, v) + cross(u, cross(u, v)));
}
float3 Close(float3 a, float3 b) => float3(abs(a.x - b.x), abs(a.y - b.y), abs(a.z - b.z));
var forward = Axis(pose, float3(0, 0, 1));
var rodrigues = forward * cos(angle) + cross(Axis(pose, float3(0, 1, 0)), forward) * sin(angle);
var upBefore = Axis(pose, float3(0, 1, 0));
var tolerance = float3(1e-5f, 1e-5f, 1e-5f);
Assert.True(all(Close(Axis(turned, float3(0, 1, 0)), upBefore) < tolerance), "the pose's up does not move");
Assert.True(all(Close(Axis(turned, float3(0, 0, 1)), rodrigues) < tolerance), "the forward axis swings about it by the angle");
}
}

View file

@ -17,6 +17,8 @@ public sealed class StatResolverTests : IDisposable
private string Catalog => Path.Combine(_root, "Aetheria.cc");
private static readonly int2 HardpointCell = new int2(0, 0);
private static readonly int2 SecondHardpointCell = new int2(1, 0);
private static readonly int2 FirstGunCell = new int2(2, 0);
private static readonly int2 SecondGunCell = new int2(0, 1);
public StatResolverTests() => Directory.CreateDirectory(_root);
public void Dispose() => Directory.Delete(_root, true);
@ -40,7 +42,9 @@ public sealed class StatResolverTests : IDisposable
Hardpoints =
{
new HardpointData { Type = HardpointType.Sensors, Position = HardpointCell, Shape = new Shape() },
new HardpointData { Type = HardpointType.Sensors, Position = SecondHardpointCell, Shape = new Shape() }
new HardpointData { Type = HardpointType.Sensors, Position = SecondHardpointCell, Shape = new Shape() },
new HardpointData { Type = HardpointType.Sensors, Position = FirstGunCell, Shape = new Shape() },
new HardpointData { Type = HardpointType.Sensors, Position = SecondGunCell, Shape = new Shape() }
}
});
cache.Upsert(new GearData { Name = "Battery", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 10, Behaviors = { capacitor } });
@ -72,6 +76,61 @@ public sealed class StatResolverTests : IDisposable
return ship;
}
// A modifier's StatReference names a behaviour type, and WeaponData.Damage is declared once on the abstract
// base. A ship carrying an AutoWeapon gun and a ChargedWeapon gun and a Booster whose modifier aims at
// `target` is the real case; the two tests below read each gun's resolved Damage through EquippedItem.Evaluate.
private (CultCache Cache, EquippedItem Auto, EquippedItem Charged, PerformanceStat AutoDamage, PerformanceStat ChargedDamage)
BuildGunShipWithBooster(string target)
{
var autoDamage = new PerformanceStat { Min = 10, Max = 10 };
var chargedDamage = new PerformanceStat { Min = 10, Max = 10 };
var modifier = new StatModifierData
{
Stat = new StatReference { Target = target, Stat = nameof(WeaponData.Damage) },
Modifier = new PerformanceStat { Min = 3, Max = 3 },
Type = StatModifierType.Multiplier
};
var cache = OpenCatalog(new CapacitorData { Capacity = new PerformanceStat { Min = 1, Max = 1 } }, modifier);
cache.Upsert(new GearData { Name = "AutoGun", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 10, Behaviors = { new AutoWeaponData { Damage = autoDamage } } });
cache.Upsert(new GearData { Name = "ChargedGun", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 10, Behaviors = { new ChargedWeaponData { Damage = chargedDamage } } });
cache.FlushAsync().Wait();
var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { });
var ship = BuildActivatedShip(cache, items, withBooster: true);
ship.Deactivate(); // TryEquip refuses while deployed
Assert.True(ship.TryEquip(Mint(cache, items, cache.GetByName<GearData>("AutoGun")), FirstGunCell));
Assert.True(ship.TryEquip(Mint(cache, items, cache.GetByName<GearData>("ChargedGun")), SecondGunCell));
// Re-activate so the booster's Initialize sees the guns it did not see at the first activation.
ship.Activate();
var booster = ship.Equipment.Single(e => e.Data.Name == "Booster");
var behavior = booster.GetBehavior<StatModifier>();
behavior.Execute(0f);
behavior.Update(0f);
return (cache, ship.Equipment.Single(e => e.Data.Name == "AutoGun"), ship.Equipment.Single(e => e.Data.Name == "ChargedGun"), autoDamage, chargedDamage);
}
// A modifier aimed at the abstract base reaches every subtype carried. Mutation: restore exact-type matching
// (`bd.GetType() == targetType`) in either behaviour filter of StatModifier.TargetsOf and both guns read 10.
[Fact]
public void AModifierOnABaseTypeReachesEverySubtype()
{
var (cache, auto, charged, autoDamage, chargedDamage) = BuildGunShipWithBooster(nameof(WeaponData));
using var _ = cache;
Assert.Equal(30f, auto.Evaluate(autoDamage), 3);
Assert.Equal(30f, charged.Evaluate(chargedDamage), 3);
}
// A modifier aimed at one concrete subtype leaves its sibling alone: assignability is downward only.
[Fact]
public void AModifierOnAConcreteTypeReachesOnlyIt()
{
var (cache, auto, charged, autoDamage, chargedDamage) = BuildGunShipWithBooster(nameof(AutoWeaponData));
using var _ = cache;
Assert.Equal(30f, auto.Evaluate(autoDamage), 3);
Assert.Equal(10f, charged.Evaluate(chargedDamage), 3);
}
// §1.1's authority claim, structurally: "StatResolver, one per Entity, constructed with it." Mutation: make
// Entity.Resolver a static field -- every entity then shares one resolver, and NotSame goes red.
[Fact]
@ -382,7 +441,7 @@ public sealed class StatResolverTests : IDisposable
for (var i = 0; i < 20; i++)
{
var lot = items.Lots.Add(new Lot { Design = cache.RefOf<ItemData>(boosterData), Origin = new Attributed(), Quality = .5f, Roles = new List<RoleFill>() });
var consumableItem = new ConsumableItem { Data = cache.RefOf<ItemData>(boosterData), Lot = lot };
var consumableItem = Assert.IsType<ConsumableItem>(items.CreateInstance(lot));
ship.ActivateConsumable(consumableItem);
// Duration is 0.01s; one 1-second tick expires it and drives Entity.Update's expiry branch.
@ -393,4 +452,132 @@ public sealed class StatResolverTests : IDisposable
Assert.Equal(baselineCache, resolver.CacheEntryCount);
Assert.Equal(baselineModifiers, resolver.ModifierEntryCount);
}
// Ruling boost-stacking-multiply: every multiplier on one stat multiplies, with no stacking penalty, and every
// constant adds. The rig is the production path end to end: gear carrying StatModifierData is equipped on a ship
// beside a thruster, a consumable is minted through ItemManager.CreateInstance and activated on the ship, and
// the resolved value is read through EquippedItem.Evaluate. Nothing here calls AttachModifier by hand.
private sealed class ThrustRig
{
public CultCache Cache;
public ItemManager Items;
public Ship Ship;
public EquippedItem Engine;
public PerformanceStat Thrust;
public Func<ConsumableItem> Consumable; // null when the rig was built without one
public float Resolved => Engine.Evaluate(Thrust);
// Two ticks: the first executes every modifier, the second applies it (StatModifier.Update).
public void Tick(float dt) { for (var i = 0; i < 2; i++) Ship.Update(dt); }
}
private static StatModifierData ThrustModifier(StatModifierType type, float value) => new StatModifierData
{
Stat = new StatReference { Target = nameof(ThrusterData), Stat = nameof(ThrusterData.Thrust) },
Modifier = new PerformanceStat { Min = value, Max = value },
Type = type
};
// A Thrust-10 thruster and one gear per entry of `gear`, in that attach order, plus (optionally) a consumable
// whose single modifier is `consumable`. The hull has four hardpoints, so at most three gear modifiers.
private ThrustRig BuildThrustRig((StatModifierType Type, float Value)[] gear, (StatModifierType Type, float Value)? consumable = null)
{
var thrust = new PerformanceStat { Min = 10, Max = 10 };
var cache = AetheriaStores.Open(Catalog, catalogWritable: true);
cache.Upsert(new TestCatalogGlobal { Name = "Temperament" });
var hullShape = new Shape(3, 3);
foreach (var cell in hullShape.AllCoordinates) hullShape[cell] = true;
var cells = new[] { HardpointCell, SecondHardpointCell, FirstGunCell, SecondGunCell };
cache.Upsert(new HullData
{
Name = "Skiff", HullType = HullType.Ship, Shape = hullShape, Durability = 10,
Hardpoints = cells.Select(c => new HardpointData { Type = HardpointType.Sensors, Position = c, Shape = new Shape() }).ToList()
});
cache.Upsert(new GearData { Name = "Engine", Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 10, Behaviors = { new ThrusterData { Thrust = thrust } } });
for (var i = 0; i < gear.Length; i++)
cache.Upsert(new GearData { Name = "Boost" + i, Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 10, Behaviors = { ThrustModifier(gear[i].Type, gear[i].Value) } });
if (consumable != null)
cache.Upsert(new ConsumableItemData { Name = "Stim", Duration = 1f, Shape = new Shape(), Behaviors = { ThrustModifier(consumable.Value.Type, consumable.Value.Value) } });
cache.FlushAsync().Wait();
var items = new ItemManager(cache, new ProvenanceLedger(), Settings(), _ => { });
var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null);
var ship = new Ship(items, zone, Mint(cache, items, cache.GetByName<HullData>("Skiff")), new EntitySettings());
Assert.True(ship.TryEquip(Mint(cache, items, cache.GetByName<GearData>("Engine")), cells[0]));
for (var i = 0; i < gear.Length; i++)
{
// A test gear has no authored heat response, so its thermal performance reads 0 and it would sit offline;
// the override is the entity's own switch for keeping a part running, not a stand-in for the rule.
var boost = Mint(cache, items, cache.GetByName<GearData>("Boost" + i));
boost.OverrideShutdown = true;
Assert.True(ship.TryEquip(boost, cells[i + 1]));
}
ship.OverrideShutdown = true;
zone.Entities.Add(ship);
ship.Activate();
Func<ConsumableItem> mint = null;
if (consumable != null)
{
var design = cache.GetByName<ConsumableItemData>("Stim");
mint = () => Assert.IsType<ConsumableItem>(items.CreateInstance(items.Lots.Add(
new Lot { Design = cache.RefOf<ItemData>(design), Origin = new Attributed(), Quality = .5f, Roles = new List<RoleFill>() })));
}
return new ThrustRig { Cache = cache, Items = items, Ship = ship, Engine = ship.Equipment.Single(e => e.Data.Name == "Engine"), Thrust = thrust, Consumable = mint };
}
// Two scales multiply: x1.2 and x1.25 on one stat resolve to base x1.5, and x1.1, x1.2, x1.25 to base x1.65,
// whatever order they attach in. Mutations at StatResolver.ScaleModifier: a sum of excesses reads 14.5 and
// 15.5, the strongest-only rule 12.5, a diminishing curve 14.67, and `result *= value * value` or
// `result *= value + 0.01f` (functions of the scale itself) read off 15.
[Theory]
[InlineData(new[] { 1.2f, 1.25f }, 15f)]
[InlineData(new[] { 1.25f, 1.2f }, 15f)]
[InlineData(new[] { 1.1f, 1.2f, 1.25f }, 16.5f)]
[InlineData(new[] { 1.25f, 1.1f, 1.2f }, 16.5f)]
[InlineData(new[] { 1.2f, 1.25f, 1.1f }, 16.5f)]
public void TwoScalesOnOneStatMultiply(float[] scales, float expected)
{
var rig = BuildThrustRig(scales.Select(s => (StatModifierType.Multiplier, s)).ToArray());
using var _ = rig.Cache;
Assert.Equal(10f, rig.Resolved, 3); // modifiers not yet applied
rig.Tick(.1f);
Assert.Equal(expected, rig.Resolved, 3);
}
// A gear modifier and a consumable modifier on one drive's Thrust share one entry and multiply: x1.2 gear and
// x1.5 consumable read x1.8, and when the consumable expires only the gear's x1.2 remains.
[Fact]
public void AConsumableBoostMultipliesWithGear()
{
var rig = BuildThrustRig(new[] { (StatModifierType.Multiplier, 1.2f) }, (StatModifierType.Multiplier, 1.5f));
using var _ = rig.Cache;
rig.Tick(.1f);
Assert.Equal(12f, rig.Resolved, 3); // gear alone
rig.Ship.ActivateConsumable(rig.Consumable());
rig.Tick(.1f); // 0.8s of the 1s remain
Assert.Equal(18f, rig.Resolved, 3);
rig.Tick(.5f); // the consumable's duration has run out
Assert.Equal(12f, rig.Resolved, 3);
}
// Constants add, and compose with scales through PerformanceStat.Evaluate: (base x scale) + constant. +3 and +4
// resolve as a constant of 7; with a x2 scale beside them the value is Evaluate's for scale 2 and constant 7,
// (10 x 2) + 7. Mutations at ConstantModifier: `result = Math.Max(result, value)` reads constant 4;
// `result += value * 2` reads constant 14.
[Theory]
[InlineData(new[] { 3f, 4f }, new float[0], 1f, 7f, 17f)]
[InlineData(new[] { 3f, 4f }, new[] { 2f }, 2f, 7f, 27f)]
public void TwoConstantsOnOneStatAdd(float[] constants, float[] scales, float expectedScale, float expectedConstant, float expected)
{
var rig = BuildThrustRig(constants.Select(c => (StatModifierType.Constant, c))
.Concat(scales.Select(s => (StatModifierType.Multiplier, s))).ToArray());
using var _ = rig.Cache;
rig.Tick(.1f);
Assert.Equal(expectedScale, rig.Ship.Resolver.ScaleModifier(rig.Engine, rig.Thrust), 3);
Assert.Equal(expectedConstant, rig.Ship.Resolver.ConstantModifier(rig.Engine, rig.Thrust), 3);
Assert.Equal(expected, rig.Resolved, 3);
}
}

View file

@ -241,7 +241,7 @@ public sealed class SteeringTests
}
// The turn bound has one owner, the actuators: Ship.Update hands Turn to them unclamped, Thruster.Axis saturates to
// 0..1 and AetherDrive.Axis clamps to -1..1. A Turn of 3 therefore rotates the hull as a Turn of 1.
// 0..1. A Turn of 3 therefore rotates the hull as a Turn of 1.
[Fact]
public void TheActuatorsBoundATurnBeyondOne()
{
@ -276,13 +276,6 @@ public sealed class SteeringTests
thruster.Axis = -3f;
Assert.Equal(0f, thruster.Axis);
}
// Axis is a pure property; no catalog hull carries a drive, so the instance is made without its item.
var drive = (AetherDrive)System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(typeof(AetherDrive));
drive.Axis = float3(3f, -3f, 3f);
Assert.Equal(float3(1f, -1f, 1f), drive.Axis);
drive.Axis = float3(0f, 0f, -3f);
Assert.Equal(-1f, drive.Axis.z);
}
// The size of a turn, computed from the hull and not read back from the code under test: each rotation thruster

View file

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

View file

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

View file

@ -33,7 +33,7 @@ UNITY_EXE = r"C:\Program Files\Unity\Hub\Editor\6000.3.24f1\Editor\Unity.exe"
ITEM_DATA_CS = REPO_ROOT / "Assets" / "Scripts" / "ServerShared" / "ItemData.cs"
DIRECTORY_BUILD_PROPS = REPO_ROOT / "Directory.Build.props"
# A known-good record to mutate: HullData "LonginusX", whose Prefab already resolves (see the Cut 2
# A known-good record to mutate: HullData "Longinus", whose Prefab already resolves (see the Cut 2
# migration report). Texture2D guid is its own Schematic (schema_Longinus.png), still a real,
# addressable asset, just the wrong type for Prefab (which wants a GameObject+EntityInstance).
TEXTURE_GUID = "51702555e534a7a4fb39eb105b80bbaf"
@ -109,7 +109,7 @@ using System.Linq;
using System.Reflection;
using GameCult.Caching;
// Scratch-only (not landed): sets HullData "LonginusX".Prefab to an arbitrary string in a copy of
// Scratch-only (not landed): sets HullData "Longinus".Prefab to an arbitrary string in a copy of
// the catalog, for tests/mutation_tests.py to feed to EngineAssetCheck and prove it fails.
internal static class Program
{
@ -122,12 +122,12 @@ internal static class Program
{
var stored = cache.AllStoredDocuments.First(s =>
s.Descriptor.DocumentType.Name == "HullData" &&
(string)s.Descriptor.DocumentType.GetField("Name").GetValue(s.Document) == "LonginusX");
(string)s.Descriptor.DocumentType.GetField("Name").GetValue(s.Document) == "Longinus");
var field = stored.Descriptor.DocumentType.GetField("Prefab", BindingFlags.Public | BindingFlags.Instance);
field.SetValue(stored.Document, newValue);
cache.UpsertAsync(stored.Descriptor.DocumentType, stored.Document, stored.Key).Wait();
cache.FlushAllBackingStores();
Console.WriteLine($"Set HullData \"LonginusX\".Prefab = \"{newValue}\"");
Console.WriteLine($"Set HullData \"Longinus\".Prefab = \"{newValue}\"");
return 0;
}
finally
@ -217,11 +217,11 @@ def main():
if code == 0:
failures.append(f"{name}: EngineAssetCheck exited 0; the mutation was not caught")
continue
if "LonginusX" not in text:
failures.append(f"{name}: failure did not name the record (LonginusX)")
if "Longinus" not in text:
failures.append(f"{name}: failure did not name the record (Longinus)")
continue
assert_contains(text, expect, name)
print(f"OK: caught, exit {code}, named LonginusX, mentioned {expect!r}")
print(f"OK: caught, exit {code}, named Longinus, mentioned {expect!r}")
except SystemExit as exc:
failures.append(f"{name}: {exc}")
finally: