Facility: on screen an ore rig works the rocks, off screen its recipes run by span

A rig whose run list is all raw ore works the zone's first whole rock (belt Site, then index) through Zone.Wear and FireControl.Extract, the
player's own mining, at Production.OreRate (Facility.Work); the unit's FacilityRun is left alone and a cycle begun off screen resumes
when the zone is. RegionClock calls Facility.Span, always Production.Advance, so off screen the same rig starts its recipes by the
deposit pick. Any other list, a skimmer's included, runs Advance in both. Dice for the ore a rig's wear pays: SimulationDice.RigStream.
ExtractionTests pins the pick, the per-unit weight, the gate, Barren, Cycles in a pack, the zone's deposits, the on-screen wear, the
agreement of both rates, the full-bay stop, the skimmer's spans against steps, OreRate against what Advance averages, and the batch.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
soul 2026-11-29 07:48:17 +01:00
commit 6004fbc8d8
4 changed files with 585 additions and 6 deletions

View file

@ -1,4 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using GameCult.Caching;
using MessagePack;
using Newtonsoft.Json;
@ -19,10 +22,18 @@ public class FacilityData : BehaviorData
}
// The installed facility (ruling demand-consumed-inputs-processed-by-facilities). It ticks once per zone step, from EquippedItem.Update
// while the item is active, on screen; off screen RegionClock.AdvanceInstalled calls Execute with the span the zone missed. Its recipes are the run list of its design, fixed for a run because the catalog is.
// while the item is active, on screen; off screen RegionClock.AdvanceInstalled calls Span with the span the zone missed. Its recipes are
// the run list of its design, fixed for a run because the catalog is.
//
// Two paths, by where the zone is (ruling auto-mining-is-off-screen-only). Off screen every facility advances by Production.Advance:
// an ore rig's raw recipes start by the deposit pick. On screen a run list of nothing but raw ore works the zone's rocks instead (Work),
// through Zone.Wear and FireControl.Extract, the player's own mining, at Production.OreRate, the rate Advance's pick averages to; the
// player sees the rocks break, and the unit's FacilityRun is left as the off-screen path last wrote it. Any other list, a skimmer's
// included (ruling skimmers-run-their-recipe-on-screen-for-now), runs Advance in both.
public class Facility : Behavior
{
private IReadOnlyList<RecipeData> _runList;
private bool _mines;
private EntityHold _hold;
// Why the facility advanced no further this step: derived by Advance every step, never stored on the unit.
@ -37,23 +48,76 @@ public class Facility : Behavior
public Facility(FacilityData data, EquippedItem item) : base(data, item)
{
_runList = Production.RunList(ItemManager.ItemData, Item.EquippableItem.Data.Key);
SetRunList();
}
// The run list as the catalog holds it, and whether it is all raw ore: the lists that work rocks on screen.
private void SetRunList()
{
_runList = Production.RunList(ItemManager.ItemData, Item.EquippableItem.Data.Key);
_mines = _runList.Count > 0 && _runList.All(recipe => Recipes.IsRaw(ItemManager.ItemData, recipe)
&& ItemManager.ItemData.Get(recipe.Output) is SimpleCommodityData output && FieldKinds.IsOre(ItemManager.ItemData, output));
}
// The on-screen step: one zone step.
public override bool Execute(float dt)
{
if (_mines) Work(dt);
else Advance(dt);
return true;
}
// The off-screen step: the span the zone missed, always the recipe rule.
public void Span(double seconds) => Advance(seconds);
// The rock an ore rig works, in sim time dt: the first whole rock in belt Site then index order (the order Deposits reads the
// belts in) takes the damage that owes OreRate x dt units (what FireControl.Extract pays for the damage it absorbs), and Extract pays
// the station by dice of its own stream. Barren with no whole rock or no ore the ground holds; Room, with nothing worn, when no bay
// has a cell for any of its ores. A cycle begun off screen resumes when the zone is off screen again.
private void Work(double dt)
{
_hold ??= new EntityHold(Entity);
var catalog = ItemManager.ItemData;
var zone = Entity.Zone;
var rate = Production.OreRate(catalog, _runList, _hold);
if (zone == null || !(rate > 0)) { Stall = Stall.Barren; return; }
var rock = default(ChunkId);
var found = false;
foreach (var belt in zone.AsteroidBelts.OrderBy(entry => entry.Value.Data.SiteOr(entry.Key), StringComparer.Ordinal))
{
for (var index = 0; index < belt.Value.Data.Asteroids.Length && !found; index++)
if (zone.ChunkExists(rock = new ChunkId(belt.Key, index))) found = true;
if (found) break;
}
if (!found) { Stall = Stall.Barren; return; }
var room = _runList.Any(recipe => _hold.Deposit(recipe.Output.Key) > 0f && Entity.CargoBays.Any(bay =>
bay.TryFindSpace(new SimpleCommodity { Data = new CultRecordRef<ItemData>(recipe.Output.Key), Quantity = 1 })));
if (!room) { Stall = Stall.Room; return; }
var settings = zone.Settings;
var size = ((AsteroidBeltData) zone.Planets[rock.Field]).Asteroids[rock.Index].Size;
var damage = (float) (rate * dt / settings.AsteroidYield.Evaluate(size) * settings.AsteroidHitpoints.Evaluate(size));
var place = Entity.Equipment.IndexOf(Item);
var ordinal = SimulationDice.Mix(unchecked((uint) (long) Math.Floor(zone.ExactTime * 1000))) ^ (uint) place;
FireControl.Extract(zone, rock, zone.Wear(rock, damage), Entity, SimulationDice.For(zone.DropSeed, SimulationDice.RigStream, ordinal));
Stall = Stall.None;
}
private void Advance(double seconds)
{
_hold ??= new EntityHold(Entity);
var idle = Item.EquippableItem.Run == null || Item.EquippableItem.Run.Progress <= 0;
if (idle && Stall == Stall.Inputs && _hold.Revision == _failedAt) return true;
if (idle && Stall == Stall.Inputs && _hold.Revision == _failedAt) return;
Attempts++;
// A running cycle whose recipe left the catalog or stopped running here is dropped by Advance: the list it was built from is
// stale, so it is rebuilt from the catalog before that step.
if (!idle && Production.Live(ItemManager.ItemData, Item.EquippableItem.Run.Recipe) == null)
_runList = Production.RunList(ItemManager.ItemData, Item.EquippableItem.Data.Key);
var (run, stall) = Production.Advance(ItemManager.ItemData, _runList, Item.EquippableItem.Run, dt, _hold);
SetRunList();
var (run, stall) = Production.Advance(ItemManager.ItemData, _runList, Item.EquippableItem.Run, seconds, _hold);
Item.EquippableItem.Run = run;
Stall = stall;
if (idle && stall == Stall.Inputs) _failedAt = _hold.Revision;
return true;
}
}

View file

@ -58,7 +58,10 @@ public static class RegionClock
{
if (!unit.Enabled.Value || unit.EquippableItem.IsDestroyed) continue;
foreach (var behavior in unit.Behaviors)
if (behavior is Facility || behavior is Habitation) behavior.Execute((float) seconds);
{
if (behavior is Facility facility) facility.Span(seconds);
else if (behavior is Habitation) behavior.Execute((float) seconds);
}
}
}
}

View file

@ -21,6 +21,9 @@ public static class SimulationDice
// The ore a shot's wear of rocks pays, ordinal the shot's ShotId, on the zone's DropSeed (mined ore is a drop):
// FireControl.Extract is the one reader.
public const uint OreStream = 6;
// The ore an ore rig's wear of rocks pays (Facility.Work), ordinal the zone's time and the unit's place: FireControl.Extract
// reads it as it reads OreStream.
public const uint RigStream = 7;
// 9.1 (docs/fire-control-cut.md): fmix32, MurmurHash3's 32-bit finalizer -- xor-shift, multiply,
// xor-shift, multiply, xor-shift. Diffuses a structured seed (a zone seed XORed with a small,

View file

@ -0,0 +1,509 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CultMath;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
using MessagePack;
using Xunit;
// Extraction (aetheria-living-world, cut facility-extraction; rulings auto-mining-is-off-screen-only and
// skimmers-run-their-recipe-on-screen-for-now): off screen a rig starts its raw ore recipes by the deposit pick, on screen it works the
// zone's rocks at the rate that pick averages to, and a skimmer runs its recipe in both. The fixture seats the shipped Extraction Rig
// and Volatiles Skimmer by hand on a station of its own over the booted catalog, with the first two ore recipes of the rig made short
// (Cycle 2, one unit) and a field kind that holds those two ores 3 to 1, and steps Zone.Update by SimClock.GameStep.
public sealed class ExtractionTests : IDisposable
{
private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-extraction-" + Guid.NewGuid().ToString("N"));
private readonly CultCache _cache;
private readonly CultRecordKey _oreA, _oreB;
private readonly FieldKindData _field;
private readonly FieldKindData _fieldB;
public ExtractionTests()
{
Directory.CreateDirectory(_root);
var path = Path.Combine(_root, "catalog.cc");
File.Copy(TestCatalog.Repo, path);
_cache = new CultCache(TestCatalog.Registry());
_cache.AddBackingStore(new SingleFileMessagePackBackingStore(path), AetheriaStores.CatalogTypes);
_cache.AddBackingStore(new SingleFileMessagePackBackingStore(Path.Combine(_root, "run.cc")), AetheriaStores.RunTypes);
AddHull();
var rig = Production.RunList(_cache, Design("Extraction Rig"));
_oreA = rig[0].Output.Key;
_oreB = rig[1].Output.Key;
foreach (var key in new[] { _oreA, _oreB })
{
var recipe = _cache.Get<RecipeData>(RecipeData.KeyOf(key));
recipe.Cycle = 2;
recipe.OutputCount = 1;
_cache.Upsert(typeof(RecipeData), recipe, RecipeData.KeyOf(key));
}
_field = new FieldKindData { Name = "Fix Field", CrossSection = 1f, GenerationWeight = 0f };
_field.Yields.Add(new FieldYield { Commodity = new CultRecordRef<SimpleCommodityData>(_oreA), Abundance = 3f });
_field.Yields.Add(new FieldYield { Commodity = new CultRecordRef<SimpleCommodityData>(_oreB), Abundance = 1f });
_cache.Upsert(_field);
_fieldB = new FieldKindData { Name = "Fix Field B", CrossSection = 1f, GenerationWeight = 0f };
_fieldB.Yields.Add(new FieldYield { Commodity = new CultRecordRef<SimpleCommodityData>(_oreB), Abundance = 1f });
_cache.Upsert(_fieldB);
// The shipped atmosphere is a knob of authoring: the skimmer tests read their own, 3 to 2 to 1.
var atmosphere = new AtmosphereData { Name = "Fix Atmosphere" };
foreach (var (name, abundance) in new[] { ("Methane", 3f), ("Ammonia", 2f), ("Water", 1f) })
atmosphere.Yields.Add(new FieldYield { Commodity = new CultRecordRef<SimpleCommodityData>(Good(name)), Abundance = abundance });
_cache.Upsert(typeof(AtmosphereData), atmosphere, AtmosphereData.KeyOf(Deposits.GasGiantAtmosphere));
foreach (var skimmer in Production.RunList(_cache, Design("Volatiles Skimmer")))
{
skimmer.Cycle = 2;
skimmer.OutputCount = 1;
_cache.Upsert(typeof(RecipeData), skimmer, RecipeData.KeyOf(skimmer.Output.Key));
}
}
public void Dispose()
{
_cache.Dispose();
Directory.Delete(_root, true);
}
private static Shape Solid(int width, int height)
{
var shape = new Shape(width, height);
foreach (var cell in shape.AllCoordinates) shape[cell] = true;
return shape;
}
private void AddHull()
{
_cache.Upsert(new HullData
{
Name = "Test Yard", HullType = HullType.Station, Shape = Solid(8, 8), Price = 1, Durability = 10, Mass = 1000,
Hardpoints = { new HardpointData { Type = HardpointType.Facility, Position = new int2(0, 0), Shape = Solid(2, 2), Transform = "Fa.1" } }
});
_cache.Upsert(new CargoBayData { Name = "Crate", Shape = new Shape(), InteriorShape = Solid(4, 4), Price = 20, Durability = 4 });
_cache.Upsert(new CargoBayData { Name = "Vault", Shape = new Shape(), InteriorShape = Solid(12, 12), Price = 20, Durability = 4 });
_cache.Upsert(new CargoBayData { Name = "Pocket", Shape = new Shape(), InteriorShape = Solid(1, 1), Price = 5, Durability = 4 });
_cache.Upsert(new SimpleCommodityData { Name = "Slag", Shape = new Shape(), Price = 1, MaxStack = 100 });
}
private CultRecordKey Design(string name) => _cache.RefOf<ItemData>(_cache.GetByName<GearData>(name)).Key;
private CultRecordKey Good(string name) => _cache.RefOf<ItemData>(_cache.GetByName<SimpleCommodityData>(name)).Key;
// ---- the rule over a hold of its own -------------------------------------------------------------------------------------
// A ground that holds what it is told, a ledger for units, and room unless a design is marked full.
private sealed class Ground : IProductionHold
{
public readonly Dictionary<CultRecordKey, float> Deposits = new Dictionary<CultRecordKey, float>();
public readonly Dictionary<CultRecordKey, int> Units = new Dictionary<CultRecordKey, int>();
public readonly HashSet<CultRecordKey> Full = new HashSet<CultRecordKey>();
public int Takes;
public int Held(CultRecordKey design) => Units.TryGetValue(design, out var held) ? held : 0;
public bool TryTake(IReadOnlyList<(CultRecordKey design, int units)> units) { Takes++; return true; }
public bool TryPut(CultRecordKey design, int units) { Units[design] = Held(design) + units; return true; }
public int Room(CultRecordKey design) => Full.Contains(design) ? 0 : int.MaxValue;
public float Deposit(CultRecordKey design) => Deposits.TryGetValue(design, out var held) ? held : 0f;
}
// A raw commodity and the recipe that makes it, with the cycle and count asked for.
private RecipeData Raw(string name, int count, float cycle)
{
var key = _cache.Upsert(new SimpleCommodityData { Name = name, Shape = new Shape(), Price = 1, MaxStack = 1000 }).Key;
_cache.Upsert(typeof(RecipeData), new RecipeData { Output = new CultRecordRef<ItemData>(key), OutputCount = count, Cycle = cycle }, RecipeData.KeyOf(key));
return _cache.Get<RecipeData>(RecipeData.KeyOf(key));
}
private (double made, Ground ground, FacilityRun run, Stall stall, RecipeData a, RecipeData b) ReadMade()
{
var a = Raw("Fix A", 1, 10);
var b = Raw("Fix B", 1, 10);
var ground = new Ground { Deposits = { [a.Output.Key] = 3f, [b.Output.Key] = 1f } };
var (run, stall) = Production.Advance(_cache, new[] { a, b }, null, 400 * 10, ground);
return ((double) ground.Held(a.Output.Key) / ground.Held(b.Output.Key), ground, run, stall, a, b);
}
[Fact]
public void UnitsFollowDeposits()
{
var (made, ground, run, stall, a, b) = ReadMade();
Assert.Equal(400, run.Cycles);
Assert.Equal(Stall.None, stall);
Assert.Equal(400, ground.Held(a.Output.Key) + ground.Held(b.Output.Key));
Assert.True(ground.Held(b.Output.Key) > 0, "one good only: Cycles is not carried into the pick");
Assert.InRange(made, MadeLow, 1e9);
}
// Bounds follow the margin rule (lodur:ruling:deterministic-bound-margin): the geometric mean of the shipped reading and the least claimed
// mutant's, each side at least 1.2 from both. Shipped 2.39 against 1.0 (the cursor goes round robin): 1.55.
private const double MadeLow = 1.55;
private double ReadPerUnit()
{
var one = Raw("Fix One", 1, 10);
var four = Raw("Fix Four", 4, 10);
var ground = new Ground { Deposits = { [one.Output.Key] = 5f, [four.Output.Key] = 5f } };
Production.Advance(_cache, new[] { one, four }, null, 400 * 10, ground);
return (double) ground.Held(four.Output.Key) / ground.Held(one.Output.Key);
}
// Shipped reading 1.30 (units of the count-four good over the count-one, deposits equal), against about 4 without the division by
// OutputCount: 2.28.
[Fact]
public void WeightIsPerUnitNotPerCycle() => Assert.InRange(ReadPerUnit(), 1 / PerUnitBound, PerUnitBound);
private const double PerUnitBound = 2.28;
// OreRate is what the pick averages to, whatever the counts and cycles: units made over 40000 s against it. Shipped reading about 1;
// without the division by OutputCount in OreRate it would claim half the rate (2.0 the other way), so the bound is 1.41.
[Fact]
public void OreRateIsWhatAdvanceAverages()
{
var a = Raw("Fix Rate A", 1, 10);
var b = Raw("Fix Rate B", 8, 40);
var kind = new FieldKindData { Name = "Fix Rate Field", CrossSection = 1f, GenerationWeight = 0f };
kind.Yields.Add(new FieldYield { Commodity = new CultRecordRef<SimpleCommodityData>(a.Output.Key), Abundance = 1f });
kind.Yields.Add(new FieldYield { Commodity = new CultRecordRef<SimpleCommodityData>(b.Output.Key), Abundance = 1f });
_cache.Upsert(kind);
var ground = new Ground { Deposits = { [a.Output.Key] = 3f, [b.Output.Key] = 1f } };
var rate = Production.OreRate(_cache, new[] { a, b }, ground);
Assert.Equal(4.0 / (3 * 10 / 1.0 + 1 * 40 / 8.0), rate, 6);
Production.Advance(_cache, new[] { a, b }, null, 40000, ground);
var made = ground.Held(a.Output.Key) + ground.Held(b.Output.Key);
Assert.InRange(made / 40000.0 / rate, 1 / OreRateBound, OreRateBound);
Assert.Equal(0.0, Production.OreRate(_cache, new[] { a, b }, new Ground()));
}
private const double OreRateBound = 1.41;
[Fact]
public void UnheldGoodNeverStarts()
{
var a = Raw("Fix Held", 1, 10);
var b = Raw("Fix Absent", 1, 10);
// The held good has no room, so its candidate is skipped and the loop falls on to the absent one.
var ground = new Ground { Deposits = { [a.Output.Key] = 3f }, Full = { a.Output.Key } };
var (run, stall) = Production.Advance(_cache, new[] { a, b }, null, 1000, ground);
Assert.Null(run);
Assert.Equal(Stall.Room, stall);
Assert.Equal(0, ground.Held(b.Output.Key));
Assert.Equal(0, ground.Takes);
}
[Fact]
public void BarrenGroundSaysBarren()
{
var a = Raw("Fix Barren A", 1, 10);
var b = Raw("Fix Barren B", 1, 10);
var ground = new Ground();
var idle = new FacilityRun { Recipe = new CultRecordRef<RecipeData>(RecipeData.KeyOf(b.Output.Key)), Progress = 0, Cycles = 5 };
var (run, stall) = Production.Advance(_cache, new[] { a, b }, idle, 1000, ground);
Assert.Same(idle, run);
Assert.Equal(Stall.Barren, stall);
Assert.Equal(0, ground.Takes);
Assert.Empty(ground.Units);
Assert.Equal((null as FacilityRun, Stall.Barren), Production.Advance(_cache, new[] { a, b }, null, 1000, ground));
}
[Fact]
public void CyclesPersist()
{
var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(HullData).Assembly);
var run = new FacilityRun { Recipe = new CultRecordRef<RecipeData>(RecipeData.KeyOf(_oreA)), Progress = 3, Cycles = 7 };
var back = MessagePackSerializer.Deserialize<FacilityRun>(MessagePackSerializer.Serialize(run, options), options);
Assert.Equal((run.Recipe.Key, run.Progress, 7L), (back.Recipe.Key, back.Progress, back.Cycles));
// A pack written before the key: two elements.
var old = MessagePackSerializer.Deserialize<FacilityRun>(MessagePackSerializer.Serialize(new PreCycles { Recipe = run.Recipe, Progress = 3 }, options), options);
Assert.Equal((run.Recipe.Key, 3.0, 0L), (old.Recipe.Key, old.Progress, old.Cycles));
}
[MessagePackObject]
public class PreCycles
{
[Key(0)] public CultRecordRef<RecipeData> Recipe;
[Key(1)] public double Progress;
}
// ---- the rule on a zone ------------------------------------------------------------------------------------------------
private sealed class World
{
public ItemManager Items;
public Zone Zone;
public OrbitalEntity Station;
public Facility Facility;
public EquippableItem Unit;
public EntityHold Hold;
public List<CultRecordKey> Belts = new List<CultRecordKey>();
}
private EquippableItem Mint(ItemManager items, string design)
{
var data = _cache.GetByName<EquippableItemData>(design);
return new EquippableItem
{
Data = _cache.RefOf<ItemData>(data),
Durability = data.Durability,
Lot = items.Lots.Add(new Lot { Design = _cache.RefOf<ItemData>(data), Origin = new Attributed(), Quality = .5f, Roles = new List<RoleFill>() })
};
}
// A zone of a sun, one belt of each count of rocks (kind `fields[i]`), `giants` gas giants, and a Test Yard station holding the
// named facility and bay.
private World Build(string facility, int[] beltRocks, FieldKindData[] fields = null, int giants = 0, string bay = "Vault")
{
var items = new ItemManager(1u, _cache, new ProvenanceLedger(), RunSaveTests.TestSettings(), _ => { });
var sunOrbit = _cache.Upsert(new OrbitData { FixedPosition = float2.zero }).Key;
var pack = new ZonePack
{
Orbits = { new CultRecordRef<OrbitData>(sunOrbit) },
Planets = { new CultRecordRef<BodyData>(_cache.Upsert(new SunData { Orbit = new CultRecordRef<OrbitData>(sunOrbit), Mass = 1f }).Key) },
Radius = 5000f, Mass = 10000f
};
var world = new World();
for (var at = 0; at < beltRocks.Length; at++)
{
var orbit = _cache.Upsert(new OrbitData { Parent = new CultRecordRef<OrbitData>(sunOrbit), Distance = 150f + 40f * at }).Key;
var belt = new AsteroidBeltData
{
Orbit = new CultRecordRef<OrbitData>(orbit), Kind = _cache.RefOf((fields ?? new[] { _field })[at % (fields ?? new[] { _field }).Length]),
Asteroids = Enumerable.Range(0, beltRocks[at]).Select(i => MiningCut3Tests.Rock(100f + 3f * i, (i * .6180339887f) % 1f, .5f)).ToArray()
};
var key = _cache.Upsert(belt).Key;
pack.Orbits.Add(new CultRecordRef<OrbitData>(orbit));
pack.Planets.Add(new CultRecordRef<BodyData>(key));
world.Belts.Add(key);
}
for (var at = 0; at < giants; at++)
{
var orbit = _cache.Upsert(new OrbitData { Parent = new CultRecordRef<OrbitData>(sunOrbit), Distance = 600f + 100f * at }).Key;
pack.Orbits.Add(new CultRecordRef<OrbitData>(orbit));
pack.Planets.Add(new CultRecordRef<BodyData>(_cache.Upsert(new GasGiantData { Orbit = new CultRecordRef<OrbitData>(orbit), Mass = 1f }).Key));
}
var settings = MiningCut3Tests.PlanetSettings();
settings.ChunkCompositionVariance = 0f;
var zone = new Zone(items, settings, pack, new GalaxyZone { Name = "Extraction", Owner = null }, null);
var station = new OrbitalEntity(items, zone, Mint(items, "Test Yard"), default, new EntitySettings());
Assert.True(station.TryEquip(Mint(items, facility), new int2(0, 0)));
Assert.True(station.TryEquip(Mint(items, bay), new int2(4, 4)));
zone.Admit(station, piloted: false);
var unit = station.Equipment.First(equipped => equipped.Behaviors.Any(behavior => behavior is Facility));
world.Items = items;
world.Zone = zone;
world.Station = station;
world.Facility = unit.Behaviors.OfType<Facility>().Single();
world.Unit = unit.EquippableItem;
world.Hold = new EntityHold(station);
return world;
}
private static void Step(World world, double seconds)
{
for (var at = 0; at < Math.Round(seconds / SimClock.GameStep); at++) world.Zone.Update(SimClock.GameStep);
}
private static void Span(World world, double seconds)
{
for (var at = 1; at <= Math.Round(seconds / RegionClock.Span); at++) world.Zone.AdvanceTo(world.Zone.ExactTime + RegionClock.Span);
}
private int Units(World world) => world.Hold.Held(_oreA) + world.Hold.Held(_oreB);
[Fact]
public void OnScreenRigWearsRocks()
{
var world = Build("Extraction Rig", new[] { 3 });
var first = new ChunkId(world.Belts[0], 0);
var second = new ChunkId(world.Belts[0], 1);
var yield = world.Zone.Settings.AsteroidYield.Evaluate(.5f);
var steps = 0;
while (world.Zone.ChunkExists(first) && steps++ < 60000) world.Zone.Update(SimClock.GameStep);
Assert.False(world.Zone.ChunkExists(first), "the first whole rock in index order broke");
Assert.True(world.Zone.ChunkExists(second));
Assert.Equal(world.Zone.AsteroidBelts[world.Belts[0]].UndamagedSize(1, world.Zone.Settings), world.Zone.ChunkRadius(second));
Assert.Null(world.Unit.Run);
Assert.Equal(Stall.None, world.Facility.Stall);
var units = Units(world);
Assert.InRange(units, 1, (int) Math.Ceiling(yield) + 2);
Assert.Equal(units, world.Hold.Held(_oreA) + world.Hold.Held(_oreB));
}
private (double totals, double shares, int on, int off) ReadAgreement()
{
const double seconds = 600;
var on = Build("Extraction Rig", new[] { 40 });
var off = Build("Extraction Rig", new[] { 40 });
Step(on, seconds);
for (var at = 1; at <= seconds / RegionClock.Span; at++) off.Zone.AdvanceTo(at * RegionClock.Span);
var shareOn = (double) on.Hold.Held(_oreA) / Units(on);
var shareOff = (double) off.Hold.Held(_oreA) / Units(off);
return ((double) Units(on) / Units(off), shareOn / shareOff, Units(on), Units(off));
}
[Fact]
public void OnAndOffScreenRatesAgree()
{
var (totals, shares, _, off) = ReadAgreement();
Assert.Equal(300, off);
Assert.InRange(totals, RateLow, RateHigh);
Assert.InRange(shares, ShareLow, ShareHigh);
}
// Shipped readings: total units on screen over off 0.953 (286 over 300; the Bernoulli of each step's owed fraction is a Poisson count, one
// sigma about 6%), and the on-screen share of the first ore over the off-screen one 1.064. Claimed mutants: the rate doubled (about 1.9)
// or halved (about 0.48) gives 1.35 and 0.68; ore drawn evenly instead of by the ground (share ratio about 0.67) gives 0.84.
private const double RateLow = 0.68, RateHigh = 1.35, ShareLow = 0.84, ShareHigh = 1.3;
[Fact]
public void RigStopsWhenFull()
{
var on = Build("Extraction Rig", new[] { 3 }, bay: "Pocket");
var off = Build("Extraction Rig", new[] { 3 }, bay: "Pocket");
foreach (var world in new[] { on, off })
Assert.True(world.Station.CargoBays[0].TryStore(new SimpleCommodity { Data = new CultRecordRef<ItemData>(Good("Slag")), Quantity = 1 }));
Step(on, 30);
Assert.Equal(Stall.Room, on.Facility.Stall);
Assert.Equal(0, Units(on));
Assert.Equal(on.Zone.AsteroidBelts[on.Belts[0]].UndamagedSize(0, on.Zone.Settings), on.Zone.ChunkRadius(new ChunkId(on.Belts[0], 0)));
Assert.True(on.Zone.ChunkExists(new ChunkId(on.Belts[0], 0)));
off.Zone.AdvanceTo(RegionClock.Span);
Assert.Equal(Stall.Room, off.Facility.Stall);
Assert.Equal(0, Units(off));
Assert.Equal(2.0, off.Unit.Run.Progress);
}
// A skimmer runs its recipe in both paths, so a span of steps and a span of time read alike, byte for byte.
[Fact]
public void SkimmerSpansEqualSteps()
{
var steps = Build("Volatiles Skimmer", new int[0], giants: 1);
var spans = Build("Volatiles Skimmer", new int[0], giants: 1);
// 599 s: ends inside a cycle, so a step's float rounding cannot start the next cycle a hair early.
Step(steps, 599);
Span(spans, 540);
spans.Zone.AdvanceTo(spans.Zone.ExactTime + 59);
// The bays, byte for byte; the unit's run only to the float rounding of 36000 steps of dt.
Assert.Equal(Contents(spans), Contents(steps));
Assert.Equal(spans.Unit.Run.Cycles, steps.Unit.Run.Cycles);
Assert.InRange(steps.Unit.Run.Progress, spans.Unit.Run.Progress - 1e-3, spans.Unit.Run.Progress + 1e-3);
Assert.True(Methane(steps) > Water(steps) && Water(steps) > 0, $"3 to 1 by the atmosphere: methane {Methane(steps)}, water {Water(steps)}");
Assert.Equal(299, Methane(steps) + Water(steps) + steps.Hold.Held(Good("Ammonia")));
}
private int Methane(World world) => world.Hold.Held(Good("Methane"));
private int Water(World world) => world.Hold.Held(Good("Water"));
private static byte[] Contents(World world)
{
var pack = EntitySerializer.Pack(world.Station);
var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(HullData).Assembly);
return MessagePackSerializer.Serialize((pack.CargoBays, pack.CargoContents), options);
}
[Fact]
public void AtmospheresBatchWritesOnlyWhereItDiffers()
{
var author = new EconomyAuthor(_cache);
new Atmospheres().Author(author);
Assert.Equal(new[] { "atmosphere:gas-giant" }, author.Touched);
var held = _cache.Get<AtmosphereData>(AtmosphereData.KeyOf(Deposits.GasGiantAtmosphere));
Assert.Equal(new[] { ("Ammonia", 1f), ("Methane", 3f), ("Water", 2f) }, held.Yields.Select(yield => (_cache.Get(yield.Commodity).Name, yield.Abundance)).ToArray());
var again = new EconomyAuthor(_cache);
new Atmospheres().Author(again);
Assert.Empty(again.Touched);
}
// The shipped catalog holds what the batch writes: applying it to a copy touches nothing.
[Fact]
public void ShippedAtmosphereIsTheBatch()
{
var path = Path.Combine(_root, "shipped.cc");
File.Copy(TestCatalog.Repo, path);
using var shipped = new CultCache(TestCatalog.Registry());
shipped.AddBackingStore(new SingleFileMessagePackBackingStore(path), AetheriaStores.CatalogTypes);
Assert.NotNull(shipped.Get<AtmosphereData>(AtmosphereData.KeyOf(Deposits.GasGiantAtmosphere)));
var author = new EconomyAuthor(shipped);
new Atmospheres().Author(author);
Assert.Empty(author.Touched);
}
// What the ground holds: a belt adds its kind's yields as shares of one, times what its rocks pay; a gas giant its atmosphere's.
[Fact]
public void DepositsSumBeltsByRockYield()
{
var world = Build("Extraction Rig", new[] { 4, 1 }, new[] { _field, _fieldB }, giants: 2);
var each = world.Zone.Settings.AsteroidYield.Evaluate(.5f);
var got = Deposits.Of(world.Zone, _cache);
var held = got.ToDictionary(entry => entry.design, entry => entry.amount);
Assert.Equal(4 * each * .75, held[_oreA], 3);
Assert.Equal(4 * each * .25 + each, held[_oreB], 3);
// Two giants of one atmosphere: Methane, Ammonia and Water as 3 : 2 : 1 of two.
Assert.Equal(2 * 3 / 6.0, held[Good("Methane")], 3);
Assert.Equal(2 * 2 / 6.0, held[Good("Ammonia")], 3);
Assert.Equal(2 * 1 / 6.0, held[Good("Water")], 3);
Assert.Equal(got.Select(entry => entry.design.Value).OrderBy(key => key, StringComparer.Ordinal), got.Select(entry => entry.design.Value));
// Volatiles are not ore, and a zone with neither belt nor gas giant holds nothing.
Assert.DoesNotContain(held.Keys, key => FieldKinds.IsOre(_cache, _cache.Get<ItemData>(key)) && !key.Equals(_oreA) && !key.Equals(_oreB));
Assert.False(FieldKinds.IsOre(_cache, _cache.Get<ItemData>(Good("Methane"))));
Assert.Empty(Deposits.Of(Build("Extraction Rig", new int[0]).Zone, _cache));
Assert.Empty(Deposits.Of(null, _cache));
}
}
// What a generated region's ground holds, on the zones a run boots (the run-start fixture builds them).
public sealed partial class RunStartTests
{
[Fact]
public void DepositsReadTheZone()
{
var provinced = 0;
var holding = 0;
foreach (var seed in RegionSeeds)
{
var (galaxy, _, _) = RegionRun(seed);
foreach (var galaxyZone in galaxy.Zones)
{
var zone = galaxyZone.Contents;
var got = Deposits.Of(zone, _cache);
var stated = new SortedDictionary<string, double>(StringComparer.Ordinal);
var mined = new HashSet<string>();
foreach (var belt in zone.AsteroidBelts.Values)
{
var yields = FieldKinds.Yield(belt.Data.Kind, galaxyZone.Province?.Type ?? default, _cache);
var total = yields.Sum(yield => (double) yield.Amount);
var rocks = belt.Data.Asteroids.Sum(rock => (double) zone.Settings.AsteroidYield.Evaluate(rock.Size));
foreach (var yield in yields)
{
stated[yield.Commodity.Key.Value] = stated.GetValueOrDefault(yield.Commodity.Key.Value) + yield.Amount / total * rocks;
mined.Add(yield.Commodity.Key.Value);
}
// The same belt in a default province: the regional ores it holds differ.
var plain = FieldKinds.Yield(belt.Data.Kind, default, _cache).Select(yield => yield.Commodity.Key.Value).ToArray();
if (!plain.OrderBy(key => key, StringComparer.Ordinal).SequenceEqual(yields.Select(yield => yield.Commodity.Key.Value))) provinced++;
}
var giants = zone.Planets.Values.Count(body => body is GasGiantData && !(body is SunData));
var atmosphere = _cache.Get<AtmosphereData>(AtmosphereData.KeyOf(Deposits.GasGiantAtmosphere));
if (giants > 0 && atmosphere != null)
{
var yields = FieldKinds.Yield(atmosphere.Yields, galaxyZone.Province?.Type ?? default, _cache);
var total = yields.Sum(yield => (double) yield.Amount);
foreach (var yield in yields)
stated[yield.Commodity.Key.Value] = stated.GetValueOrDefault(yield.Commodity.Key.Value) + yield.Amount / total * giants;
}
Assert.Equal(stated.Keys, got.Select(entry => entry.design.Value));
for (var at = 0; at < got.Length; at++) Assert.InRange(got[at].amount, stated[got[at].design.Value] * .9999, stated[got[at].design.Value] * 1.0001);
// Every ore a rock of the zone can pay has a deposit, and no other ore has one.
Assert.Equal(mined.OrderBy(key => key, StringComparer.Ordinal),
got.Where(entry => FieldKinds.IsOre(_cache, _cache.Get<ItemData>(entry.design))).Select(entry => entry.design.Value));
if (zone.AsteroidBelts.Count == 0 && giants == 0) Assert.Empty(got);
if (got.Length > 0) holding++;
}
}
Assert.True(holding > 0, "no zone holds anything");
Assert.True(provinced > 0, "no belt's ores depend on its province: the province read is untested");
}
}