diff --git a/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs b/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs index 133de8e3a..ad8f6dbef 100644 --- a/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs +++ b/Assets/Scripts/ServerShared/Behaviors/Behaviors.cs @@ -196,6 +196,7 @@ public interface IPowerConsumer Union(51, typeof(ScannerData)), Union(52, typeof(LockWeaponData)), Union(53, typeof(FacilityData)), + Union(54, typeof(HabitationData)), JsonObject(MemberSerialization.OptIn)] public abstract class BehaviorData { diff --git a/Assets/Scripts/ServerShared/Behaviors/Habitation.cs b/Assets/Scripts/ServerShared/Behaviors/Habitation.cs new file mode 100644 index 000000000..3e2c56e56 --- /dev/null +++ b/Assets/Scripts/ServerShared/Behaviors/Habitation.cs @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using GameCult.Caching; +using MessagePack; +using Newtonsoft.Json; + +// The habitation gear a station carries to house a population: a GearData whose Behaviors hold one of these. The design says how many +// it houses and what each occupant consumes, so a population is installed gear like a facility is (rulings +// installed-gear-decides-what-a-station-buys, mass-populations-live-in-blooms): there is no population record and no needs table +// outside the module design. A station's Crew Quarters and a habitat's Housing Districts are designs of it. Installed gear, never a +// consumable's effect. +[Inspectable, MessagePackObject, JsonObject(MemberSerialization.OptIn)] +public class HabitationData : BehaviorData +{ + // The occupants the unit houses when full: what a unit with no recorded population holds, and, until population dynamics moves + // it, what it holds always. + [Inspectable, JsonProperty("capacity"), Key(1)] + public int Capacity; + + // What each occupant consumes: one row per commodity. + [Inspectable, JsonProperty("table"), Key(2)] + public List Table = new List(); + + public override Behavior CreateInstance(EquippedItem item) + { + return new Habitation(this, item); + } + public override Behavior CreateInstance(ConsumableItemEffect item) + { + throw new InvalidOperationException($"{item.Data.Name} cannot carry a habitation module: a habitation module is installed gear, never a consumable effect."); + } +} + +// One commodity a population eats: units per occupant per sim hour, and whether the occupants cannot do without it (Basic) or it is +// a lifestyle good. Basic is recorded for the follow-up that makes a shortfall matter; this cut reads it nowhere. +[MessagePackObject, JsonObject(MemberSerialization.OptIn)] +public class HabitationRow +{ + [JsonProperty("commodity"), Key(0)] public CultRecordRef Commodity; + [JsonProperty("perOccupantHour"), Key(1)] public float PerOccupantHour; + [JsonProperty("basic"), Key(2)] public bool Basic; + + // Element identity: minted by the cache on write; "" means unset. + [Key(3)] [CultElementId] public string Id = ""; +} + +// The population an installed habitation unit houses, on the unit (EquippableItem.Habitants): its size and, per table row, the +// fraction of a unit its occupants have consumed and not yet taken. Written only by Habitation.Execute from Upkeep.Advance's result. +[MessagePackObject, JsonObject(MemberSerialization.OptIn)] +public class Habitants +{ + [JsonProperty("size"), Key(0)] public double Size; + // By table row. Always a fraction below one between steps: whole units are taken, or dropped when the hold lacks them. + [JsonProperty("owed"), Key(1)] public double[] Owed = Array.Empty(); +} + +// The one rule for what a population consumes: the occupants of a unit accrue Size x rate x seconds / 3600 of each row, the hold is +// asked for the whole units, and a unit the hold cannot give is dropped, never carried as a debt (idea planets-blooms-map.rejected-carry-unmet-debt). +// On screen its one caller is Habitation.Execute with one zone step; off screen RegionClock.AdvanceInstalled calls that with the span +// the zone missed. It reads no random, no clock and no crew. +public static class Upkeep +{ + // The population after `seconds`, and the rows of the table that went short (a row whose hold gave fewer whole units than the + // occupants owed). A null state is a unit that has not stepped yet: full capacity, nothing owed. Pure over its arguments but for the + // hold it takes from. + public static (Habitants state, IReadOnlyList shortfall) Advance(HabitationData data, Habitants state, double seconds, IProductionHold hold) + { + var size = state?.Size ?? data.Capacity; + if (!(seconds > 0)) seconds = 0; + var owed = new double[data.Table.Count]; + var shortfall = new List(); + for (var at = 0; at < owed.Length; at++) + { + var row = data.Table[at]; + var was = state?.Owed != null && at < state.Owed.Length ? state.Owed[at] : 0; + owed[at] = was + size * row.PerOccupantHour * seconds / 3600; + var whole = (int) Math.Floor(owed[at]); + if (whole <= 0 || !row.Commodity.IsSet()) continue; + var key = row.Commodity.Key; + var taken = whole; + if (!hold.TryTake(new[] { (key, whole) })) + { + taken = Math.Min(whole, hold.Held(key)); + if (taken > 0 && !hold.TryTake(new[] { (key, taken) })) taken = 0; + shortfall.Add(key); + } + owed[at] -= whole; + } + return (new Habitants { Size = size, Owed = owed }, shortfall); + } +} + +// The installed habitation unit. 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. It takes from the same hold a facility does. +public class Habitation : Behavior +{ + private readonly HabitationData _data; + private EntityHold _hold; + + // The commodities the last step could not fully take: derived by Execute every step, never stored on the unit. + public IReadOnlyList Shortfall { get; private set; } = Array.Empty(); + + public Habitation(HabitationData data, EquippedItem item) : base(data, item) + { + _data = data; + } + + public override bool Execute(float dt) + { + _hold ??= new EntityHold(Entity); + var (state, shortfall) = Upkeep.Advance(_data, Item.EquippableItem.Habitants, dt, _hold); + Item.EquippableItem.Habitants = state; + Shortfall = shortfall; + return true; + } +} diff --git a/Assets/Scripts/ServerShared/Behaviors/Habitation.cs.meta b/Assets/Scripts/ServerShared/Behaviors/Habitation.cs.meta new file mode 100644 index 000000000..caff50143 --- /dev/null +++ b/Assets/Scripts/ServerShared/Behaviors/Habitation.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4066805b976ae8b493827f0cefb1a1d0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/ServerShared/ItemInstance.cs b/Assets/Scripts/ServerShared/ItemInstance.cs index 6e94cc049..513568ece 100644 --- a/Assets/Scripts/ServerShared/ItemInstance.cs +++ b/Assets/Scripts/ServerShared/ItemInstance.cs @@ -100,6 +100,10 @@ public class EquippableItem : CraftedItemInstance // A facility's cycle in progress: per-unit installation state like PowerTier, null on everything but a facility that has started // a cycle. Its one writer is Facility.Execute, storing Production.Advance's result. 13 is CompoundCommodity's, so 14. [JsonProperty("run"), Key(14)] public FacilityRun Run; + + // The population a habitation unit houses: per-unit installation state like Run, null on everything but a habitation unit that has + // stepped. Its one writer is Habitation.Execute, storing Upkeep.Advance's result. 13 is CompoundCommodity's and 14 is Run, so 15. + [JsonProperty("habitants"), Key(15)] public Habitants Habitants; } [MessagePackObject, JsonObject(MemberSerialization.OptIn)] diff --git a/Assets/Scripts/ServerShared/RegionClock.cs b/Assets/Scripts/ServerShared/RegionClock.cs index 03b7b4cca..195ecfedd 100644 --- a/Assets/Scripts/ServerShared/RegionClock.cs +++ b/Assets/Scripts/ServerShared/RegionClock.cs @@ -49,16 +49,16 @@ public static class RegionClock public static ZonePack Seen(GalaxyZone zone, Zone current) => zone.Contents != null && zone.Contents == current ? current.PackZone() : zone.LastSeen; - // The entity's installed plant runs `seconds`, as EquippedItem.Update runs it each step: a unit that is enabled and not - // destroyed (Active also needs ThermalOnline, which only a stepped entity sets, so it is not the off-screen gate). The - // units in Equipment order, each unit's Facility behaviours in order. + // The entity's installed plant and populations run `seconds`, as EquippedItem.Update runs them each step: a unit that is enabled + // and not destroyed (Active also needs ThermalOnline, which only a stepped entity sets, so it is not the off-screen gate). The + // units in Equipment order, each unit's Facility and Habitation behaviours in order. public static void AdvanceInstalled(Entity entity, double seconds) { foreach (var unit in entity.Equipment) { if (!unit.Enabled.Value || unit.EquippableItem.IsDestroyed) continue; foreach (var behavior in unit.Behaviors) - if (behavior is Facility facility) facility.Execute((float) seconds); + if (behavior is Facility || behavior is Habitation) behavior.Execute((float) seconds); } } } diff --git a/Assets/Scripts/ServerShared/Zone.cs b/Assets/Scripts/ServerShared/Zone.cs index cfd2801c8..7514a9f9c 100644 --- a/Assets/Scripts/ServerShared/Zone.cs +++ b/Assets/Scripts/ServerShared/Zone.cs @@ -363,7 +363,7 @@ public class Zone private bool IsExpired(ChunkWear wear) => wear.Damage <= 0f && (!wear.BrokenUntil.HasValue || wear.BrokenUntil.Value <= _time); - // A zone the player is not in, brought to `time` (RegionClock.Step and Enter only): its installed plant runs the span it missed, + // A zone the player is not in, brought to `time` (RegionClock.Step and Enter only): its facilities and populations run the span it missed, // its clock moves, and every orbit is placed at the new time so the next Update differences from it, not from where the // zone was left. public void AdvanceTo(double time) diff --git a/tests/Aetheria.Shared.Tests/HabitationTests.cs b/tests/Aetheria.Shared.Tests/HabitationTests.cs new file mode 100644 index 000000000..ef054fa93 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/HabitationTests.cs @@ -0,0 +1,252 @@ +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; + +// A population is installed gear (aetheria-living-world, cut habitation-gear; rulings installed-gear-decides-what-a-station-buys, +// mass-populations-live-in-blooms): HabitationData names a capacity and a table, Upkeep.Advance is the one rule for what the occupants +// take, and Habitation.Execute is the one writer of the unit's Habitants. The fixture seats a test Crew Quarters by hand on a station +// of its own, over the booted catalog, and steps Zone.Update by SimClock.GameStep, the on-screen clock. +public sealed class HabitationTests : IDisposable +{ + // Occupants and rates of the fixture design: per occupant per hour, a ratio of six, so spans of 3.75 s add exactly. + private const int Capacity = 20; + private const float WaterRate = 90f, AirRate = 15f; + + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-habitation-" + Guid.NewGuid().ToString("N")); + private readonly CultCache _cache; + private readonly CultRecordKey _water, _air; + + public HabitationTests() + { + 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); + _water = Commodity("Test Water"); + _air = Commodity("Test Air"); + _cache.Upsert(new HullData + { + Name = "Test Berth", HullType = HullType.Station, Shape = Solid(8, 8), Price = 1, Durability = 10, Mass = 1000 + }); + _cache.Upsert(new CargoBayData { Name = "Test Crate", Shape = new Shape(), InteriorShape = Solid(4, 4), Price = 20, Durability = 4 }); + // The thermal band of every installed design (Facilities): wide enough that a station's cells are inside it, so the unit is Active. + _cache.Upsert(new GearData + { + Name = "Test Crew Quarters", Shape = Solid(2, 2), Price = 1, Durability = 100, Hardpoint = HardpointType.Tool, + MinimumTemperature = -1, MaximumTemperature = 1000, OptimalTemperature = 280, PlateauWidth = 560, + Behaviors = { Table() } + }); + } + + 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 CultRecordKey Commodity(string name) + { + var design = new SimpleCommodityData { Name = name, Shape = new Shape(), Price = 1, MaxStack = 100 }; + _cache.Upsert(design); + return _cache.RefOf(design).Key; + } + + private HabitationData Table() => new HabitationData + { + Capacity = Capacity, + Table = + { + new HabitationRow { Commodity = new CultRecordRef(_water), PerOccupantHour = WaterRate, Basic = true }, + new HabitationRow { Commodity = new CultRecordRef(_air), PerOccupantHour = AirRate, Basic = true } + } + }; + + // A hold that is a ledger, as the strategic tick's is: whole or nothing. + private sealed class Ledger : IProductionHold + { + public readonly Dictionary Units = new Dictionary(); + public int Held(CultRecordKey design) => Units.TryGetValue(design, out var held) ? held : 0; + public bool TryTake(IReadOnlyList<(CultRecordKey design, int units)> units) + { + if (units.Any(entry => Held(entry.design) < entry.units)) return false; + foreach (var (design, count) in units) Units[design] = Held(design) - count; + return true; + } + public bool TryPut(CultRecordKey design, int units) { Units[design] = Held(design) + units; return true; } + public int Room(CultRecordKey design) => int.MaxValue; + } + + private Ledger Stocked(int water, int air) => new Ledger { Units = { [_water] = water, [_air] = air } }; + + // Runs the spans through Upkeep.Advance, carrying the state as Habitation.Execute does. + private (Habitants state, IReadOnlyList last) Run(Ledger hold, Habitants state, params double[] spans) + { + IReadOnlyList last = new CultRecordKey[0]; + foreach (var span in spans) (state, last) = Upkeep.Advance(Table(), state, span, hold); + return (state, last); + } + + [Fact] + public void ConsumesByTableAndSize() + { + // 15 s of twenty occupants: water 20 x 90 x 15 / 3600 = 7.5, air 20 x 15 x 15 / 3600 = 1.25. + var whole = Stocked(100, 100); + Run(whole, null, 15); + Assert.Equal((93, 99), (whole.Held(_water), whole.Held(_air))); + + // The same total in four spans of 3.75 s takes the same whole units: the fraction of a span is kept, not rounded away. + var split = Stocked(100, 100); + Run(split, null, 3.75, 3.75, 3.75, 3.75); + Assert.Equal((93, 99), (split.Held(_water), split.Held(_air))); + + // Size scales the rate: a population of one takes a twentieth, so 240 s of one takes what 12 s of twenty does. + var small = Stocked(100, 100); + Upkeep.Advance(Table(), new Habitants { Size = 1, Owed = new double[2] }, 240, small); + Assert.Equal((94, 99), (small.Held(_water), small.Held(_air))); + + // 1440 s of twenty takes 20 x 90 x 0.4 = 720 water and 120 air. + var day = Stocked(1000, 1000); + Run(day, null, Enumerable.Repeat(3.75, 384).ToArray()); + Assert.Equal((1000 - 720, 1000 - 120), (day.Held(_water), day.Held(_air))); + } + + [Fact] + public void UnmetUnitsAreDroppedNotOwed() + { + // A hold with no water: the water row is short, the air row is not, and nothing is carried as a debt (a minute owes 30 water). + var hold = Stocked(0, 100); + var (state, shortfall) = Run(hold, null, 60); + Assert.Equal(new[] { _water }, shortfall); + Assert.Equal(0, hold.Held(_water)); + Assert.Equal(95, hold.Held(_air)); + Assert.All(state.Owed, owed => Assert.InRange(owed, 0, 1)); + + // Restocked, the next minute takes that minute's 30 units and not the 60 an unpaid first minute would have left. + hold.Units[_water] = 100; + (state, shortfall) = Upkeep.Advance(Table(), state, 60, hold); + Assert.Empty(shortfall); + Assert.Equal(70, hold.Held(_water)); + + // Short of part of the row: what the hold has is taken, and the row is reported short. + var partial = Stocked(10, 100); + (_, shortfall) = Run(partial, null, 60); + Assert.Equal(new[] { _water }, shortfall); + Assert.Equal(0, partial.Held(_water)); + } + + [Fact] + public void NullStateIsFullCapacity() + { + var hold = Stocked(100, 100); + var (state, _) = Upkeep.Advance(Table(), null, 60, hold); + Assert.Equal(Capacity, state.Size); + Assert.Equal(70, hold.Held(_water)); + Assert.Equal(95, hold.Held(_air)); + + // On a seated unit the first step writes Habitants, and it is the one writer. + var world = Build(); + Assert.Null(world.Unit.Habitants); + Step(world, 1); + Assert.NotNull(world.Unit.Habitants); + Assert.Equal(Capacity, world.Unit.Habitants.Size); + } + + private sealed class World + { + public ItemManager Items; + public Zone Zone; + public OrbitalEntity Station; + public EquippableItem Unit; + public EntityHold Hold; + } + + private EquippableItem Mint(ItemManager items, string design) + { + var data = _cache.GetByName(design); + return new EquippableItem + { + Data = _cache.RefOf(data), + Durability = data.Durability, + Lot = items.Lots.Add(new Lot { Design = _cache.RefOf(data), Origin = new Attributed(), Quality = .5f, Roles = new List() }) + }; + } + + // A station with the test Crew Quarters in its interior and a crate holding 400 of each good. + private World Build() + { + var items = new ItemManager(1u, _cache, new ProvenanceLedger(), RunSaveTests.TestSettings(), _ => { }); + var zone = new Zone(items, new PlanetSettings(), new ZonePack(), new GalaxyZone { Name = "Test Zone", Owner = null }, null); + var station = new OrbitalEntity(items, zone, Mint(items, "Test Berth"), default, new EntitySettings()); + Assert.True(station.TryEquip(Mint(items, "Test Crew Quarters"), new int2(2, 2))); + Assert.True(station.TryEquip(Mint(items, "Test Crate"), new int2(4, 4))); + zone.Admit(station, piloted: false); + foreach (var good in new[] { _water, _air }) + for (var chunk = 0; chunk < 4; chunk++) + Assert.True(station.CargoBays[0].TryStore(new SimpleCommodity { Data = new CultRecordRef(good), Quantity = 100 })); + return new World + { + Items = items, Zone = zone, Station = station, Hold = new EntityHold(station), + Unit = station.Equipment.First(unit => unit.Behaviors.OfType().Any()).EquippableItem + }; + } + + private static void Step(World world, int steps) + { + for (var at = 0; at < steps; at++) world.Zone.Update(SimClock.GameStep); + } + + [Fact] + public void OffScreenMatchesOnScreen() + { + // 120 sim seconds: on screen, one zone step at a time; off screen, two spans of 60 s through RegionClock.AdvanceInstalled. + var onScreen = Build(); + var offScreen = Build(); + Step(onScreen, (int) Math.Round(120 / SimClock.GameStep)); + RegionClock.AdvanceInstalled(offScreen.Station, 60); + RegionClock.AdvanceInstalled(offScreen.Station, 60); + foreach (var (good, rate) in new[] { (_water, WaterRate), (_air, AirRate) }) + { + var taken = 400 - offScreen.Hold.Held(good); + Assert.True(taken > 0, "an off-screen population that takes nothing proves nothing"); + Assert.InRange(400 - onScreen.Hold.Held(good), taken - 1, taken + 1); + } + Assert.True(onScreen.Unit.Habitants != null && offScreen.Unit.Habitants != null); + } + + [Fact] + public void HabitantsRoundTrip() + { + var world = Build(); + Step(world, 10); + world.Unit.Habitants = new Habitants { Size = 17, Owed = new[] { .25, .5 } }; + var options = CultDocumentMessagePackSerialization.OptionsFor(typeof(HullData).Assembly); + + // The unit as the run stores it: saved mid-span, restored with the same size and the same fractions owed. + var restored = MessagePackSerializer.Deserialize(MessagePackSerializer.Serialize(world.Unit, options), options); + Assert.Equal(17, restored.Habitants.Size); + Assert.Equal(new[] { .25, .5 }, restored.Habitants.Owed); + + // A unit stored before the cut has no key 15: the array ends at 14 and Habitants reads null. The current form's last + // element is Habitants, so the older form is the same array without it. + world.Unit.Habitants = null; + var current = MessagePackSerializer.Serialize(world.Unit, options); + Assert.Equal(new byte[] { 0xdc, 0x00, 0x10 }, current.Take(3)); + Assert.Equal(0xc0, current[^1]); + var precut = new byte[] { 0x9f }.Concat(current.Skip(3).Take(current.Length - 4)).ToArray(); + Assert.Null(MessagePackSerializer.Deserialize(precut, options).Habitants); + } +}