Merge origin/master (da6fe033) into faction-play-1

Combat.cs: master's lazy optimum-range owner kept, the OptimumRange accessor beside it. FireControlPerWeaponTests: the exponent test runs the first Update before reading the optimum (master derives it there).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-16 22:01:56 +02:00
commit 2ff48d0b45
10 changed files with 800 additions and 12 deletions

View file

@ -0,0 +1,493 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using CultMath;
using GameCult.Caching;
using Xunit;
using static CultMath.math;
using float2 = CultMath.float2;
using float3 = CultMath.float3;
using int2 = CultMath.int2;
// AI pilots use consumables (aetheria-release cut consumable-ai r3; rulings sensor-stat-set item 4,
// lock-warning-strength, launcher-lock-solution-quality): CombatState vents when ONE Track paint in the ship's own
// IncomingPaints passes .5 and otherwise overdrives to close a target farther than twice its optimum range while
// heading within 15 degrees of it. It reads only its own ship's senses. A consumable is chosen by what its behaviours
// are, never by name, so the vent design is named "Overdrive" and the overdrive design "Coolant".
//
// The agent's one gun has Range 1000 and EffectiveRange 500 with nothing at maximum range, so its optimum range is
// about 500 while its shortest and longest gun range are both 1000: a threshold taken from either gun range is wrong
// and these tests can tell. The optimum is read by reflection, as FireControlTests does, and the thresholds are
// authored against it.
public sealed class ConsumableAiTests : IDisposable
{
private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-consumable-ai-" + Guid.NewGuid().ToString("N"));
private readonly List<CultCache> _caches = new List<CultCache>();
private static readonly int2 HardpointCell = new int2(0, 0);
private static readonly int2 SecondHardpointCell = new int2(2, 2);
private static readonly int2 HoldCell = new int2(1, 1);
private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic;
public ConsumableAiTests() => Directory.CreateDirectory(_root);
public void Dispose()
{
foreach (var c in _caches) c.Dispose();
Directory.Delete(_root, true);
}
private static PerformanceStat Const(float v) => new PerformanceStat { Min = v, Max = v };
private sealed class Scene
{
public ItemManager Items;
public Zone Zone;
public Ship Agent, Prey, Locker;
public EquippedCargoBay Hold;
public ConsumableItemData Vent, Overdrive, Decoy, StackableVent;
public GearData HeavyGun;
public CultRecordRef<Faction> Maker;
public float Optimum;
public void Store(ConsumableItemData design) =>
Assert.True(Hold.TryStore((ItemInstance) Items.CreateInstance(Items.CreateLot(design, Maker, .5f))));
public bool Active(ConsumableItemData design) => Agent.FindActiveConsumable(design) != null;
public int Carried => Hold.Cargo.Keys.Count(i => i is ConsumableItem);
public object State => typeof(Agent).GetField("_currentState", Private).GetValue(Zone.Agents.Single());
public void AssertInCombat() => Assert.True(State is CombatState, $"the agent is in {State?.GetType().Name}");
// The target at `distance` and `degrees` off north, the agent at the origin with its hull `hullDegrees` off north.
public void Place(float distance, float degrees, float hullDegrees = 0f)
{
Agent.Position = float3.zero;
var h = hullDegrees * 0.0174533f;
Agent.Direction = float2(sin(h), cos(h));
var a = degrees * 0.0174533f;
Prey.Position = float3(sin(a) * distance, 0, cos(a) * distance);
}
// Paints of the locker's launcher reaching the agent as the zone publishes them, then one tick in which the
// agent decides. The agent reads them before the zone republishes (agents update, then PublishInbox).
public void Tick(params (PaintMode mode, float strength)[] paints)
{
foreach (var (mode, strength) in paints)
Agent.ReceivePaint(Locker, Locker.Equipment.Single(i => i.Behaviors.Any(b => b is LockWeapon)), mode, strength);
Agent.PublishInbox();
Zone.Update(.05f);
}
}
private static GearData GunData(float effective, string name = "Gun", float damage = 10f) => new GearData
{
Name = name, Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 1,
MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000,
Behaviors =
{
new InstantWeaponData
{
Damage = Const(damage), Range = Const(1000), MinRange = Const(0), Velocity = Const(0),
Spread = Const(0), DamageSpread = Const(0), Penetration = Const(0), Count = Const(1),
BurstTime = Const(0), Cooldown = Const(1),
EffectiveRange = Const(effective), DamageAtMaxRange = 0f
}
}
};
private Scene Build(bool carryVent = false, bool carryOverdrive = false, bool carryDecoy = false, int stackableVents = 0, float effective = 500f)
{
var cache = AetheriaStores.Open(Path.Combine(_root, Guid.NewGuid().ToString("N") + ".cc"), catalogWritable: true);
_caches.Add(cache);
cache.Upsert(new VerseGrammar { Revision = 1 });
cache.Upsert(new Faction { Name = "Maker", ShortName = "MKR" });
var hullShape = new Shape(3, 3);
foreach (var cell in hullShape.AllCoordinates) hullShape[cell] = true;
cache.Upsert(new HullData
{
Name = "Skiff", HullType = HullType.Ship, Shape = hullShape, Durability = 1000000, Mass = 1000,
Hardpoints =
{
new HardpointData { Type = HardpointType.Sensors, Position = HardpointCell, Shape = new Shape() },
new HardpointData { Type = HardpointType.Sensors, Position = SecondHardpointCell, Shape = new Shape() }
}
});
cache.Upsert(GunData(effective));
cache.Upsert(GunData(800f, "HeavyGun", damage: 1000f));
cache.Upsert(LockWarningTests.Launcher("Launcher", lockSpeed: .6f, sensorImpact: 1, lockAngle: 30, directionImpact: 1));
var interior = new Shape(4, 1);
foreach (var cell in interior.AllCoordinates) interior[cell] = true;
cache.Upsert(new CargoBayData { Name = "Hold", Shape = new Shape(), InteriorShape = interior, Durability = 10 });
// A vent named like the other kind, an overdrive named like it, a decoy, and a stackable vent.
cache.Upsert(new ConsumableItemData
{
Name = "Overdrive", Duration = 100f, Shape = new Shape(),
Behaviors = { new VapourDumpData { Radius = Const(20), Opacity = Const(.9f), Lifetime = Const(100) } }
});
cache.Upsert(new ConsumableItemData { Name = "Coolant", Duration = 100f, Shape = new Shape(), Behaviors = { new ThrottleLockData() } });
cache.Upsert(new ConsumableItemData { Name = "Flare", Duration = 1f, Shape = new Shape() });
cache.Upsert(new ConsumableItemData
{
Name = "StackVent", Duration = 100f, Stackable = true, Shape = new Shape(),
Behaviors = { new VapourDumpData { Radius = Const(20), Opacity = Const(.9f), Lifetime = Const(100) } }
});
cache.FlushAsync().Wait();
var settings = RunSaveTests.TestSettings();
settings.TargetDetectionInfoThreshold = .1f;
settings.TargetGearInfoThreshold = .8f;
settings.FiringArc = 170;
settings.CommitHorizon = .5f;
settings.SchematicCellSize = 1f;
settings.UnaidedAccuracy = .05f;
settings.UnaidedTracking = 10f;
settings.UnaidedPrecision = 2f;
settings.AgentMinHitProbability = 0f;
settings.BeamResolveInterval = .1f;
var items = new ItemManager(cache, new ProvenanceLedger(), settings, _ => { });
var maker = cache.RefOf(cache.GetByName<Faction>("Maker"));
EquippableItem Make<T>(string name) where T : CraftedItemData =>
(EquippableItem) items.CreateInstance(items.CreateLot(cache.GetByName<T>(name), maker, .5f));
var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null);
Ship NewShip(string gear)
{
var ship = new Ship(items, zone, Make<HullData>("Skiff"), new EntitySettings())
{ Faction = new Faction { Name = "F" + Guid.NewGuid().ToString("N") } };
if (gear != null) Assert.True(ship.TryEquip(Make<GearData>(gear), HardpointCell));
return ship;
}
var scene = new Scene
{
Items = items, Zone = zone, Maker = maker,
Vent = cache.GetByName<ConsumableItemData>("Overdrive"),
Overdrive = cache.GetByName<ConsumableItemData>("Coolant"),
Decoy = cache.GetByName<ConsumableItemData>("Flare"),
StackableVent = cache.GetByName<ConsumableItemData>("StackVent"),
HeavyGun = cache.GetByName<GearData>("HeavyGun"),
Agent = NewShip("Gun"), Prey = NewShip(null), Locker = NewShip("Launcher")
};
Assert.True(scene.Agent.TryEquip(Make<CargoBayData>("Hold"), HoldCell));
scene.Hold = scene.Agent.CargoBays.Single();
// The agent joins as the zone admits a piloted ship (its Minion and CombatState come from production); the
// locker is a gun ship nobody pilots.
zone.Admit(scene.Agent, piloted: true);
zone.Agents.Single().Task = null; // the test zone has no orbits to patrol; the Minion and its CombatState are production's
zone.Admit(scene.Prey, piloted: false);
zone.Admit(scene.Locker, piloted: false);
zone.Update(0f); // brings the gear online
scene.Agent.SetIff(scene.Prey, true);
scene.Agent.EntityInfoGathered[scene.Prey] = 1f;
scene.Agent.SetTarget(scene.Prey);
scene.Locker.Position = float3(0, 0, -40);
scene.Place(100f, 0f);
zone.Update(.05f);
zone.Update(.05f);
scene.AssertInCombat();
// Read, never re-sampled: the optimum is whatever production derived for the spawned ship.
scene.Optimum = (float) typeof(CombatState).GetField("_optimumRange", Private).GetValue(scene.State);
Assert.InRange(scene.Optimum, effective - 1000f / 32f, effective + 1000f / 32f);
if (carryVent) scene.Store(scene.Vent);
if (carryOverdrive) scene.Store(scene.Overdrive);
if (carryDecoy) scene.Store(scene.Decoy);
for (var i = 0; i < stackableVents; i++) scene.Store(scene.StackableVent);
Assert.True(scene.Carried == (carryVent ? 1 : 0) + (carryOverdrive ? 1 : 0) + (carryDecoy ? 1 : 0) + stackableVents,
$"carried {scene.Carried}, cargo entries {scene.Hold.Cargo.Count}: {string.Join(",", scene.Hold.Cargo.Keys.Select(k => k.GetType().Name))}");
return scene;
}
[Theory]
[InlineData(.4f, false)]
[InlineData(.49f, false)]
[InlineData(.5f, false)]
[InlineData(.51f, true)]
[InlineData(.6f, true)]
public void AnAgentVentsWhenLocked(float strength, bool vents)
{
var s = Build(carryVent: true, carryOverdrive: true);
s.AssertInCombat();
s.Tick((PaintMode.Track, strength));
Assert.Equal(vents, s.Active(s.Vent));
Assert.Equal(vents ? 1 : 2, s.Carried);
Assert.False(s.Active(s.Overdrive));
}
[Fact]
public void AnAgentVentsOnOneTrackPaintOnItself()
{
var s = Build(carryVent: true);
s.AssertInCombat();
s.Tick((PaintMode.Track, .3f), (PaintMode.Track, .3f)); // two weak locks never sum
s.Tick((PaintMode.Search, .9f));
s.Tick((PaintMode.Scan, .9f));
Assert.False(s.Active(s.Vent));
Assert.Equal(1, s.Carried);
// The locker is a ship the agent has no information on, and one strong Track paint on it is enough.
s.Tick((PaintMode.Track, .9f));
Assert.True(s.Active(s.Vent));
Assert.Equal(0, s.Carried);
}
// The production path: a real launcher on a ship the agent has never sensed locks it through zone ticks, and the
// agent vents once the paint is published, with its own senses as the only input.
[Fact]
public void AnUnseenLockerThatLocksTheAgentMakesItVent()
{
var s = Build(carryVent: true);
s.AssertInCombat();
s.Locker.SetIff(s.Agent, true);
s.Locker.EntityInfoGathered[s.Agent] = 1f;
s.Locker.SetTarget(s.Agent);
for (var i = 0; i < 4 && !s.Active(s.Vent); i++)
{
s.Place(100f, 0f);
s.Locker.Aim = normalize(s.Agent.Position - s.Locker.Position);
s.Zone.Update(1f);
}
Assert.True(s.Active(s.Vent));
Assert.Equal(0, s.Carried);
Assert.Equal(s.Prey, s.Agent.Target.Value.Entity);
}
[Fact]
public void AnAgentThatIsLockedVentsInsteadOfOverdriving()
{
var s = Build(carryVent: true, carryOverdrive: true);
s.AssertInCombat();
s.Place(3 * s.Optimum, 0f);
s.Tick((PaintMode.Track, .6f));
Assert.True(s.Active(s.Vent));
Assert.False(s.Active(s.Overdrive));
Assert.Equal(1, s.Carried);
}
// Two guns, optimums about 300 and 700: the threshold is twice the optimum the ship derived, so no constant, no gun
// range and no scaling of the arc by distance can sit at 2 x optimum +- 20 for both.
[Theory]
[InlineData(300f, 0f, 2f, 20f, true)]
[InlineData(300f, 14f, 2f, 20f, true)]
[InlineData(300f, 16f, 2f, 20f, false)]
[InlineData(300f, 30f, 2f, 20f, false)]
[InlineData(300f, 180f, 2f, 20f, false)]
[InlineData(300f, 0f, 2f, -20f, false)]
[InlineData(300f, 0f, 1f, 0f, false)]
[InlineData(700f, 0f, 2f, 20f, true)]
[InlineData(700f, 14f, 2f, 20f, true)]
[InlineData(700f, 16f, 2f, 20f, false)]
[InlineData(700f, 0f, 2f, -20f, false)]
[InlineData(700f, 0f, 1f, 0f, false)]
public void AnAgentOverdrivesToClose(float effective, float degrees, float optimums, float offset, bool overdrives)
{
var s = Build(carryVent: true, carryOverdrive: true, effective: effective);
s.AssertInCombat();
s.Place(optimums * s.Optimum + offset, degrees);
s.Tick();
Assert.Equal(overdrives, s.Active(s.Overdrive));
Assert.False(s.Active(s.Vent));
Assert.Equal(overdrives ? 1 : 2, s.Carried);
}
// The arc is the hull's heading against the bearing to the target; the aim always points at the target, so an
// arc taken from the aim would surge with the hull pointing away.
[Theory]
[InlineData(0f, 14f, true)]
[InlineData(0f, -14f, true)]
[InlineData(0f, 16f, false)]
[InlineData(0f, 90f, false)]
public void TheArcIsTheHullsHeadingNotTheAim(float targetDegrees, float hullDegrees, bool overdrives)
{
var s = Build(carryOverdrive: true);
s.AssertInCombat();
s.Place(3 * s.Optimum, targetDegrees, hullDegrees);
s.Tick();
Assert.Equal(overdrives, s.Active(s.Overdrive));
}
// The production path for the optimum: a ship the zone admits as piloted derives it from its gun's live stats
// before it needs it, and re-derives it when its loadout changes. The gun's effective range is 500 and the
// heavy gun's is 800, so the optimum moves with the weapons it has now.
[Fact]
public void ASpawnedShipsOptimumFollowsItsWeaponsAndNeverReadsZero()
{
var s = Build(carryOverdrive: true);
s.AssertInCombat();
Assert.InRange(s.Optimum, 500f - 1000f / 32f, 500f + 1000f / 32f);
s.Place(30f, 0f);
s.Tick();
s.Tick();
Assert.False(s.Active(s.Overdrive)); // 30 m is not "distant" against a derived optimum
Assert.Equal(1, s.Carried);
// A refit is a docked ship's act: out of the zone and inactive, then back in. The heavy gun dominates the
// damage, so with it fitted the optimum sits at its effective range, and without it at the first gun's.
void Refit(Action<Ship> fit)
{
Assert.True(s.Zone.Remove(s.Agent));
s.Agent.Deactivate();
fit(s.Agent);
s.Zone.Admit(s.Agent, piloted: false); // back in, the agent's Minion keeps its CombatState
s.Place(30f, 0f);
s.Zone.Update(.05f);
s.Zone.Update(.05f);
}
float Optimum() => (float) typeof(CombatState).GetField("_optimumRange", Private).GetValue(s.State);
EquippedItem heavy = null;
Refit(ship =>
{
var before = ship.Equipment.ToList();
Assert.True(ship.TryEquip((EquippableItem) s.Items.CreateInstance(s.Items.CreateLot(s.HeavyGun, s.Maker, .5f)), SecondHardpointCell));
heavy = ship.Equipment.Single(e => !before.Contains(e));
});
Assert.InRange(Optimum(), 800f - 1000f / 32f, 800f + 1000f / 32f);
Refit(ship => Assert.NotNull(ship.TryUnequip(heavy)));
Assert.InRange(Optimum(), 500f - 1000f / 32f, 500f + 1000f / 32f);
}
// A Search or Scan paint and a Track paint in one tick, in either order: the strongest Track paint decides.
[Theory]
[InlineData(PaintMode.Search, PaintMode.Track)]
[InlineData(PaintMode.Track, PaintMode.Search)]
[InlineData(PaintMode.Scan, PaintMode.Track)]
[InlineData(PaintMode.Track, PaintMode.Scan)]
public void AMixOfPaintsInOneTickVentsOnTheTrackPaint(PaintMode first, PaintMode second)
{
var s = Build(carryVent: true);
s.AssertInCombat();
s.Tick((first, first == PaintMode.Track ? .9f : .2f), (second, second == PaintMode.Track ? .9f : .2f));
Assert.True(s.Active(s.Vent));
Assert.Equal(0, s.Carried);
}
[Fact]
public void AMixOfWeakTrackAndStrongSearchPaintsDoesNotVent()
{
var s = Build(carryVent: true);
s.AssertInCombat();
s.Tick((PaintMode.Search, .9f), (PaintMode.Track, .3f));
s.Tick((PaintMode.Track, .3f), (PaintMode.Scan, .9f));
Assert.False(s.Active(s.Vent));
}
[Fact]
public void AnOverdriveIsNotStoppedByAWeakTrackPaint()
{
var s = Build(carryVent: true, carryOverdrive: true);
s.AssertInCombat();
s.Place(2 * s.Optimum + 20f, 0f);
s.Tick((PaintMode.Track, .4f));
Assert.True(s.Active(s.Overdrive));
Assert.False(s.Active(s.Vent));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void AnAgentWithoutConsumablesDoesNothing(bool carryDecoy)
{
var s = Build(carryDecoy: carryDecoy);
s.AssertInCombat();
s.Tick((PaintMode.Track, .9f));
s.Place(3 * s.Optimum, 0f);
s.Tick();
Assert.False(s.Active(s.Decoy));
Assert.Equal(carryDecoy ? 1 : 0, s.Carried);
}
[Fact]
public void ADeadOrDockedShipActivatesNothing()
{
var s = Build(carryVent: true, carryOverdrive: true);
s.AssertInCombat();
Assert.True(s.Zone.Remove(s.Agent)); // what death and docking do
s.Agent.Deactivate();
s.Place(3 * s.Optimum, 0f);
s.Tick();
s.Tick();
Assert.Equal(2, s.Carried);
Assert.False(s.Active(s.Vent));
Assert.False(s.Active(s.Overdrive));
Assert.False(s.Agent.TryActivateConsumable(s.Overdrive));
Assert.Equal(2, s.Carried);
}
[Fact]
public void AStackOfVentsIsSpentOneAtATime()
{
var s = Build(stackableVents: 3);
s.AssertInCombat();
s.Tick((PaintMode.Track, .6f));
s.Tick((PaintMode.Track, .6f));
s.Tick((PaintMode.Track, .6f));
Assert.True(s.Active(s.StackableVent));
Assert.Equal(2, s.Carried);
}
// The hold is per kind: a second vent design in cargo is not spent while one vent is active, and an active
// overdrive does not stop a vent.
[Fact]
public void TheHoldIsPerKindNotPerDesignAndNotPerAnyConsumable()
{
var s = Build(carryVent: true, carryOverdrive: true, stackableVents: 1);
s.AssertInCombat();
s.Place(3 * s.Optimum, 0f);
s.Tick(); // overdrive
Assert.True(s.Active(s.Overdrive));
s.Tick((PaintMode.Track, .6f));
s.Tick((PaintMode.Track, .6f));
s.Tick((PaintMode.Track, .6f));
Assert.True(s.Active(s.Overdrive));
Assert.Equal(1, new[] { s.Vent, s.StackableVent }.Count(s.Active)); // one vent, whichever design came first
Assert.Equal(1, s.Carried); // the other vent design is still in cargo
}
// The vent reads only the agent's own paints: with its target gone from VisibleEnemies (still targeted, no
// longer sensed) and the locker unseen, it still vents.
[Fact]
public void AVentDoesNotNeedAnyEnemyInSight()
{
var s = Build(carryVent: true);
s.AssertInCombat();
s.Agent.VisibleEnemies.Clear();
Assert.Equal(s.Prey, s.Agent.Target.Value.Entity);
Assert.DoesNotContain(s.Locker, s.Agent.VisibleEnemies);
s.Tick((PaintMode.Track, .9f));
Assert.Empty(s.Agent.VisibleEnemies);
Assert.True(s.Active(s.Vent));
}
}

View file

@ -750,8 +750,12 @@ public sealed class FireControlPerWeaponTests : IDisposable
public void TheDoctrinesExponentMovesTheOptimumRange()
{
var r = Build(range: 400f, decoy: true);
float Optimum(float exponent) =>
new CombatState(new Minion(r.Shooter, new RoleDoctrine { RangeExponent = exponent, MinHitProbability = .2f })).OptimumRange;
float Optimum(float exponent)
{
var combat = new CombatState(new Minion(r.Shooter, new RoleDoctrine { RangeExponent = exponent, MinHitProbability = .2f }));
combat.Update(0f); // the optimum is derived at the first Update
return combat.OptimumRange;
}
Assert.True(Optimum(1f) - Optimum(0f) > 100f);
}

View file

@ -67,7 +67,7 @@ public sealed class LockWarningTests : IDisposable
private static PerformanceStat Const(float v) => new PerformanceStat { Min = v, Max = v };
private static GearData Launcher(string name, float lockSpeed, float sensorImpact, float lockAngle, float directionImpact) => WithMunitionParts(new GearData
internal static GearData Launcher(string name, float lockSpeed, float sensorImpact, float lockAngle, float directionImpact) => WithMunitionParts(new GearData
{
Name = name, Hardpoint = HardpointType.Sensors, Shape = new Shape(), Durability = 1,
MinimumTemperature = -1000, MaximumTemperature = 1000, OptimalTemperature = 0, PlateauWidth = 2000,
@ -159,6 +159,7 @@ public sealed class LockWarningTests : IDisposable
[InlineData(1.55f, .93f)]
[InlineData(1.6f, .96f)]
[InlineData(1.65f, .99f)]
[InlineData(1.66f, .996f)]
public void StrengthIsTheLockAcrossItsWholeRange(float dt, float expectedLock)
{
var locker = NewShip(float3(0, 0, 0), "Launcher");

View file

@ -0,0 +1,200 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CultMath;
using GameCult.Caching;
using Xunit;
// Operator rulings suns-never-green and suns-never-green-edges: no generated sun colour (the body's two colour stops, its
// fog tint and its light colour) takes a hue where green dominates. The band is the Settings default, 75 to 165 degrees;
// yellow (60) and teal (170) stay allowed. Hues are recovered from the RGB the production generator wrote.
public sealed class SunsNeverGreenTests : IDisposable
{
private const float Degree = 1f / 360f;
// Hue recovered from a float RGB wobbles by a few millionths of a turn; the band is judged with this much margin.
private const float Slack = 1e-3f;
private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-sunsgreen-" + Guid.NewGuid().ToString("N"));
private int _runs;
private readonly List<CultCache> _caches = new List<CultCache>();
public SunsNeverGreenTests() => Directory.CreateDirectory(_root);
public void Dispose()
{
foreach (var cache in _caches) cache.Dispose();
Directory.Delete(_root, true);
}
[Theory]
[InlineData(76f)]
[InlineData(80f)]
[InlineData(120f)]
[InlineData(160f)]
[InlineData(164f)]
public void HuesInsideTheDefaultBandAreRefused(float degrees)
{
var settings = new ZoneGenerationSettings();
Assert.True(ColorMath.HueInBand(degrees * Degree, settings.SunHueExcludedStart, settings.SunHueExcludedEnd));
}
[Theory]
[InlineData(0f)]
[InlineData(60f)]
[InlineData(74f)]
[InlineData(166f)]
[InlineData(170f)]
[InlineData(180f)]
[InlineData(300f)]
public void YellowTealAndTheRestOfTheCircleAreAllowed(float degrees)
{
var settings = new ZoneGenerationSettings();
Assert.False(ColorMath.HueInBand(degrees * Degree, settings.SunHueExcludedStart, settings.SunHueExcludedEnd));
}
// The hues below are read back from RGB the generator wrote, so the reader must invert the writer.
[Fact]
public void ReadingHueBackFromRgbInvertsWritingIt()
{
for (var degrees = 5; degrees < 360; degrees += 5)
foreach (var value in new[] { .5f, 1f })
{
var rgb = ColorMath.HsvToRgb(new float3(degrees * Degree, .75f, value));
Assert.Equal(degrees * Degree, ColorMath.RgbToHsv(rgb).x, 4);
}
}
[Fact]
public void TheDrawMapsOntoTheWholeAllowedArcAndNothingElse()
{
var settings = new ZoneGenerationSettings();
var start = settings.SunHueExcludedStart;
var end = settings.SunHueExcludedEnd;
var low = float.MaxValue;
var high = float.MinValue;
for (var i = 0; i < 1000; i++)
{
var hue = ColorMath.HueOutsideBand(i / 1000f, start, end);
Assert.False(ColorMath.HueInBand(hue, start, end), $"draw {i}/1000 landed in the band");
// Unwrapped from the band's far edge, the allowed arc runs 165 up to 75 + 360.
var along = ColorMath.HueInBand(hue, 0f, end) ? hue + 1f : hue;
low = Math.Min(low, along);
high = Math.Max(high, along);
}
Assert.InRange(low, end, end + 1f * Degree);
Assert.InRange(high, 1f + start - 1f * Degree, 1f + start);
}
[Fact]
public void GeneratedSunsKeepEveryColourOutOfTheDefaultBand()
{
var settings = new ZoneGenerationSettings();
var suns = GenerateSuns(z => { }, out _);
Assert.True(suns.Count >= 10, $"only {suns.Count} suns generated");
foreach (var sun in suns)
foreach (var hue in Hues(sun))
Assert.False(ColorMath.HueInBand(hue, settings.SunHueExcludedStart + Slack, settings.SunHueExcludedEnd - Slack),
$"a sun colour fell in the green band (hue {hue / Degree:F1} degrees)");
}
[Fact]
public void TheBandComesFromSettingsNotFromTheGenerator()
{
// A blue band, 200 to 300 degrees: suns avoid it and now take green freely.
var suns = GenerateSuns(z =>
{
z.SunHueExcludedStart = 200f * Degree;
z.SunHueExcludedEnd = 300f * Degree;
}, out _);
Assert.True(suns.Count >= 10, $"only {suns.Count} suns generated");
var hues = suns.SelectMany(Hues).ToList();
Assert.All(hues, hue => Assert.False(ColorMath.HueInBand(hue, 200f * Degree + Slack, 300f * Degree - Slack)));
Assert.Contains(hues, hue => ColorMath.HueInBand(hue, 75f * Degree, 165f * Degree));
}
[Fact]
public void TheDrawIsUniformOverTheAllowedArc()
{
var settings = new ZoneGenerationSettings();
const int draws = 1000, bins = 10;
var counts = new int[bins];
var arc = 1f - (settings.SunHueExcludedEnd - settings.SunHueExcludedStart);
for (var i = 0; i < draws; i++)
{
var hue = ColorMath.HueOutsideBand((i + .5f) / draws, settings.SunHueExcludedStart, settings.SunHueExcludedEnd);
var along = hue - settings.SunHueExcludedEnd;
if (along < 0) along += 1f;
counts[Math.Min(bins - 1, (int)(along / arc * bins))]++;
}
Assert.All(counts, count => Assert.InRange(count, draws / bins - 1, draws / bins + 1));
}
// The body blends its two stops in RGB (Gradient Blend), so the blend is sampled, not just the stops.
[Theory]
[InlineData(75f, 165f)]
[InlineData(55f, 185f)]
[InlineData(20f, 250f)]
public void TheRampBetweenTheStopsNeverCrossesTheBand(float startDegrees, float endDegrees)
{
var suns = GenerateSuns(z =>
{
z.SunHueExcludedStart = startDegrees * Degree;
z.SunHueExcludedEnd = endDegrees * Degree;
}, out _);
Assert.True(suns.Count >= 10, $"only {suns.Count} suns generated");
foreach (var sun in suns)
{
var a = sun.Colors[0].xyz;
var b = sun.Colors[1].xyz;
for (var step = 0; step <= 40; step++)
{
var hue = ColorMath.RgbToHsv(a + (b - a) * (step / 40f)).x;
Assert.False(ColorMath.HueInBand(hue, startDegrees * Degree + Slack, endDegrees * Degree - Slack),
$"the ramp passed through the band (hue {hue / Degree:F1} degrees, step {step}/40)");
}
foreach (var colourHue in Hues(sun))
Assert.False(ColorMath.HueInBand(colourHue, startDegrees * Degree + Slack, endDegrees * Degree - Slack),
$"a sun colour fell in the band (hue {colourHue / Degree:F1} degrees)");
}
}
private static IEnumerable<float> Hues(SunData sun) =>
sun.Colors.Select(c => c.xyz)
.Concat(new[] { sun.FogTintColor, sun.LightColor })
.Select(rgb => ColorMath.RgbToHsv(rgb).x);
// Production path: Galaxy, ItemManager and ZoneGenerator.GenerateZone over the shipped ZoneSettings, as in OrbitsFromFieldTests.
private List<SunData> GenerateSuns(Action<ZoneGenerationSettings> adjust, out int zones)
{
var suns = new List<SunData>();
zones = 0;
_runs++;
for (uint seed = 1; seed <= 8; seed++)
{
var dir = Path.Combine(_root, $"galaxy{_runs}-{seed}");
Directory.CreateDirectory(dir);
var catalog = Path.Combine(dir, "Aetheria.cc");
File.Copy(TestCatalog.Repo, catalog);
var cache = new CultCache(TestCatalog.Registry());
_caches.Add(cache);
cache.AddBackingStore(new GameCult.Caching.MessagePack.SingleFileMessagePackBackingStore(catalog), AetheriaStores.CatalogTypes);
cache.AddBackingStore(new GameCult.Caching.MessagePack.SingleFileMessagePackBackingStore(Path.Combine(dir, "run.cc")), AetheriaStores.RunTypes);
var authored = AuthoredSettings.Load(RunStartTests.FindRepoRoot());
var tutorial = authored.Read<TutorialGenerationSettings>("TutorialGenerationSettings");
var galaxy = new Galaxy(tutorial, authored.Read<SectorBackgroundSettings>("TutorialBackgroundSettings"),
authored.Read<NameGeneratorSettings>("NameGeneratorSettings"), cache, new PlayerSettings(),
Directory.CreateDirectory(Path.Combine(dir, "Narrative")), _ => { }, null, seed);
var items = new ItemManager(cache, new ProvenanceLedger(), authored.Read<GameplaySettings>("GameplaySettings"), _ => { });
var zoneSettings = authored.Read<ZoneGenerationSettings>("ZoneSettings");
adjust(zoneSettings);
foreach (var zone in galaxy.Zones)
{
zones++;
var pack = ZoneGenerator.GenerateZone(items, zoneSettings, galaxy, zone, false, false);
suns.AddRange(pack.Planets.Select(p => cache.Get(p)).OfType<SunData>());
}
}
return suns;
}
}