Aetheria/Assets/Scripts/ServerShared/StationWants.cs
soul c77ef59953 A hauler acts on what it saw at its To door, saved with it; no zone's bays are read from afar
Ruling hauler-remembers-what-it-saw. HaulRun.ToStation and its live read of the To station's bays are deleted. A hauler writes down at
the To door which goods of its order were refused and when (Ship.HaulSeen, EntityPack Key 25); the leg is To while the hold holds a good
it does not remember being refused, and a call at From returns what it remembers being refused and loads the rest. A refusal lives
RefusalLife seconds, so a stale memory costs a real round trip. At the To door a call delivers what the station takes or learns what it
does not (StationWants.Takable, derived once per call there and nowhere else). Tests: the learn-and-carry-home round trip, no leg reads
another zone's bays, any-versus-all on a mixed hold and expiry, returns land in the output bays, the dive at every jump, the memory
saved with the hauler, and wormhole transfers bounded against the memory-less mutant.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-01 14:18:54 +01:00

163 lines
10 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using GameCult.Caching;
using MessagePack;
using Newtonsoft.Json;
// What a station buys (aetheria-living-world:ruling:installed-gear-decides-what-a-station-buys): the goods its installed
// recipe facilities draw, the goods its installed habitation modules' tables name (the crew eats), and, when it carries a silo,
// the goods of the haul orders that start at its orbit (ruling transit-depots-buy-for-onward-haul). Derived on every call from the station's gear and the catalog, stored nowhere.
// StationServices.TrySellPart is gated by it and limited by the bays' room.
//
// Where goods land and how much of a product a station holds (cut facility-output-room). A station with a silo keeps what its
// facilities make there, and each product holds an even share of the silo: Allocation, floor(silo cells / products) x the
// product's MaxStack (a good a haul order names has a share of the silo as a product has). A recipe starts only when its product has room (CanStart), and a station draws an ore only while some recipe
// that takes it can start, so a full product stops its ores being bought while the station keeps running its other recipes. Prior
// art: X4's per-ware storage allocation (a full ware stops that production, the station keeps running the rest) and Factorio's
// per-product output slot. A station with no silo has no bound: outputs land in any bay and Room happens at the put.
public static class StationWants
{
public static IReadOnlyCollection<CultRecordKey> Of(Entity station)
{
var wants = Drawn(station);
wants.UnionWith(Ordered(station));
return wants;
}
// Where a bought or delivered good may land and how much of it: the non-silo bays, unbounded, when an installed recipe facility
// draws it (a drawn good is stock, never silo content); the silo bays, up to the good's share of the silo (Room), when the station
// wants it through a haul order (a transit depot holds goods in its silo, never in its stock bay). The one owner of where a good
// lands; none when the station does not want it.
public static IEnumerable<(IReadOnlyList<EquippedCargoBay> Bays, int Room)> Landing(Entity station, CultRecordKey good) =>
LandingOf(station, Drawn(station), Ordered(station).ToHashSet(), good);
private static IEnumerable<(IReadOnlyList<EquippedCargoBay> Bays, int Room)> LandingOf(Entity station, HashSet<CultRecordKey> drawn, HashSet<CultRecordKey> ordered, CultRecordKey good)
{
if (drawn.Contains(good)) yield return (station.CargoBays.Where(bay => !(bay.Data is SiloData)).ToArray(), int.MaxValue);
if (ordered.Contains(good)) yield return (station.CargoBays.Where(bay => bay.Data is SiloData).ToArray(), Room(station, good));
}
// Of the goods, those the station would take a unit of now: it wants the good (Landing), has room for it and a bay with a place for a
// unit. What a station wants is derived from its gear on every read, so this asks once for all the goods: a hauler asks on every call.
public static HashSet<CultRecordKey> Takable(Entity station, IEnumerable<CultRecordKey> goods)
{
var drawn = Drawn(station);
var ordered = Ordered(station).ToHashSet();
return goods.Where(good => LandingOf(station, drawn, ordered, good).Any(landing => landing.Room > 0
&& landing.Bays.Any(bay => bay.TryFindSpace(new SimpleCommodity { Data = new CultRecordRef<ItemData>(good), Quantity = 1 })))).ToHashSet();
}
public static IEnumerable<EquippedCargoBay> Bays(Entity station, CultRecordKey good) => Landing(station, good).SelectMany(landing => landing.Bays);
// The bays a facility's output may land in: the silo bays when the station has one, else every bay. The one owner of where
// a facility output lands.
public static IEnumerable<EquippedCargoBay> OutputBays(Entity station, CultRecordKey good) =>
station.CargoBays.Any(bay => bay.Data is SiloData) ? station.CargoBays.Where(bay => bay.Data is SiloData) : station.CargoBays;
// The units of a good the station may hold in its silo: the silo's cells divided evenly among the distinct goods that land there,
// the outputs of its recipe facilities and the goods of its haul orders, each share worth that many full stacks of the good. Null
// (no bound) without a silo or a recipe facility (a depot with no facility holds what its orders name). Derived on every call,
// stored nowhere.
public static int? Allocation(Entity station, CultRecordKey good)
{
var silos = station.CargoBays.Where(bay => bay.Data is SiloData).ToArray();
if (silos.Length == 0) return null;
var outputs = Makes(station);
if (outputs.Count == 0) return null;
var slots = outputs.Concat(Ordered(station)).Distinct().Count();
var cells = silos.Sum(bay => bay.Data.InteriorShape.Coordinates.Length);
var stack = station.ItemManager.ItemData.Get<SimpleCommodityData>(good)?.MaxStack ?? 0;
return cells / slots * stack;
}
// The units of a good that may still be stored in the silo: its share less what the output bays hold, int.MaxValue with no bound.
// The one decision of room: a recipe starts on it (CanStart, EntityHold.Room) and a sale of an ordered good stops at it.
public static int Room(Entity station, CultRecordKey good)
{
var allocation = Allocation(station, good);
return allocation == null ? int.MaxValue : Math.Max(0, allocation.Value - OutputBays(station, good).Sum(bay => bay.Count(good)));
}
// Whether the recipe's product has room for one more cycle's output.
public static bool CanStart(Entity station, RecipeData recipe) => Room(station, recipe.Output.Key) >= recipe.OutputCount;
private static IEnumerable<RecipeData> FacilityRecipes(Entity station)
{
var catalog = station.ItemManager.ItemData;
foreach (var equipped in station.Equipment)
{
var design = station.ItemManager.GetData(equipped.EquippableItem);
if (!StationKinds.IsRecipeFacility(design)) continue;
foreach (var recipe in Production.RunList(catalog, catalog.RefOf(design).Key)) yield return recipe;
}
}
// Every good the station's installed recipe facilities consume, startable or not: what a standing haul order may carry to it (a
// seeded leg waits on room and never writes an order for a good no installed recipe takes). The crew's table is not here: it is
// bought by sale, never hauled by a seeded leg. Drawn is the startable part.
public static IReadOnlyCollection<CultRecordKey> Consumed(Entity station) =>
FacilityRecipes(station).SelectMany(recipe => Production.Draws(station.ItemManager.ItemData, recipe)).ToHashSet();
// The goods its installed recipe facilities make: the set Allocation builds.
public static IReadOnlyCollection<CultRecordKey> Makes(Entity station) => FacilityRecipes(station).Select(recipe => recipe.Output.Key).ToHashSet();
private static HashSet<CultRecordKey> Drawn(Entity station)
{
var catalog = station.ItemManager.ItemData;
var wants = new HashSet<CultRecordKey>();
foreach (var recipe in FacilityRecipes(station).Where(recipe => CanStart(station, recipe)))
foreach (var draw in Production.Draws(catalog, recipe))
wants.Add(draw);
// What its crew eats: the table of every habitation unit that runs (the module defines what and how much it consumes).
foreach (var unit in station.Equipment.Where(unit => unit.Enabled.Value && !unit.EquippableItem.IsDestroyed))
foreach (var habitation in unit.Behaviors.Select(behavior => behavior.Data).OfType<HabitationData>())
foreach (var row in habitation.Table.Where(row => row.Commodity.IsSet()))
wants.Add(row.Commodity.Key);
return wants;
}
private static IEnumerable<CultRecordKey> Ordered(Entity station)
{
if (!(station is OrbitalEntity { OrbitData: var orbit }) || !orbit.IsSet() || !station.CargoBays.Any(bay => bay.Data is SiloData))
return Enumerable.Empty<CultRecordKey>();
return station.ItemManager.ItemData.GetAll<HaulOrderData>().Where(order => order.From.Key.Equals(orbit))
.SelectMany(order => order.Goods.Select(good => good.Key)).ToArray();
}
}
// A standing haul order: goods that move from one station's orbit to another's, keyed haul-order:<id>. A run document: saved
// with the run, cleared, replaced and discarded with it. Fixed until offices issue orders (ruling transit-depots-buy-for-onward-haul);
// From and To are the stations' orbit records until installations give a station a key of its own.
[CultDocument("aetheria.haulorderdata", "1"), MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class HaulOrderData
{
[JsonProperty("from"), Key(0)] public CultRecordRef<OrbitData> From;
[JsonProperty("to"), Key(1)] public CultRecordRef<OrbitData> To;
[JsonProperty("goods"), Key(2)] public List<CultRecordRef<ItemData>> Goods = new List<CultRecordRef<ItemData>>();
// What stood this order up (scenario:<id>), so a reader can tell a staged order from one an office issues.
[JsonProperty("commitment"), Key(3)] public string Commitment;
public static CultRecordKey KeyOf(string id) => new CultRecordKey("haul-order:" + id);
}
// What a hauler last saw at its To station's door (ruling hauler-remembers-what-it-saw): the goods of its order that were refused there and
// when (zone time of the visit). The hauler's own knowledge, set at the door and read to choose its leg and its load; saved with it
// (EntityPack Key 25). A refusal lives HaulRun.RefusalLife seconds.
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class HaulSeen
{
[JsonProperty("refusals"), Key(0)] public List<HaulRefusal> Refusals = new List<HaulRefusal>();
// A copy no later visit changes: what a pack holds and what the ship holds are never one list.
public HaulSeen Copy() => new HaulSeen { Refusals = Refusals.Select(refusal => new HaulRefusal { Good = refusal.Good, At = refusal.At }).ToList() };
}
[MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class HaulRefusal
{
[JsonProperty("good"), Key(0)] public CultRecordRef<ItemData> Good;
[JsonProperty("at"), Key(1)] public double At;
// Element identity: minted by the cache on write; "" means unset.
[Key(2)] [CultElementId] public string Id = "";
}