From 8a31099d991b4971467599059012c0e568db25d9 Mon Sep 17 00:00:00 2001 From: Nibu Date: Thu, 12 Nov 2026 23:05:07 +0000 Subject: [PATCH] Mining 5a: a worn rock pays the shooter in ore at the wear site from the shot's dice; overflow floats Co-Authored-By: Claude Sonnet 5.5 --- Assets/Resources/Settings.asset | 4 +- Assets/Scripts/ServerShared/FireControl.cs | 76 +++++- Assets/Scripts/ServerShared/Settings.cs | 5 + Assets/Scripts/ServerShared/SimulationDice.cs | 3 + .../Aetheria.Shared.Tests/MiningCut3Tests.cs | 2 + .../Aetheria.Shared.Tests/MiningCut4bTests.cs | 10 +- .../Aetheria.Shared.Tests/MiningCut5aTests.cs | 245 ++++++++++++++++++ 7 files changed, 332 insertions(+), 13 deletions(-) create mode 100644 tests/Aetheria.Shared.Tests/MiningCut5aTests.cs diff --git a/Assets/Resources/Settings.asset b/Assets/Resources/Settings.asset index 46bee7272..c12d32c99 100644 --- a/Assets/Resources/Settings.asset +++ b/Assets/Resources/Settings.asset @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:7f09c54dfdb87dffd76fa92365d62c53ce333457b89ccf8ead09093ffffedc42 -size 12525 +oid sha256:711ded55b95c512e3803df7682e44f0a9bb83ad36a384432781dc12dc5dadf0a +size 12630 diff --git a/Assets/Scripts/ServerShared/FireControl.cs b/Assets/Scripts/ServerShared/FireControl.cs index 6cd860ab3..3df60cf50 100644 --- a/Assets/Scripts/ServerShared/FireControl.cs +++ b/Assets/Scripts/ServerShared/FireControl.cs @@ -7,6 +7,7 @@ using System.Buffers; using System.Collections.Generic; using System.Linq; using CultMath; +using GameCult.Caching; using static CultMath.math; using float2 = CultMath.float2; using float3 = CultMath.float3; @@ -1234,7 +1235,7 @@ public static class FireControl // Detonate is still the one blast path. if (shot.Outcome.Result == ShotResult.Burst || shot.Fuse == WeaponFuse.Proximity) { - Detonate(zone, shot.Outcome.BurstPoint, shot.BlastRadius, shot.Damage, shot.DamageType); + Detonate(zone, shot.Outcome.BurstPoint, shot.BlastRadius, shot.Damage, shot.DamageType, shot); return; } @@ -1270,11 +1271,12 @@ public static class FireControl var direction = float3(shot.TravelDirection.x, 0, shot.TravelDirection.y); var surface = centre - shot.TravelDirection * zone.ChunkRadius(rock); Publish(zone.ChunkCapabilities, AbsorbLayer.Hull, float3(surface.x, 0f, surface.y), direction, shot.Damage, shot.DamageType); - zone.Wear(rock, shot.Damage); + var absorbed = zone.Wear(rock, shot.Damage); + Extract(zone, rock, absorbed, shot.Source, SimulationDice.For(zone.DropSeed, SimulationDice.OreStream, (uint) shot.ShotId)); return; } var point = Armed(shot.FireOrigin, shot.TravelDirection, shot.BlastRadius, float3(centre.x, shot.FireOrigin.y, centre.y)).xz; - Detonate(zone, point, shot.BlastRadius, shot.Damage, shot.DamageType); + Detonate(zone, point, shot.BlastRadius, shot.Damage, shot.DamageType, shot); } // Cut 12.3 (docs/fire-control-cut.md, "How a direct hit travels"): replaces Entity.ApplyHit's 0.5-step @@ -1413,7 +1415,7 @@ public static class FireControl // the muzzle than the blast radius is detonated on at the radius, along the round's own flight line. var hullPoint = target.ToWorldPoint(schematicPoint); var worldPoint = Armed(shot.FireOrigin, shot.TravelDirection, shot.BlastRadius, float3(hullPoint.x, shot.FireOrigin.y, hullPoint.y)).xz; - Detonate(target.Zone, worldPoint, shot.BlastRadius, shot.Damage, shot.DamageType); + Detonate(target.Zone, worldPoint, shot.BlastRadius, shot.Damage, shot.DamageType, shot); } // Cut 12.4(b) (docs/fire-control-cut.md, "The penetrator", Q12-8): the one penetration-reach owner, moved @@ -1715,7 +1717,7 @@ public static class FireControl // call: doing so would buy no behaviour, per ProbeC in the cut doc). Leftovers -- unoccupied-cell shares, // and whatever an item's pool does not absorb -- join one entity-wide hull total, applied through one // DamageHull call. - public static void Detonate(Zone zone, float2 worldPlanar, float radius, float damage, DamageType damageType) + public static void Detonate(Zone zone, float2 worldPlanar, float radius, float damage, DamageType damageType, PendingShot? shot = null) { // No distance prefilter: RectDiskOverlap is the one decider of whether the disc touches a hull. A // prefilter measured from Position (the centre of mass) with the bounding box's half-diagonal is not a @@ -1804,6 +1806,9 @@ public static class FireControl return byField != 0 ? byField : a.Target.Chunk.Value.Index.CompareTo(b.Target.Chunk.Value.Index); }); var discArea = PI * radius * radius; + // Mining Cut 5a: a shot's blast pays its Source for the rocks it wears, from the shot's own dice, once for the + // blast, drawn in the rock order above. A mine (no shot) wears rocks and yields nothing. + var dice = shot != null ? SimulationDice.For(zone.DropSeed, SimulationDice.OreStream, (uint) shot.Value.ShotId) : default; foreach (var rock in rocks) { var chunk = rock.Target.Chunk.Value; @@ -1812,7 +1817,66 @@ public static class FireControl var share = damage * CircleCircleOverlap(length(centre - worldPlanar), radius, zone.ChunkRadius(chunk)) / discArea; if (!(share > 0f)) continue; PublishBlast(zone.ChunkCapabilities, centre, 0f, worldPlanar, AbsorbLayer.Hull, share, damageType); - zone.Wear(chunk, share); + var absorbed = zone.Wear(chunk, share); + if (shot != null) Extract(zone, chunk, absorbed, shot.Value.Source, dice); + } + } + + // Mining Cut 5a: the one loot owner of a rock. A worn rock pays the shooter at the wear site, at arrival or detonation, + // from the shot's own dice: the damage it absorbed is that fraction of its hitpoints, and the same fraction of the + // units its size authors (AsteroidYield), so a rock pays its whole yield however many hits break it. Whole units, and + // one Bernoulli draw on the fraction. Each unit draws an ore by weight: the belt's yields for this province, scaled by + // exp(variance x g), g a stable hash of (field, index, ore) in [-1, 1) -- a rock's composition, derived here every call + // and never stored. A shot with no Source (a mine) yields nothing. The units go to the shooter's cargo bays in + // stacks; what does not fit, or everything when the shooter has left the zone, floats at the rock (ruling + // mining-overflow-floats). + // Draw order: the Bernoulli, then one draw per unit. + public static void Extract(Zone zone, ChunkId chunk, float absorbed, Entity shooter, Random dice) + { + if (shooter == null || !(absorbed > 0f)) return; + var settings = zone.Settings; + var belt = zone.AsteroidBelts[chunk.Field]; + var catalog = shooter.ItemManager.ItemData; + var ores = FieldKinds.Yield(belt.Data.Kind, zone.GalaxyZone?.Province?.Type ?? default, catalog); + if (ores.Length == 0) return; + + var size = belt.Data.Asteroids[chunk.Index].Size; + var owed = absorbed / settings.AsteroidHitpoints.Evaluate(size) * settings.AsteroidYield.Evaluate(size); + var units = (int) floor(owed); + if (dice.NextFloat() < owed - units) units++; + if (units == 0) return; + + var weights = new float[ores.Length]; + var total = 0f; + for (var i = 0; i < ores.Length; i++) + { + var g = $"{chunk.Field.Value}:{chunk.Index}:{ores[i].Commodity.Key.Value}".StableHash() / 2147483648.0 - 1.0; + total += weights[i] = ores[i].Amount * (float) Math.Exp(settings.ChunkCompositionVariance * g); + } + var counts = new int[ores.Length]; + for (var unit = 0; unit < units; unit++) + { + var pick = dice.NextFloat() * total; + var ore = 0; + while (ore < ores.Length - 1 && pick >= weights[ore]) pick -= weights[ore++]; + counts[ore]++; + } + + var at = zone.ChunkPose(chunk.Field, chunk.Index).xy; + var velocity = zone.ChunkVelocity(chunk); + var present = zone.Entities.Contains(shooter); + for (var i = 0; i < ores.Length; i++) + { + var key = ores[i].Commodity.Key; + var maxStack = Math.Max(1, ((SimpleCommodityData) catalog.Get(ores[i].Commodity)).MaxStack); + for (var left = counts[i]; left > 0; left -= maxStack) + { + var stack = new SimpleCommodity { Data = new CultRecordRef(key), Quantity = Math.Min(left, maxStack) }; + // A partial store leaves the remainder in Quantity and returns false, so the next bay is offered the rest. + var stored = false; + if (present) foreach (var bay in shooter.CargoBays) if (stored = bay.TryStore(stack)) break; + if (!stored) zone.Release(stack, at, velocity); + } } } diff --git a/Assets/Scripts/ServerShared/Settings.cs b/Assets/Scripts/ServerShared/Settings.cs index 8326f76da..1d83bd692 100644 --- a/Assets/Scripts/ServerShared/Settings.cs +++ b/Assets/Scripts/ServerShared/Settings.cs @@ -29,6 +29,11 @@ public class PlanetSettings public ExponentialLerp AsteroidSize; public ExponentialLerp AsteroidHitpoints; public ExponentialLerp AsteroidRespawnTime; + // Units of ore a whole rock of normalized size s gives (FireControl.Extract), however many hits break it. + public ExponentialLerp AsteroidYield; + // How far a rock's mix of its belt's ores strays from the kind's ratio: each ore's weight is scaled by + // exp(variance x g), g in [-1, 1) a stable hash of (rock, ore). Zero reads the kind's ratio. + public float ChunkCompositionVariance; public float SecureAreaRadiusMultiplier = .45f; diff --git a/Assets/Scripts/ServerShared/SimulationDice.cs b/Assets/Scripts/ServerShared/SimulationDice.cs index adc440299..c8cb9e759 100644 --- a/Assets/Scripts/ServerShared/SimulationDice.cs +++ b/Assets/Scripts/ServerShared/SimulationDice.cs @@ -18,6 +18,9 @@ public static class SimulationDice // seed (CombatSeed): the run seed feeds drops and mines only (ruling run-seed-drops-only), and placement never rides // ItemManager.Random. public const uint ScatterStream = 5; + // 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; // 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, diff --git a/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs b/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs index d020b068e..64e371c07 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs +++ b/tests/Aetheria.Shared.Tests/MiningCut3Tests.cs @@ -56,6 +56,8 @@ public sealed partial class MiningCut3Tests : IDisposable AsteroidSize = new ExponentialLerp { Minimum = 2f, Maximum = 9f, Exponent = 1.7f }, AsteroidHitpoints = new ExponentialLerp { Minimum = 20f, Maximum = 220f, Exponent = 1.6f }, AsteroidRespawnTime = new ExponentialLerp { Minimum = 8f, Maximum = 96f, Exponent = 1.2f }, + AsteroidYield = new ExponentialLerp { Minimum = 2f, Maximum = 6f, Exponent = 1f }, + ChunkCompositionVariance = .5f, BodyRadius = new ExponentialCurve(), LightRadius = new ExponentialCurve { Constant = lightRadius } }; diff --git a/tests/Aetheria.Shared.Tests/MiningCut4bTests.cs b/tests/Aetheria.Shared.Tests/MiningCut4bTests.cs index 6b263652a..8502e7d7d 100644 --- a/tests/Aetheria.Shared.Tests/MiningCut4bTests.cs +++ b/tests/Aetheria.Shared.Tests/MiningCut4bTests.cs @@ -22,7 +22,7 @@ public sealed class MiningCut4bTests : IDisposable public void Dispose() => _fixtures.Dispose(); - private sealed class Rig + internal sealed class Rig { public MiningCut3Tests.Scene Scene; public Zone Zone => Scene.Zone; @@ -56,11 +56,11 @@ public sealed class MiningCut4bTests : IDisposable } // `precision` 1 gives sigma 1 cell; accuracy 1 and a resolution that asks little of the info make PSensor 1. - private Rig Build(bool sensor = true, bool launcher = false, float damage = 10f, float velocity = 0f, float spread = 0f, + internal Rig Build(bool sensor = true, bool launcher = false, float damage = 10f, float velocity = 0f, float spread = 0f, float precision = 1f, float effective = float.PositiveInfinity, WeaponFuse? fuse = null, float blastRadius = 0f, - float rockSize = 0f, float crossSection = 20f, bool target = true, float tracking = 1000000f) + float rockSize = 0f, float crossSection = 20f, bool target = true, float tracking = 1000000f, FieldKindData kind = null) { - var kind = MiningCut3Tests.Kind("Asteroid", crossSection); + kind ??= MiningCut3Tests.Kind("Asteroid", crossSection); var scene = _fixtures.BuildScene(new[] { kind }, MiningCut3Tests.Belt(kind, MiningCut3Tests.Rock(Distance, .25f, rockSize))); var gear = MiningCut3Tests.Gear("Targeting", new TargetingSystemData { @@ -209,7 +209,7 @@ public sealed class MiningCut4bTests : IDisposable // ==== resolution ==== - private static void Run(Rig rig, float seconds) + internal static void Run(Rig rig, float seconds) { for (var elapsed = 0f; elapsed < seconds; elapsed += .01f) rig.Zone.Update(.01f); } diff --git a/tests/Aetheria.Shared.Tests/MiningCut5aTests.cs b/tests/Aetheria.Shared.Tests/MiningCut5aTests.cs new file mode 100644 index 000000000..cd93ca233 --- /dev/null +++ b/tests/Aetheria.Shared.Tests/MiningCut5aTests.cs @@ -0,0 +1,245 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ + +using System; +using System.Collections.Generic; +using System.Linq; +using CultMath; +using GameCult.Caching; +using Xunit; +using static CultMath.math; + +// Mining Cut 5a (docs/mining-cut-refresh.md): a worn rock pays the shooter in ore at the wear site, from the shot's own +// dice; what does not fit in the hold floats at the rock. The fixtures are Cut 3's belt scene and Cut 4b's rig. +public sealed class MiningCut5aTests : IDisposable +{ + private readonly MiningCut4bTests _rigs = new MiningCut4bTests(); + private readonly MiningCut3Tests _scenes = new MiningCut3Tests(); + + public void Dispose() + { + _rigs.Dispose(); + _scenes.Dispose(); + } + + private static SimpleCommodityData Commodity(string name, int maxStack = 100) => + new SimpleCommodityData { Name = name, Shape = new Shape(), Price = 5, MaxStack = maxStack }; + + // Registers the ores and the kind's yields in the scene's catalog (the kind refs need the stored commodities). + private static void Stock(MiningCut3Tests.Scene scene, FieldKindData kind, params (SimpleCommodityData Ore, float Abundance)[] yields) + { + kind.Yields.Clear(); + foreach (var (ore, abundance) in yields) + { + scene.Cache.Upsert(ore); + kind.Yields.Add(new FieldYield { Commodity = scene.Cache.RefOf(ore), Abundance = abundance }); + } + scene.Cache.Upsert(kind); + } + + private EquippedCargoBay Bay(MiningCut3Tests.Scene scene, Ship ship, int width, int height, string name) + { + var shape = new Shape(width, height); + foreach (var cell in shape.AllCoordinates) shape[cell] = true; + var data = new CargoBayData { Name = name, Shape = new Shape(), InteriorShape = shape, Price = 1, Durability = 4 }; + scene.Cache.Upsert(data); + var bay = new EquippedCargoBay(scene.Items, MiningCut3Tests.Mint(scene, data), new int2(1, 1), ship, name); + ship.CargoBays.Add(bay); + return bay; + } + + private static int Units(IEnumerable items, string ore, MiningCut3Tests.Scene scene) => + items.OfType().Where(c => scene.Items.GetData(c).Name == ore).Sum(c => c.Quantity); + + private static int Units(EquippedCargoBay bay, string ore, MiningCut3Tests.Scene scene) => Units(bay.Cargo.Keys, ore, scene); + + // A rig whose rock (size .5: 4 units, whole) yields `ores`, shooter holding one bay. + private (MiningCut4bTests.Rig Rig, EquippedCargoBay Bay) Mining(int bayWidth = 4, int bayHeight = 4, float damage = 1000f, + WeaponFuse? fuse = null, float velocity = 0f, params (SimpleCommodityData, float)[] ores) + { + var kind = MiningCut3Tests.Kind("Asteroid", 20f); + var rig = _rigs.Build(damage: damage, fuse: fuse, blastRadius: fuse == null ? 0f : 6f, precision: 1000f, rockSize: .5f, velocity: velocity, kind: kind); + Stock(rig.Scene, kind, ores.Length > 0 ? ores : new[] { (Commodity("Rock"), 1f) }); + return (rig, Bay(rig.Scene, rig.Shooter, bayWidth, bayHeight, "Hold")); + } + + private static int Hits(MiningCut4bTests.Rig rig, int cap = 40) + { + for (var shot = 0; shot < cap && !rig.Resolved.Any(o => o.Hit); shot++) + { + // A broken rock cannot be targeted again: the first hit ends the loop. + FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + MiningCut4bTests.Run(rig, .05f); + } + return rig.Resolved.Count(o => o.Hit); + } + + private static float Hitpoints(MiningCut4bTests.Rig rig) => + rig.Zone.Settings.AsteroidHitpoints.Evaluate(rig.Zone.AsteroidBelts[rig.Rock.Field].Data.Asteroids[rig.Rock.Index].Size); + + [Fact] + public void WearReturnsWhatTheRockAbsorbed() + { + var (rig, _) = Mining(); + var hp = Hitpoints(rig); + Assert.Equal(hp * .3f, rig.Zone.Wear(rig.Rock, hp * .3f), 3); + // The breaking hit absorbs only what the rock had left. + Assert.Equal(hp * .7f, rig.Zone.Wear(rig.Rock, hp * 5f), 3); + Assert.False(rig.Zone.ChunkExists(rig.Rock)); + Assert.Equal(0f, rig.Zone.Wear(rig.Rock, hp)); + } + + // Units owed are absorbed/hitpoints x AsteroidYield(size): a rock pays its whole yield however many hits break it, so + // the mean over many rocks does not depend on how the damage arrives. + [Fact] + public void ARockYieldsItsAuthoredTotalWhateverBreaksIt() + { + const int rocks = 300; + var ore = Commodity("Rock"); + var kind = MiningCut3Tests.Kind("Asteroid", 4f); + var scene = _scenes.BuildScene(new[] { kind }, MiningCut3Tests.Belt(kind, + Enumerable.Range(0, rocks).Select(i => MiningCut3Tests.Rock(150f + i * .1f, i / (float) rocks, .3f)).ToArray())); + Stock(scene, kind, (ore, 1f)); + var ship = new Ship(scene.Items, scene.Zone, MiningCut3Tests.Mint(scene, scene.Hull), new EntitySettings()); + scene.Zone.Admit(ship, piloted: false); + var bay = Bay(scene, ship, 8, 8, "Hold"); + var settings = scene.Zone.Settings; + var hp = settings.AsteroidHitpoints.Evaluate(.3f); + var owed = settings.AsteroidYield.Evaluate(.3f); + + uint ordinal = 0; + void Hit(int rock, float fraction) => + FireControl.Extract(scene.Zone, new ChunkId(scene.Belts[0], rock), scene.Zone.Wear(new ChunkId(scene.Belts[0], rock), hp * fraction), + ship, SimulationDice.For(scene.Zone.DropSeed, SimulationDice.OreStream, ++ordinal)); + + for (var rock = 0; rock < rocks / 2; rock++) Hit(rock, 2f); + var wholeHits = Units(bay.Cargo.Keys.Concat(scene.Zone.FloatingItems.Select(f => f.Item)), "Rock", scene); + for (var rock = rocks / 2; rock < rocks; rock++) for (var part = 0; part < 4; part++) Hit(rock, .25f); + var total = Units(bay.Cargo.Keys.Concat(scene.Zone.FloatingItems.Select(f => f.Item)), "Rock", scene); + var quartered = total - wholeHits; + + // owed = 3.2 per rock; 150 rocks: mean 480, sigma about 4.9 whole, 4.9 quartered. + Assert.InRange(wholeHits, 480 - 30, 480 + 30); + Assert.InRange(quartered, 480 - 30, 480 + 30); + Assert.Equal(3.2f, owed, 3); + } + + [Fact] + public void ADirectHitPaysTheShooter() + { + var (rig, bay) = Mining(ores: new[] { (Commodity("Rock"), 1f), (Commodity("Gold"), 1f) }); + var yields = FieldKinds.Yield(rig.Zone.AsteroidBelts[rig.Rock.Field].Data.Kind, default, rig.Scene.Cache); + Assert.Equal(2, yields.Length); + Assert.Equal(1, Hits(rig)); + Assert.False(rig.Zone.ChunkExists(rig.Rock)); + Assert.Equal(4, Units(bay, "Rock", rig.Scene) + Units(bay, "Gold", rig.Scene)); + Assert.Empty(rig.Zone.FloatingItems); + } + + [Fact] + public void ABlastPaysTheShooter() + { + var (rig, bay) = Mining(fuse: WeaponFuse.Contact, ores: new[] { (Commodity("Rock"), 1f) }); + Hits(rig); + Assert.False(rig.Zone.ChunkExists(rig.Rock)); + Assert.Equal(4, Units(bay, "Rock", rig.Scene)); + } + + [Fact] + public void AMineWearsButYieldsNothing() + { + var (rig, bay) = Mining(); + var at = rig.Zone.ChunkPose(rig.Rock.Field, rig.Rock.Index).xy; + FireControl.Detonate(rig.Zone, at, 6f, 1000f, DamageType.Kinetic); + Assert.False(rig.Zone.ChunkExists(rig.Rock)); + Assert.Empty(bay.Cargo); + Assert.Empty(rig.Zone.FloatingItems); + } + + // Ruling mining-overflow-floats: what the hold cannot take floats at the rock, where another ship can pick it up. + [Fact] + public void AFullHoldReleasesTheOverflow() + { + var grit = Commodity("Grit", maxStack: 2); + var (rig, bay) = Mining(bayWidth: 1, bayHeight: 1, ores: new[] { (grit, 1f) }); + Hits(rig); + + Assert.Equal(2, Units(bay, "Grit", rig.Scene)); + var floating = Assert.Single(rig.Zone.FloatingItems); + Assert.Equal(2, Assert.IsType(floating.Item).Quantity); + var rock = rig.Zone.ChunkPose(rig.Rock.Field, rig.Rock.Index).xy; + Assert.True(length(floating.Body.Position - rock) < 1f, "the overflow leaves from the rock"); + + var taker = new Ship(rig.Scene.Items, rig.Zone, MiningCut3Tests.Mint(rig.Scene, rig.Scene.Hull), new EntitySettings()); + rig.Zone.Admit(taker, piloted: false); + var takerBay = Bay(rig.Scene, taker, 4, 4, "Taker"); + Assert.True(rig.Zone.TryPickUp(taker, floating.Id)); + Assert.Equal(2, Units(takerBay, "Grit", rig.Scene)); + } + + [Fact] + public void AGoneShooterReleasesEverything() + { + var (rig, bay) = Mining(velocity: 50f); + FireControl.Fire(rig.Gun, rig.GunItem, rig.Shooter); + rig.Shooter.HeatstrokeDeath.OnNext(UniRx.Unit.Default); + MiningCut4bTests.Run(rig, 3f); + + Assert.Empty(bay.Cargo); + Assert.Equal(4, Units(rig.Zone.FloatingItems.Select(f => f.Item), "Rock", rig.Scene)); + } + + // Two zones of one pack share every key, so the same rocks wear in each: the ore is a function of the dice alone. + private (MiningCut3Tests.Scene Scene, Func NewZone, Ship Shooter) Field(int rocks, float size, float variance = .5f, float yield = 4f) + { + var kind = MiningCut3Tests.Kind("Asteroid", 4f); + var scene = _scenes.BuildScene(new[] { kind }, MiningCut3Tests.Belt(kind, + Enumerable.Range(0, rocks).Select(i => MiningCut3Tests.Rock(150f + i, i / (float) rocks, size)).ToArray())); + Stock(scene, kind, (Commodity("Rock"), 1f), (Commodity("Gold"), 1f)); + var ship = new Ship(scene.Items, scene.Zone, MiningCut3Tests.Mint(scene, scene.Hull), new EntitySettings()); + Zone NewZone() + { + var settings = MiningCut3Tests.PlanetSettings(); + settings.ChunkCompositionVariance = variance; + settings.AsteroidYield = new ExponentialLerp { Minimum = yield, Maximum = yield, Exponent = 1f }; + return new Zone(scene.Items, settings, scene.Pack, new GalaxyZone { Name = "MiningCut3", Owner = null }, null); + } + return (scene, NewZone, ship); + } + + // Every rock broken once; the shooter is not in the zone, so everything floats and the floats are the record. + private static (int Rock, int Gold)[] Break(MiningCut3Tests.Scene scene, Zone zone, Ship ship, int rocks, uint seed) => + Enumerable.Range(0, rocks).Select(rock => + { + var chunk = new ChunkId(scene.Belts[0], rock); + var before = zone.FloatingItems.Select(f => f.Item).ToArray(); + FireControl.Extract(zone, chunk, zone.Wear(chunk, 1e6f), ship, SimulationDice.For(seed, SimulationDice.OreStream, (uint) rock)); + var added = zone.FloatingItems.Select(f => f.Item).Except(before).ToArray(); + return (Units(added, "Rock", scene), Units(added, "Gold", scene)); + }).ToArray(); + + [Fact] + public void TheSameShotGivesTheSameOre() + { + var (scene, newZone, ship) = Field(20, .5f); + var first = Break(scene, newZone(), ship, 20, 11); + Assert.Equal(first, Break(scene, newZone(), ship, 20, 11)); + Assert.NotEqual(first, Break(scene, newZone(), ship, 20, 12)); + } + + // Composition is derived from the rock's identity every call: variance 0 reads the kind's ratio, variance above 0 gives + // rocks different mixes, and nothing stores it (a second zone of the pack reads the same mixes from the dice and keys). + [Fact] + public void CompositionVariesByRockAndIsDerived() + { + var (scene, even, ship) = Field(12, 1f, variance: 0f, yield: 600f); + // Equal weights, 600 units a rock: even splits within sampling noise (sigma about 12). + Assert.All(Break(scene, even(), ship, 12, 5), m => Assert.InRange(m.Rock, 240, 360)); + + var (scene2, varied, ship2) = Field(12, 1f, variance: 2f, yield: 600f); + var mixes = Break(scene2, varied(), ship2, 12, 5).Select(m => m.Rock).ToArray(); + Assert.True(mixes.Max() - mixes.Min() > 100, "rocks differ in mix when variance is above zero"); + Assert.Equal(mixes, Break(scene2, varied(), ship2, 12, 5).Select(m => m.Rock)); + } +}