Production: a raw recipe runs where the ground holds its good

Deletes the !Recipes.IsRaw clause of Production.Runs, the obsolete owner that decided extraction never runs (cut facility-extraction;
rulings auto-mining-is-off-screen-only, skimmers-run-their-recipe-on-screen-for-now).

- Deposits.Of is the one owner of what a zone's ground holds (belts by rock yield through FieldKinds.Yield, gas giants through the new
  AtmosphereData); IProductionHold.Deposit reads it, EntityHold keeps it per zone.
- Production.Advance starts a list of raw recipes at a pick weighted by deposit per unit made (FieldKinds.Pick on FacilityRun.Cycles, new
  Key 2), skips a raw candidate the ground lacks, and reads Stall.Barren, writing nothing, where the ground holds none.
- Production.OreRate is the rate that pick averages to, the one rate on screen and off.
- FieldKinds.Yield gains the list overload Deposits calls; OreGeographyTests names the default FieldKindData ref the overload made ambiguous.
- RunListIsTheRule drops the raw exclusion; a recipe made raw is no longer dropped from a running cycle, so its test case goes with the rule.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
soul 2026-11-29 07:48:07 +01:00
commit dc75e9a801
9 changed files with 175 additions and 30 deletions

View file

@ -7,7 +7,7 @@ using GameCult.Caching.MessagePack;
// Aetheria's stores: one home store per type, composed here and nowhere else.
public static class AetheriaStores
{
public static readonly Type[] CatalogTypes = { typeof(ItemData), typeof(ShipAuthoring), typeof(Faction), typeof(FactionProductData), typeof(PersonalityAttribute), typeof(InputLayout), typeof(Loadout), typeof(FieldKindData), typeof(ProvinceData), typeof(VerseGrammar), typeof(VerseVerb), typeof(StationKindData), typeof(RecipeData), typeof(OutsideMarketData) };
public static readonly Type[] CatalogTypes = { typeof(ItemData), typeof(ShipAuthoring), typeof(Faction), typeof(FactionProductData), typeof(PersonalityAttribute), typeof(InputLayout), typeof(Loadout), typeof(FieldKindData), typeof(ProvinceData), typeof(VerseGrammar), typeof(VerseVerb), typeof(StationKindData), typeof(RecipeData), typeof(OutsideMarketData), typeof(AtmosphereData) };
public static readonly Type[] RunTypes = { typeof(OrbitData), typeof(BodyData), typeof(SavedZone), typeof(SavedGame), typeof(ProvenanceLedger), typeof(HaulOrderData) };
public static readonly Type[] PlayerTypes = { typeof(PlayerSettings) };

View file

@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Linq;
using GameCult.Caching;
using MessagePack;
using Newtonsoft.Json;
// What a gas giant's atmosphere holds before its province weights it: a catalog record, keyed atmosphere:<id>. Its yields are
// read by Deposits through FieldKinds.Yield, as a field kind's are. Volatiles are not ore: FieldKinds.IsOre never reads this.
[CultDocument("aetheria.atmospheredata", "1"), MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class AtmosphereData
{
[CultName, JsonProperty("name"), Key(0)]
public string Name = "";
[JsonProperty("yields"), Key(1)]
public List<FieldYield> Yields = new List<FieldYield>();
public static CultRecordKey KeyOf(string id) => new CultRecordKey("atmosphere:" + id);
}
// The one owner of what a zone's ground holds (ruling auto-mining-is-off-screen-only): the goods an ore rig mines or a skimmer
// skims, in units, derived from the zone's bodies and never stored. Production.Advance picks its raw recipes by it off screen,
// and Production.OreRate reads it for the rate on screen.
public static class Deposits
{
// The atmosphere every gas giant draws on, until a giant authors its own.
public const string GasGiantAtmosphere = "gas-giant";
// Each good's amount, in design-key order, zero dropped; empty for a null zone. A belt adds its kind's yields in this
// province (FieldKinds.Yield) as shares of one, times what its rocks pay a miner once fully worn (the sum of
// Settings.AsteroidYield over their sizes, the units FireControl.Extract splits by the same yields). A gas giant that is not
// a sun adds the atmosphere's yields the same way, as shares of one times one.
public static (CultRecordKey design, float amount)[] Of(Zone zone, CultCache catalog)
{
if (zone == null) return Array.Empty<(CultRecordKey, float)>();
var province = zone.GalaxyZone?.Province?.Type ?? default;
var held = new Dictionary<string, (CultRecordKey design, double amount)>(StringComparer.Ordinal);
void Add((CultRecordRef<SimpleCommodityData> Commodity, float Amount)[] yields, double scale)
{
var total = yields.Sum(yield => (double) yield.Amount);
if (!(total > 0) || !(scale > 0)) return;
foreach (var yield in yields)
{
var key = yield.Commodity.Key;
held.TryGetValue(key.Value, out var before);
held[key.Value] = (key, before.amount + yield.Amount / total * scale);
}
}
foreach (var belt in zone.AsteroidBelts.OrderBy(entry => entry.Value.Data.SiteOr(entry.Key), StringComparer.Ordinal))
{
var rocks = belt.Value.Data.Asteroids.Sum(rock => (double) zone.Settings.AsteroidYield.Evaluate(rock.Size));
Add(FieldKinds.Yield(belt.Value.Data.Kind, province, catalog), rocks);
}
var giants = zone.Planets.Values.Count(body => body is GasGiantData && !(body is SunData));
var atmosphere = catalog.Get<AtmosphereData>(AtmosphereData.KeyOf(GasGiantAtmosphere));
if (giants > 0 && atmosphere != null) Add(FieldKinds.Yield(atmosphere.Yields, province, catalog), giants);
return held.Values.Where(entry => entry.amount > 0).OrderBy(entry => entry.design.Value, StringComparer.Ordinal)
.Select(entry => (entry.design, (float) entry.amount)).ToArray();
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1fddcfe8170c46949a77a09bcbc69082
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -7,19 +7,24 @@ using MessagePack;
using Newtonsoft.Json;
// A facility's cycle in progress, on the installed unit (EquippableItem.Run): the recipe it last ran or is running, and the sim
// seconds of the running cycle. Progress 0 is idle, and Recipe is then the round-robin cursor. Written only by Facility.Execute
// from Production.Advance's result; the inputs of a running cycle are already taken and live nowhere else.
// seconds of the running cycle. Progress 0 is idle, and Recipe is then the round-robin cursor. Written only by Facility from
// Production.Advance's result, which carries Cycles on every run it returns; the inputs of a running cycle are already taken and
// live nowhere else.
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class FacilityRun
{
[JsonProperty("recipe"), Key(0)] public CultRecordRef<RecipeData> Recipe;
[JsonProperty("progress"), Key(1)] public double Progress;
// The cycles this unit has started, written only by Advance: the pick of a raw recipe reads it, so a span and as many steps pick
// alike. A run saved before this key reads 0.
[JsonProperty("cycles"), Key(2)] public long Cycles;
}
// Why a facility is not advancing, derived on each call and stored nowhere.
public enum Stall { None, Inputs, Room, Unrunnable }
// Why a facility is not advancing, derived on each call and stored nowhere. Barren: idle, and the ground holds none of the raw
// goods its recipes make.
public enum Stall { None, Inputs, Room, Unrunnable, Barren }
// Where a facility's goods are: its host's bays on screen, a stock ledger off screen. Each write is whole or nothing.
// Where a facility's goods are: its host's bays on screen or off (EntityHold), or a ledger in a test. Each write is whole or nothing.
public interface IProductionHold
{
int Held(CultRecordKey design);
@ -27,16 +32,19 @@ public interface IProductionHold
bool TryPut(CultRecordKey design, int units);
// The units of the design a put may still store; int.MaxValue when the hold sets no bound.
int Room(CultRecordKey design);
// How much of the design the host's ground holds (Deposits); 0 where none.
float Deposit(CultRecordKey design);
}
// The one rule for a facility cycle: which recipe starts, which units it takes, how far it has run, what it stores. On screen its
// one caller is Facility.Execute, with one zone step; off screen the strategic tick calls it with a longer span. It reads no
// random, no clock and no crew.
// caller is Facility, with one zone step (an ore rig works the rocks instead, ruling auto-mining-is-off-screen-only); off screen
// the strategic tick calls it with a longer span. It reads no random, no clock and no crew.
public static class Production
{
// A recipe a facility can run today: it takes something, and makes a simple commodity (a graded output needs a lot).
// A recipe a facility can run: it makes a simple commodity, raw or processed. A raw recipe takes from the ground (IProductionHold.Deposit);
// a graded output needs a lot, which no cycle mints.
public static bool Runs(CultCache catalog, RecipeData recipe) =>
!Recipes.IsRaw(catalog, recipe) && catalog.Get(recipe.Output) is SimpleCommodityData;
catalog.Get(recipe.Output) is SimpleCommodityData;
// The recipe a run names as the catalog holds it now, or null when the catalog no longer has it or no longer runs it here.
public static RecipeData Live(CultCache catalog, CultRecordRef<RecipeData> recipe)
@ -90,13 +98,34 @@ public static class Production
return need;
}
// The units per sim second of the list's ore recipes the ground holds: the expected output of Advance's deposit pick, so the one
// rate an ore rig runs at off screen and works the rocks at on screen. Each recipe i weighs D_i = hold.Deposit(output_i); it is
// picked in proportion to D_i / OutputCount_i and makes OutputCount_i units in Cycle_i seconds, so the rate is
// sum D_i / sum (D_i x Cycle_i / OutputCount_i). 0 when the list holds no ore the ground has.
public static double OreRate(CultCache catalog, IReadOnlyList<RecipeData> runList, IProductionHold hold)
{
double deposit = 0, seconds = 0;
foreach (var recipe in runList)
{
if (!(catalog.Get(recipe.Output) is SimpleCommodityData output) || !FieldKinds.IsOre(catalog, output)) continue;
var held = hold.Deposit(recipe.Output.Key);
if (!(held > 0f)) continue;
deposit += held;
seconds += held * recipe.Cycle / Math.Max(1, recipe.OutputCount);
}
return seconds > 0 ? deposit / seconds : 0;
}
// The facility's state after `seconds` of sim time, and why it is not advancing. An idle facility (run null or Progress 0)
// starts the first recipe after the cursor, wrapping, whose units the hold grants and whose output the hold has room for
// (IProductionHold.Room), and takes them at once; a recipe skipped for room leaves the facility on Stall.Room when none starts; a running one adds
// time; at Progress >= Cycle it stores the output and goes idle, the recipe staying as the cursor. A store the hold refuses
// holds the batch at Cycle (Room) and retries on the next call. Time left after a cycle ends runs the next one in the same call,
// so a long span runs several cycles (the rule that makes one span equal as many steps as it covers); time that no cycle can start is
// dropped. A facility with nothing to start writes nothing.
// (IProductionHold.Room), and takes them at once; a recipe skipped for room leaves the facility on Stall.Room when none starts;
// a running one adds time; at Progress >= Cycle it stores the output and goes idle, the recipe staying as the cursor. A store the
// hold refuses holds the batch at Cycle (Room) and retries on the next call. Time left after a cycle ends runs the next one in the
// same call, so a long span runs several cycles (the rule that makes one span equal as many steps as it covers); time that no cycle
// can start is dropped. A facility with nothing to start writes nothing.
// A raw recipe takes from the ground: it starts only where the hold's Deposit of its good is positive. A list of raw recipes starts
// at a pick (FieldKinds.Pick on the cycles started so far) weighted by each good's deposit per unit made, so the units of each held
// raw good come in proportion to its deposit, and a list whose ground holds none reads Barren and writes nothing.
public static (FacilityRun run, Stall stall) Advance(CultCache catalog, IReadOnlyList<RecipeData> runList, FacilityRun run,
double seconds, IProductionHold hold)
{
@ -104,14 +133,24 @@ public static class Production
// progress is gone and the inputs it took stay consumed, as they are taken whole at cycle start and the recipe that named
// them is not there to return them against. The facility then starts its next recipe. Nothing below can meet a run that is not
// live: a start is of a recipe the catalog holds and runs, so Advance never throws on one and never spins.
var cycles = run?.Cycles ?? 0;
if (run != null && run.Progress > 0 && Live(catalog, run.Recipe) == null) run = null;
if (runList.Count == 0) return (run, Stall.Unrunnable);
var raw = runList.All(recipe => Recipes.IsRaw(catalog, recipe));
while (true)
{
if (run == null || run.Progress <= 0)
{
if (seconds <= 0) return (run, Stall.None);
var cursor = run == null ? -1 : IndexOf(runList, run.Recipe.Key);
if (raw)
{
// The cursor sits one before the pick, so the pick is the first candidate: units of each held good come in
// proportion to its deposit (a cycle makes OutputCount units, hence the weight per unit made).
var pick = FieldKinds.Pick($"extract:{cycles}", runList.Select(recipe => (double) hold.Deposit(recipe.Output.Key) / Math.Max(1, recipe.OutputCount)).ToArray());
if (pick < 0) return (run, Stall.Barren);
cursor = pick - 1;
}
RecipeData start = null;
var skippedForRoom = false;
for (var step = 1; step <= runList.Count && start == null; step++)
@ -120,13 +159,14 @@ public static class Production
// started run is always one the next pass of this loop resolves, and a pass over the whole list ends the loop.
var candidate = Live(catalog, new CultRecordRef<RecipeData>(RecipeData.KeyOf(runList[(cursor + step + runList.Count) % runList.Count].Output.Key)));
if (candidate == null) continue;
if (Recipes.IsRaw(catalog, candidate) && !(hold.Deposit(candidate.Output.Key) > 0f)) continue;
var units = Take(catalog, candidate, hold);
if (units == null) continue;
if (hold.Room(candidate.Output.Key) < candidate.OutputCount) { skippedForRoom = true; continue; }
if (hold.TryTake(units)) start = candidate;
}
if (start == null) return (run, skippedForRoom ? Stall.Room : Stall.Inputs);
run = new FacilityRun { Recipe = new CultRecordRef<RecipeData>(RecipeData.KeyOf(start.Output.Key)), Progress = 0 };
run = new FacilityRun { Recipe = new CultRecordRef<RecipeData>(RecipeData.KeyOf(start.Output.Key)), Progress = 0, Cycles = ++cycles };
}
var recipe = Live(catalog, run.Recipe);
@ -137,10 +177,10 @@ public static class Production
progress += spent;
seconds -= spent;
}
if (progress < recipe.Cycle) return (new FacilityRun { Recipe = run.Recipe, Progress = progress }, Stall.None);
if (progress < recipe.Cycle) return (new FacilityRun { Recipe = run.Recipe, Progress = progress, Cycles = cycles }, Stall.None);
if (!hold.TryPut(recipe.Output.Key, recipe.OutputCount))
return (new FacilityRun { Recipe = run.Recipe, Progress = recipe.Cycle }, Stall.Room);
run = new FacilityRun { Recipe = run.Recipe, Progress = 0 };
return (new FacilityRun { Recipe = run.Recipe, Progress = recipe.Cycle, Cycles = cycles }, Stall.Room);
run = new FacilityRun { Recipe = run.Recipe, Progress = 0, Cycles = cycles };
if (seconds <= 0) return (run, Stall.None);
}
}
@ -199,6 +239,23 @@ public sealed class EntityHold : IProductionHold
// The units the output bays may still take of the design (StationWants.Room, the one decision of room).
public int Room(CultRecordKey design) => StationWants.Room(_entity, design);
private Zone _ground;
private (CultRecordKey design, float amount)[] _deposits;
// What the entity's zone's ground holds of the design (Deposits.Of), computed on the first call and kept: a zone's bodies and the
// catalog are fixed for a run. Derived, never stored; read again if the entity has moved to another zone.
public float Deposit(CultRecordKey design)
{
if (_deposits == null || !ReferenceEquals(_ground, _entity.Zone))
{
_ground = _entity.Zone;
_deposits = Deposits.Of(_ground, _entity.ItemManager.ItemData);
}
foreach (var (held, amount) in _deposits)
if (held.Equals(design)) return amount;
return 0f;
}
public bool TryPut(CultRecordKey design, int units)
{
var data = _entity.ItemManager.ItemData.Get<SimpleCommodityData>(design);

View file

@ -281,9 +281,15 @@ public static class FieldKinds
CultRecordRef<ProvinceData> province, CultCache catalog)
{
var data = catalog.Get(kind);
if (data == null) return Array.Empty<(CultRecordRef<SimpleCommodityData>, float)>();
return data == null ? Array.Empty<(CultRecordRef<SimpleCommodityData>, float)>() : Yield(data.Yields, province, catalog);
}
// The same rule over any list of yields (an atmosphere's, Deposits): each yield's Abundance times the province's factor for the ore.
public static (CultRecordRef<SimpleCommodityData> Commodity, float Amount)[] Yield(IReadOnlyList<FieldYield> yields,
CultRecordRef<ProvinceData> province, CultCache catalog)
{
var type = catalog.Get(province);
return data.Yields
return yields
.Select(yield => (yield.Commodity, Amount: yield.Abundance * Factor(
type?.Ores.Where(ore => ore.Commodity.Key.Equals(yield.Commodity.Key)).Select(ore => (double) ore.Weight), yield.Regional ? 0.0 : 1.0)))
.GroupBy(yield => yield.Commodity.Key.Value, StringComparer.Ordinal)

View file

@ -247,26 +247,31 @@ public sealed class FacilityProductionTests : IDisposable
public void RunListIsTheRule()
{
var expected = new Dictionary<string, int> { ["Refinery"] = 18, ["Munitions Line"] = 5, ["Algae Vats"] = 1,
["Fabrication Line"] = 0, ["Extraction Rig"] = 0, ["Volatiles Skimmer"] = 0 };
["Fabrication Line"] = 0, ["Extraction Rig"] = 19, ["Volatiles Skimmer"] = 3 };
foreach (var design in _cache.GetAll<GearData>().Where(StationKinds.IsRecipeFacility))
{
var key = _cache.RefOf(design).Key;
var rule = _cache.GetAll<RecipeData>()
.Where(recipe => recipe.Facility.IsSet() && recipe.Facility.Key.Equals(key))
.Where(recipe => !Recipes.IsRaw(_cache, recipe) && _cache.Get(recipe.Output) is SimpleCommodityData)
.Where(recipe => _cache.Get(recipe.Output) is SimpleCommodityData)
.OrderBy(recipe => RecipeData.KeyOf(recipe.Output.Key).Value, StringComparer.Ordinal)
.ToArray();
Assert.Equal(rule, Production.RunList(_cache, key));
Assert.Equal(expected[design.Name], rule.Length);
}
foreach (var name in new[] { "Extraction Rig", "Volatiles Skimmer", "Fabrication Line" })
// The test zone has no belt and no gas giant: a rig and a skimmer find nothing in the ground and write nothing.
foreach (var name in new[] { "Extraction Rig", "Volatiles Skimmer" })
{
var world = Build(name);
Step(world, 2);
Assert.Equal(Stall.Unrunnable, world.Facility.Stall);
Assert.Equal(Stall.Barren, world.Facility.Stall);
Assert.Null(world.Unit.Run);
}
var fabrication = Build("Fabrication Line");
Step(fabrication, 2);
Assert.Equal(Stall.Unrunnable, fabrication.Facility.Stall);
Assert.Null(fabrication.Unit.Run);
}
[Fact]
@ -673,11 +678,11 @@ public sealed class FacilityProductionTests : IDisposable
Assert.Equal(RecipeData.KeyOf(new CultRecordKey("commodity:copper")), run.Recipe.Key);
}
// A running cycle whose recipe the catalog changed under it is dropped, whatever the change: the recipe removed, made raw (it takes
// nothing now) or given a compound output (a graded output needs a lot). The facility's list is rebuilt and it moves on.
// A running cycle whose recipe the catalog changed under it is dropped, whatever the change: the recipe removed or given a compound
// output (a graded output needs a lot). The facility's list is rebuilt and it moves on. A recipe made raw is not among them: a raw recipe
// runs (it takes from the ground), so its running cycle goes on.
[Theory]
[InlineData("removed")]
[InlineData("raw")]
[InlineData("compound")]
public void ARunningCycleWhoseRecipeStoppedRunningIsDropped(string change)
{
@ -687,7 +692,6 @@ public sealed class FacilityProductionTests : IDisposable
Assert.Equal(RecipeData.KeyOf(Iron), world.Unit.Run.Recipe.Key);
var ironKey = RecipeData.KeyOf(Iron);
if (change == "removed") _cache.Remove(ironKey);
else if (change == "raw") Edit(ironKey, recipe => recipe.RoleInputs.Clear());
else Edit(ironKey, recipe => recipe.Output = new CultRecordRef<ItemData>(_cache.RefOf<ItemData>(_cache.GetAll<CompoundCommodityData>().First()).Key));
Step(world, 2);

View file

@ -88,6 +88,7 @@ public sealed class HabitationTests : IDisposable
}
public bool TryPut(CultRecordKey design, int units) { Units[design] = Held(design) + units; return true; }
public int Room(CultRecordKey design) => int.MaxValue;
public float Deposit(CultRecordKey design) => 0f;
}
private Ledger Stocked(int water, int air) => new Ledger { Units = { [_water] = water, [_air] = air } };

View file

@ -324,7 +324,7 @@ public sealed class OreGeographyTests : IDisposable
var nowhere = FieldKinds.Yield(kind, default, cache);
Assert.Equal(new[] {("ore:copper", 2f), ("ore:iron", .5f), ("ore:tin", 1f)}, nowhere.Select(y => (y.Commodity.Key.Value, y.Amount)).ToArray());
Assert.Empty(FieldKinds.Yield(default, province, cache));
Assert.Empty(FieldKinds.Yield(default(CultRecordRef<FieldKindData>), province, cache));
Assert.Empty(FieldKinds.Yield(new CultRecordRef<FieldKindData>(new CultRecordKey("field-kind:missing")), province, cache));
}

View file

@ -23,6 +23,7 @@ public sealed partial class RunStartTests
public bool TryTake(IReadOnlyList<(CultRecordKey design, int units)> units) => true;
public bool TryPut(CultRecordKey design, int units) => true;
public int Room(CultRecordKey design) => int.MaxValue;
public float Deposit(CultRecordKey design) => 0f;
}
private IEnumerable<CultRecordKey> ShippedFacilityDesigns() =>