From 34ce6e6719cdef1b2be1dd8694ecb64d11c05ce9 Mon Sep 17 00:00:00 2001 From: soul Date: Thu, 26 Nov 2026 17:14:11 +0100 Subject: [PATCH] Gear money rescale: divide gear, consumable and package hull prices by 100 through economy rescale; economy prices reads every price field (aetheria-living-world, cut gear-money-rescale r2) Equippable and Consumable prices in Aetheria.cc become round(p/100) (half away from zero, floor 1): 74 records, every ratio 100.0; commodities, ammo, missiles and mines keep their batch prices (ruling economy-numbers-are-sim-tuned-knobs). Nakovalnya 60000000 to 600000 through ShipAuthoringStore. StartingCredits 15000000 to 150000. DemoLoopIncomeToCostClosesAfterRescale pins the income-to-cost scale of the demo belt against the base measured before the ore batch. economy rescale is deleted in the next commit; economy prices stays. Co-Authored-By: Claude Sonnet 5.5 --- Assets/Scripts/ServerShared/Settings.cs | 2 +- GameData/Aetheria.cc | 4 +- GameData/Mods/aetheria.nakovalnya/ship.cc | 2 +- tests/Aetheria.Shared.Tests/DemoLoopTests.cs | 34 ++++++ .../EconomyRescaleTests.cs | 63 ++++++++++ .../StationServicesTests.cs | 2 +- tools/AetherDb/EconomyCommand.cs | 6 +- tools/AetherDb/EconomyPrices.cs | 65 ++++++++++ tools/AetherDb/EconomyRescale.cs | 112 ++++++++++++++++++ tools/AetherDb/Program.cs | 2 +- 10 files changed, 284 insertions(+), 8 deletions(-) create mode 100644 tests/Aetheria.Shared.Tests/EconomyRescaleTests.cs create mode 100644 tools/AetherDb/EconomyPrices.cs create mode 100644 tools/AetherDb/EconomyRescale.cs diff --git a/Assets/Scripts/ServerShared/Settings.cs b/Assets/Scripts/ServerShared/Settings.cs index 523e773f1..37bcc35ba 100644 --- a/Assets/Scripts/ServerShared/Settings.cs +++ b/Assets/Scripts/ServerShared/Settings.cs @@ -188,7 +188,7 @@ public class GameplaySettings public float SellFraction = .5f; // What a station charges to restore worn gear, as a fraction of the price of the wear. public float RepairFraction = .25f; - public int StartingCredits = 15000000; + public int StartingCredits = 150000; public float DurabilityQualityExponent = 2; public float DurabilityQualityMin = 2; public float DurabilityQualityMax = .25f; diff --git a/GameData/Aetheria.cc b/GameData/Aetheria.cc index 0a3ca6237..0ca750ba2 100644 --- a/GameData/Aetheria.cc +++ b/GameData/Aetheria.cc @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:59b539ef5e27f0f5ca961ba0220798f846d3996b1e59e7289ce760cb528cf32e -size 252092 +oid sha256:70b7ad2b77bd3a58b0ee34677e142b0aaeea23f8f5d1355b2fdbc545eb25c6ab +size 273831 diff --git a/GameData/Mods/aetheria.nakovalnya/ship.cc b/GameData/Mods/aetheria.nakovalnya/ship.cc index 1def7b776..c0f3c416c 100644 --- a/GameData/Mods/aetheria.nakovalnya/ship.cc +++ b/GameData/Mods/aetheria.nakovalnya/ship.cc @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:0228aa7ec3a2e060bd49e46aa64f52eea4c4cdb25951c164646c1d031ad17851 +oid sha256:f941afb95cac379b22347ab9465b7d95bd6fd2969e23e97d1b63721a2d97f800 size 30457 diff --git a/tests/Aetheria.Shared.Tests/DemoLoopTests.cs b/tests/Aetheria.Shared.Tests/DemoLoopTests.cs index 9007306ec..f306fd334 100644 --- a/tests/Aetheria.Shared.Tests/DemoLoopTests.cs +++ b/tests/Aetheria.Shared.Tests/DemoLoopTests.cs @@ -86,4 +86,38 @@ public sealed partial class RunStartTests Assert.Equal(0, credits); Assert.Contains(stock.piece, hold.Cargo.Keys); } + + // What a hold of belt ore earns against what the loop spends it on, on the shipped catalog (aetheria-living-world, ruling + // economy-numbers-are-sim-tuned-knobs: the prices are balance knobs tuned from simulation, so this pins only the scale). V is the + // belt kind's hold-cell value: a unit is drawn by abundance, a cell takes MaxStack units, so a cell's value is + // sum(abundance x price) / sum(abundance / MaxStack), over every yield of the kind. It is set against the repair of the player's hull + // with all its armour lost and against the cheapest piece Zenith stocks. The bases are those ratios on the catalog before the ore + // batch, at ore and gear prices of one scale: a divisor of ten or a thousand, or a gear type left unscaled, moves a ratio out of + // [0.5, 4] x its base. + // Measured at d1ff2f78e on belt kind Asteroid: V 9005, repair 5540402, cheapest buy 4705354. + private const double BaseRepairRatio = 0.00162533, BaseBuyRatio = 0.00191378; + + [Fact] + public void DemoLoopIncomeToCostClosesAfterRescale() + { + var (_, arena, staged, failures) = Launch(new DemoTerminus(), Inputs(() => 1)); + Assert.True(failures.Count == 0, string.Join("; ", failures)); + var player = staged.Player; + var belt = arena.Planets.Single(body => body.Value is AsteroidBeltData); + var kind = _cache.Get(((AsteroidBeltData) belt.Value).Kind); + var yields = kind.Yields.Select(y => (data: _cache.Get(y.Commodity), weight: (double) y.Abundance)).ToArray(); + var value = yields.Sum(y => y.weight * y.data.Price) / yields.Sum(y => y.weight / y.data.MaxStack); + + for (var x = 0; x < player.MaxArmor.GetLength(0); x++) + for (var y = 0; y < player.MaxArmor.GetLength(1); y++) + player.Armor[x, y] = 0; + var repair = StationServices.RepairCost(_items, player); + var zenith = arena.Entities.Single(entity => entity.HullData.Name == "Zenith"); + var cheapest = zenith.CargoBays.SelectMany(bay => bay.Cargo.Keys.OfType()).Min(piece => StationServices.BuyPrice(_items, piece)); + Assert.True(repair > 0 && cheapest > 0); + + var measured = $"belt {kind.Name}: V {value:0.###} per cell, repair {repair}, cheapest buy {cheapest}, V/repair {value / repair:0.######}, V/buy {value / cheapest:0.######}"; + Assert.True(value / repair >= 0.5 * BaseRepairRatio && value / repair <= 4 * BaseRepairRatio, measured); + Assert.True(value / cheapest >= 0.5 * BaseBuyRatio && value / cheapest <= 4 * BaseBuyRatio, measured); + } } diff --git a/tests/Aetheria.Shared.Tests/EconomyRescaleTests.cs b/tests/Aetheria.Shared.Tests/EconomyRescaleTests.cs new file mode 100644 index 000000000..9bb9ce8dd --- /dev/null +++ b/tests/Aetheria.Shared.Tests/EconomyRescaleTests.cs @@ -0,0 +1,63 @@ +using System; +using System.IO; +using System.Linq; +using GameCult.Caching; +using Newtonsoft.Json; +using Xunit; + +// The one-time price transform (aetheria-living-world, cut gear-money-rescale), on a fixture game folder. Deleted with the command. +public sealed class EconomyRescaleTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "aetheria-rescale-" + Guid.NewGuid().ToString("N")); + private string Catalog => Path.Combine(_root, "GameData", "Aetheria.cc"); + private string Package => Path.Combine(_root, "GameData", "Mods", "aetheria.wren", "ship.cc"); + + public void Dispose() => Directory.Delete(_root, true); + + // A catalog with a commodity, a gun, a hull, a cargo bay and a consumable at prices that exercise rounding, and the Wren package (6000). + private void Build() + { + Directory.CreateDirectory(Path.GetDirectoryName(Package)); + Directory.CreateDirectory(Path.GetDirectoryName(Catalog)); + File.Copy(Path.Combine(RunStartTests.FindRepoRoot(), "tests", "fixtures", "mods", "aetheria.wren", "ship.cc"), Package); + using var f = EconomyFixture.Healthy(); + f.EditItem("commodity:ore", ore => ore.Price = 777); + f.EditItem("gear:laser", gear => gear.Price = 12345); + f.EditItem("hull:skiff", hull => hull.Price = 250); + f.Cache.Upsert(typeof(CargoBayData), new CargoBayData { Name = "Bay", Shape = new Shape(), InteriorShape = new Shape(), Price = 30 }, new CultRecordKey("bay:small")); + f.Cache.Upsert(typeof(ConsumableItemData), new ConsumableItemData { Name = "Patch", Shape = new Shape(), Price = 18000 }, new CultRecordKey("consumable:patch")); + f.Cache.FlushAsync().GetAwaiter().GetResult(); + f.Cache.Dispose(); + File.Copy(f.CatalogPath, Catalog); + } + + private (int Price, string Json) Item(string key) where T : ItemData + { + using var cache = AetheriaStores.Open(Catalog, registry: TestCatalog.Registry()); + var item = cache.Get(new CultRecordKey(key)); + return (item.Price, JsonConvert.SerializeObject(item)); + } + + [Fact] + public void GearConsumablesAndPackagesScaleAndCommoditiesDoNot() + { + Build(); + var catalog = File.ReadAllBytes(Catalog); + var package = File.ReadAllBytes(Package); + var output = new StringWriter(); + + Assert.Equal(0, EconomyRescale.Apply(_root, 100, null, false, output)); + Assert.Equal(catalog, File.ReadAllBytes(Catalog)); + Assert.Equal(package, File.ReadAllBytes(Package)); + Assert.Contains("gear:laser", output.ToString()); + + var ore = Item("commodity:ore"); + Assert.Equal(0, EconomyRescale.Apply(_root, 100, null, true, new StringWriter())); + Assert.Equal(123, Item("gear:laser").Price); // 123.45 + Assert.Equal(3, Item("hull:skiff").Price); // 2.5 rounds away from zero + Assert.Equal(1, Item("bay:small").Price); // 0.3 floors at 1 + Assert.Equal(180, Item("consumable:patch").Price); + Assert.Equal(ore, Item("commodity:ore")); // untouched, field for field + Assert.Equal(60, ShipAuthoringStore.Load(Package).Hull.Price); + } +} diff --git a/tests/Aetheria.Shared.Tests/StationServicesTests.cs b/tests/Aetheria.Shared.Tests/StationServicesTests.cs index 3821a22b4..3930f836b 100644 --- a/tests/Aetheria.Shared.Tests/StationServicesTests.cs +++ b/tests/Aetheria.Shared.Tests/StationServicesTests.cs @@ -81,7 +81,7 @@ public sealed class StationServicesTests : IDisposable { Assert.Equal(.5f, _items.GameplaySettings.SellFraction); Assert.Equal(.25f, _items.GameplaySettings.RepairFraction); - Assert.Equal(15000000, _items.GameplaySettings.StartingCredits); + Assert.Equal(150000, _items.GameplaySettings.StartingCredits); } [Fact] diff --git a/tools/AetherDb/EconomyCommand.cs b/tools/AetherDb/EconomyCommand.cs index d49ea2bb0..24743b12d 100644 --- a/tools/AetherDb/EconomyCommand.cs +++ b/tools/AetherDb/EconomyCommand.cs @@ -53,7 +53,7 @@ public sealed class EconomyAuthor } } -// economy report | author ... [apply]: the one writer of economy content and a reader of the catalog's economy report. +// economy report | author ... [apply] | prices | rescale: the one writer of economy content and a reader of the catalog's economy report. // EconomyChecks owns every rule; this command only calls it. public static class EconomyCommand { @@ -63,7 +63,7 @@ public static class EconomyCommand { EconomyChecks.LRecipe, EconomyChecks.LLore, EconomyChecks.LProductive, EconomyChecks.LOneKindList, EconomyChecks.LWeights }; // A batch is compiled code under tools/AetherDb/Economy/ and runs with the operator's authority: reviewed code, never an input. - private const string Usage = "economy report | author ... [apply]\nA batch is reviewed code: it runs on a trial copy and must write only through EconomyAuthor."; + private const string Usage = "economy report | author ... [apply] | " + EconomyPrices.Usage + " | " + EconomyRescale.Usage + "\nA batch is reviewed code: it runs on a trial copy and must write only through EconomyAuthor."; public static int Run(string[] args, TextWriter output) { @@ -72,6 +72,8 @@ public static class EconomyCommand using var db = AetherDb.Open(); return Report(db.Cache, output); } + if (args.Length > 0 && args[0] == "prices") return EconomyPrices.Run(args.Skip(1).ToArray(), output); + if (args.Length > 0 && args[0] == "rescale") return EconomyRescale.Run(args.Skip(1).ToArray(), output); if (args.Length > 1 && args[0] == "author") { var apply = args.Contains("apply"); diff --git a/tools/AetherDb/EconomyPrices.cs b/tools/AetherDb/EconomyPrices.cs new file mode 100644 index 000000000..ef1fb7870 --- /dev/null +++ b/tools/AetherDb/EconomyPrices.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using GameCult.Caching; + +// economy prices [] [--mods ]: the reader of every price-bearing field. ItemData.Price on each record, +// OutsideMarketRow.Price, a package's hull price (every /*/ship.cc, GameData/Mods by default) and the purse the code +// defaults GameplaySettings.StartingCredits to. Given a second catalog it prints old, new and ratio (old over new) per record: the +// second catalog is the old side. Read-only. A package's old price is not in the second catalog, so a package prints its price alone. +public static class EconomyPrices +{ + public const string Usage = "economy prices [] [--mods ]"; + + public static int Run(string[] args, TextWriter output) + { + string other = null, mods = null; + for (var i = 0; i < args.Length; i++) + { + if (args[i] == "--mods" && i + 1 < args.Length) mods = args[++i]; + else if (other == null && !args[i].StartsWith("--", StringComparison.Ordinal)) other = args[i]; + else { output.WriteLine(Usage); return 1; } + } + using var db = AetherDb.Open(); + var now = Read(db.Cache, mods ?? Path.Combine(db.Root, "GameData", "Mods")); + if (other == null) + { + foreach (var (id, row) in now) output.WriteLine($"{id}\t{row.Label}\t{row.Price}"); + return 0; + } + using var then = AetheriaStores.Open(other); + var was = Read(then, null); + foreach (var id in now.Keys.Concat(was.Keys).Distinct().OrderBy(k => k, StringComparer.Ordinal)) + { + var hasOld = was.TryGetValue(id, out var old); + var hasNew = now.TryGetValue(id, out var current); + var ratio = hasOld && hasNew && current.Price != 0 ? (old.Price / (double) current.Price).ToString("0.####", CultureInfo.InvariantCulture) : "-"; + output.WriteLine($"{id}\t{(hasNew ? current.Label : old.Label)}\t{(hasOld ? old.Price.ToString(CultureInfo.InvariantCulture) : "-")}\t{(hasNew ? current.Price.ToString(CultureInfo.InvariantCulture) : "-")}\t{ratio}"); + } + return 0; + } + + // Every price-bearing field, by an id that names the field and the record. mods null reads the catalog alone: no packages and no purse, + // which the catalog does not hold. + public static SortedDictionary Read(CultCache catalog, string mods) + { + var rows = new SortedDictionary(StringComparer.Ordinal); + foreach (var item in catalog.GetAll()) + rows["item:" + catalog.RefOf(item).Key.Value] = ($"{item.GetType().Name} {item.Name}", item.Price); + foreach (var market in catalog.GetAll()) + foreach (var row in market.Rows ?? new List()) + if (row != null) + rows[$"market:{catalog.RefOf(market).Key.Value}:{row.Commodity.Key.Value}"] = ($"OutsideMarketRow {market.Name}", row.Price); + if (mods == null) return rows; + if (Directory.Exists(mods)) + foreach (var path in Directory.GetFiles(mods, "ship.cc", SearchOption.AllDirectories).OrderBy(p => p, StringComparer.Ordinal)) + { + var (hull, ship, _) = ShipAuthoringStore.Load(path); + rows["package:" + ship.Id] = ($"Package hull {hull.Name}", hull.Price); + } + rows["purse"] = ("GameplaySettings.StartingCredits (code default)", new GameplaySettings().StartingCredits); + return rows; + } +} diff --git a/tools/AetherDb/EconomyRescale.cs b/tools/AetherDb/EconomyRescale.cs new file mode 100644 index 000000000..ca04038d4 --- /dev/null +++ b/tools/AetherDb/EconomyRescale.cs @@ -0,0 +1,112 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using GameCult.Caching; + +// economy rescale [--mods ] [apply]: one transform that divides every gear, consumable and package hull price by the +// divisor (aetheria-living-world, cut gear-money-rescale). Equippable and Consumable items are gear scale; commodities are already +// ore scale and are not touched. Each price becomes round(price / divisor), half away from zero, never below 1. The catalog goes +// through EconomyCommand.Author's trial copy and swap, the packages through ShipAuthoringStore Load and Write. The dry run prints +// every price that moves, read through EconomyPrices. Deleted in the commit after it applies. +public static class EconomyRescale +{ + public const string Usage = "economy rescale [--mods ] [apply]"; + + public static int Run(string[] args, TextWriter output) + { + var apply = args.Contains("apply"); + string mods = null; + var rest = new List(); + for (var i = 0; i < args.Length; i++) + { + if (args[i] == "apply") continue; + if (args[i] == "--mods" && i + 1 < args.Length) mods = args[++i]; + else rest.Add(args[i]); + } + if (rest.Count != 1 || !int.TryParse(rest[0], NumberStyles.None, CultureInfo.InvariantCulture, out var divisor) || divisor < 2) + { + output.WriteLine(Usage); + return 1; + } + return Apply(AetherDb.FindRoot(), divisor, mods, apply, output); + } + + // The transform on the game folder at root: dry run unless apply. + public static int Apply(string root, int divisor, string mods, bool apply, TextWriter output) + { + var catalogPath = Path.Combine(root, "GameData", "Aetheria.cc"); + mods ??= Path.Combine(root, "GameData", "Mods"); + + // The catalog: the transform runs on a scratch copy first, so the table below is what the real run writes. + var scratch = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "aetherdb-rescale-" + Guid.NewGuid().ToString("N"))).FullName; + try + { + var copy = Path.Combine(scratch, "Aetheria.cc"); + File.Copy(catalogPath, copy); + new FileInfo(copy).IsReadOnly = false; + var trialOutput = new StringWriter(); + if (EconomyCommand.Author(copy, new List { new Divide(divisor) }, true, trialOutput) != 0) + { + output.WriteLine(trialOutput.ToString()); + return 1; + } + using (var before = AetheriaStores.Open(catalogPath)) + using (var after = AetheriaStores.Open(copy)) + { + var was = EconomyPrices.Read(before, null); + var now = EconomyPrices.Read(after, null); + foreach (var (id, row) in was) + if (now[id].Price != row.Price) output.WriteLine($"{id}\t{row.Label}\t{row.Price}\t{now[id].Price}"); + } + } + finally { Directory.Delete(scratch, true); } + + var packages = Directory.Exists(mods) ? Directory.GetFiles(mods, "ship.cc", SearchOption.AllDirectories).OrderBy(p => p, StringComparer.Ordinal).ToArray() : new string[0]; + foreach (var path in packages) + { + var (hull, ship, _) = ShipAuthoringStore.Load(path); + output.WriteLine($"package:{ship.Id}\tPackage hull {hull.Name}\t{hull.Price}\t{Scale(hull.Price, divisor)}"); + } + if (!apply) + { + output.WriteLine("\nDry run. Pass \"apply\" to write Aetheria.cc and the packages. The purse is GameplaySettings.StartingCredits in Settings.cs."); + return 0; + } + var code = EconomyCommand.Author(catalogPath, new List { new Divide(divisor) }, true, TextWriter.Null); + if (code != 0) return code; + foreach (var path in packages) + { + var (hull, ship, _) = ShipAuthoringStore.Load(path); + hull.Price = Scale(hull.Price, divisor); + using var cache = ShipAuthoringStore.Open(path, writable: true); + ShipAuthoringStore.Write(cache, hull, ship); + cache.FlushAsync().Wait(); + } + output.WriteLine($"\nWrote Aetheria.cc and {packages.Length} package(s)."); + return 0; + } + + // Half away from zero, never below 1 for a priced item; an unpriced one stays unpriced. + private static int Scale(int price, int divisor) => + price <= 0 ? price : Math.Max(1, (int) Math.Round(price / (double) divisor, MidpointRounding.AwayFromZero)); + + private sealed class Divide : EconomyBatch + { + private readonly int _divisor; + public Divide(int divisor) => _divisor = divisor; + + public override void Author(EconomyAuthor author) + { + var catalog = author.Catalog; + foreach (var item in catalog.GetAll().Where(i => i is EquippableItemData || i is ConsumableItemData) + .OrderBy(i => catalog.RefOf(i).Key.Value, StringComparer.Ordinal).ToArray()) + { + item.Price = Scale(item.Price, _divisor); + // The record's own type, so the cache's write ownership by type holds. + author.Put((dynamic) item, catalog.RefOf(item).Key); + } + } + } +} diff --git a/tools/AetherDb/Program.cs b/tools/AetherDb/Program.cs index e3f1a438f..92e7c5cdc 100644 --- a/tools/AetherDb/Program.cs +++ b/tools/AetherDb/Program.cs @@ -81,7 +81,7 @@ public static class Program case "auto-guns": return AutoGunsCatalog.Run(AetherDb.Open(catalogWritable: args.Contains("apply")).Cache, args.Contains("apply"), Console.Out); case "doctrine-catalog": return DoctrineCatalog.Run(AetherDb.Open(catalogWritable: args.Contains("apply")).Cache, args.Contains("apply"), Console.Out); default: - Console.WriteLine("commands: census, factions, station-fit, hardpoint-fit, loadout [seed], loadout-commit [,,,[@]]... [--group ,...]... [--replace] [--boss-of ], save, settings, settings-dump, dangling [clear ]... [apply], shield-migrate [apply], brownout-migrate [apply], roles-migrate [apply], firing-arc-migrate [apply], range-falloff [apply] [--effective ] [--end ], targeting-catalog [apply], targeting-catalog-6c [apply], targeting-catalog-6d [apply], ship-authoring create|inspect|validate|compose, mine-launcher [apply], smoke-hull [apply], smoke-rounds [apply], roles-backfill [apply], pd-gear [apply], consumables-first-set [apply], launch-suppressor [apply], pirates-faction [apply], verse-grammar [apply], generic-designs [apply], sensor-stat-set [apply], inspection-scanner [apply], minor-power-factions [apply], place-names [apply], product-lines weapons|minor-powers|gear|tiers [apply], doctrine-catalog [apply], auto-guns [apply], assembly-from-maker [apply], station-kinds [hull \"\" ] [apply], economy report|author ... [apply]"); + Console.WriteLine("commands: census, factions, station-fit, hardpoint-fit, loadout [seed], loadout-commit [,,,[@]]... [--group ,...]... [--replace] [--boss-of ], save, settings, settings-dump, dangling [clear ]... [apply], shield-migrate [apply], brownout-migrate [apply], roles-migrate [apply], firing-arc-migrate [apply], range-falloff [apply] [--effective ] [--end ], targeting-catalog [apply], targeting-catalog-6c [apply], targeting-catalog-6d [apply], ship-authoring create|inspect|validate|compose, mine-launcher [apply], smoke-hull [apply], smoke-rounds [apply], roles-backfill [apply], pd-gear [apply], consumables-first-set [apply], launch-suppressor [apply], pirates-faction [apply], verse-grammar [apply], generic-designs [apply], sensor-stat-set [apply], inspection-scanner [apply], minor-power-factions [apply], place-names [apply], product-lines weapons|minor-powers|gear|tiers [apply], doctrine-catalog [apply], auto-guns [apply], assembly-from-maker [apply], station-kinds [hull \"\" ] [apply], economy report|prices|rescale|author ... [apply]"); return 1; } }