A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Add the fixture-only regional geography foundation (Refs #1690) (#1846)
Eyal Golanbad2023e21df
diff --git a/changelog.d/1690.md b/changelog.d/1690.mdnew file mode 100644index 000000000..915176f5e--- /dev/null+++ b/changelog.d/1690.md@@ -0,0 +1 @@+- Add the gdd-0.3 gameplay-region geography contract, effective-map validation and immutable regional fixture pools using the existing population ledger. Keep production initialization inactive and preserve the legacy/gdd-0.1 content boundary. Regional commands, replay and production authoring remain separate work.diff --git a/content/schema/regions.schema.json b/content/schema/regions.schema.jsonnew file mode 100644index 000000000..c6ecc3581--- /dev/null+++ b/content/schema/regions.schema.json@@ -0,0 +1,54 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "title": "Gameplay region geography",+ "description": "Geography and evidence only. Absence leaves regional initialization inactive. No start allocations or operational control are implied.",+ "type": "object",+ "additionalProperties": false,+ "required": ["player_regions"],+ "properties": {+ "player_regions": {+ "type": "array",+ "items": { "$ref": "#/$defs/region" }+ }+ },+ "$defs": {+ "id": { "type": "string", "pattern": "^[a-z][a-z0-9_]*$" },+ "hex": {+ "type": "object",+ "additionalProperties": false,+ "required": ["q", "r"],+ "properties": {+ "q": { "type": "integer", "minimum": -2147483648, "maximum": 2147483647 },+ "r": { "type": "integer", "minimum": -2147483648, "maximum": 2147483647 }+ }+ },+ "control": {+ "type": "object",+ "additionalProperties": false,+ "required": ["status"],+ "properties": {+ "status": { "enum": ["SOURCED", "PARTIAL-EVIDENCE", "NEEDS-RESEARCH"] },+ "value": { "type": ["string", "null"] }+ },+ "if": { "properties": { "status": { "const": "SOURCED" } } },+ "then": { "required": ["value"], "properties": { "value": { "type": "string", "minLength": 1 } } },+ "else": { "properties": { "value": { "type": "null" } } }+ },+ "region": {+ "type": "object",+ "additionalProperties": false,+ "required": ["id", "capital_location", "member_hexes", "member_locations", "design_note", "sources", "capital_approval", "binding_status", "opening_control"],+ "properties": {+ "id": { "$ref": "#/$defs/id" },+ "capital_location": { "$ref": "#/$defs/id" },+ "member_hexes": { "type": "array", "minItems": 1, "uniqueItems": true, "items": { "$ref": "#/$defs/hex" } },+ "member_locations": { "type": "array", "minItems": 1, "uniqueItems": true, "items": { "$ref": "#/$defs/id" } },+ "design_note": { "type": "string", "minLength": 1 },+ "sources": { "type": "array", "minItems": 1, "items": { "type": "string", "minLength": 1 } },+ "capital_approval": { "enum": ["APPROVED", "NEEDS-RESEARCH"] },+ "binding_status": { "enum": ["SOURCED", "PARTIAL-EVIDENCE", "NEEDS-RESEARCH"] },+ "opening_control": { "$ref": "#/$defs/control" }+ }+ }+ }+}diff --git a/docs/rules/mvp.md b/docs/rules/mvp.mdindex 768e71ac3..415358113 100644--- a/docs/rules/mvp.md+++ b/docs/rules/mvp.md@@ -106,6 +106,10 @@ R-CITY-005: The cities' employed share (employed over civilians and craftsmen, sR-CITY-006: The cities are the `city` and `town` rows of `map/settlements_1948.yaml`, in that file's order, and their start values are `cities.yaml`'s. Each of a city's values (`people`, `employed_share`, `housing_capacity`, `job_slots`) is required and has a status: `sourced` (read from the source named), `derived` (computed from sourced values), `wikipedia-only` (an owner-accepted Wikipedia figure) or `design` (a labelled design value, R-LOOP-005). A `sourced`, `derived` or `wikipedia-only` value has at least one source, each with a url and a checked date, and the day (YYYY-MM-DD) or month (YYYY-MM) it describes; the loader refuses a value without them, naming the file and field (GDD Phase 3 plan, review focus 3).+The regional foundation under exact `gdd-0.3` identity reads optional `regions.yaml` (`schema/regions.schema.json`), separate from aliyah origins. Each explicit region has a stable id, one capital, land member hexes and member place ids from settlements or named map locations. Validation uses effective placements after overrides; inconsistent dual identities, repeated members and overlapping ownership are errors. Different place ids may share one hex within a region. No contiguity or complete-map coverage is required. Unknown opening control stays null and never grants access. Geography approval is separate from evidence status and human historical review.++Regional state is currently initialized only by explicit internal fixtures, through the existing population ledger. Immutable pools keep base ordinary housing, condition fractions, Industry/workshop slots and uniquely owned facility contributions separate; reception/training beds do not add ordinary housing. Population and assignment summaries come from the ledger. Canonical geography/capacity sections are limited to initialized `gdd-0.3` regional fixtures, and clones share only immutable records. No shipped era selects regional initialization, no production regional content or allocations are supplied, and the aggregate-city guards remain. The city behavior above remains the production path; capital-addressed commands, replay, capacity reservation policy and the production cutover are later increments of #1690 and its consumers.+R-CITY-007: A city starts with `civilians` = `people / people_per_unit` to the nearest unit (a half rounds up), and at least 1 when `people` is above 0 (Q-START-2, owner, 15 October 2026); `employed` = `people * employed_share / people_per_unit` to the nearest unit; `housing_capacity` and `job_slots` as written, in units. The loader refuses a city whose start employed is above its job slots. The arithmetic is decimal, so it is exact on every runtime.R-HOUSE-001: Each city has a housing condition from 0 to 1, an average over the city (D-D2, Q-HOUSE-2, owner, 15 October 2026). Every city starts at `mvp.housing_start_condition` (Q-START-3: one design value for all the cities, 0.35, `model.yaml`'s `housing` base). The condition is per city: one city's counts never change another's. It is in the state hash (R-LOOP-002).diff --git a/sim/Statecraft.Sim.Tests/PlayerRegionsContentTests.cs b/sim/Statecraft.Sim.Tests/PlayerRegionsContentTests.csnew file mode 100644index 000000000..01176d65e--- /dev/null+++ b/sim/Statecraft.Sim.Tests/PlayerRegionsContentTests.cs@@ -0,0 +1,188 @@+using Statecraft.Sim;++/// <summary>R-CITY-006: approved named-place projections, not a production boundary roster.</summary>+public class PlayerRegionsContentTests+{+ // Geography from the approved #1691 research: Tel Aviv and Jaffa share (-3,19),+ // Rishon LeZion is (-4,21). Approval of capitals does not establish opening control.+ internal const string TelAviv = @"+ - id: tel_aviv_jaffa+ capital_location: tel_aviv+ member_hexes: [{ q: -3, r: 19 }]+ member_locations: [tel_aviv, jaffa]+ design_note: 'Named-place projection for testing; not a historical boundary'+ sources: ['content/map/settlement_hexes.yaml:5-6', 'owner 27 October 2026: approved capital Tel Aviv']+ capital_approval: APPROVED+ binding_status: NEEDS-RESEARCH+ opening_control: { status: NEEDS-RESEARCH, value: null }+";+ internal const string Central = @"+ - id: central_plain+ capital_location: rishon_lezion+ member_hexes: [{ q: -4, r: 21 }]+ member_locations: [rishon_lezion]+ design_note: 'Named-place projection for testing; not a historical boundary'+ sources: ['content/map/settlement_hexes.yaml:17', 'owner 27 October 2026: approved capital Rishon LeZion']+ capital_approval: APPROVED+ binding_status: NEEDS-RESEARCH+ opening_control: { status: NEEDS-RESEARCH, value: null }+";+ internal static Content Load(string? regions = "player_regions:\n" + TelAviv, bool modern = true,+ string? overrideText = null, Action<string>? onRead = null)+ {+ var root = RealContentTests.ContentRoot();+ return ContentLoader.Load(rel =>+ {+ onRead?.Invoke(rel);+ if (rel == PlayerRegionCatalogue.FileName) return regions;+ if (rel == MapOverrides.FileName) return overrideText;+ var path = Path.Combine(root, rel);+ var text = File.Exists(path) ? File.ReadAllText(path) : null;+ return modern && rel == "eras.yaml" ? text!.Replace("loop: gdd", "loop: gdd, ruleset: gdd-0.3") : text;+ }, Directory.GetFiles(Path.Combine(root, "events"), "*.yaml").Select(p => "events/" + Path.GetFileName(p)));+ }++ [Fact]+ public void SharedHexRetainsTwoPlaceIdentitiesAndOneCapital()+ {+ var c = Load(); var r = Assert.Single(c.PlayerRegions.Regions).Value;+ Assert.Equal("tel_aviv_jaffa", r.Id); Assert.Equal("APPROVED", r.CapitalApproval);+ Assert.Equal("NEEDS-RESEARCH", r.BindingStatus); Assert.Null(r.OpeningController);+ Assert.Equal(new[] { "jaffa", "tel_aviv" }, r.MemberLocations);+ Assert.Single(r.MemberHexes);+ Assert.Same(r, c.PlayerRegions.AtLocation("jaffa"));+ Assert.Same(r, c.PlayerRegions.AtCapital("tel_aviv"));+ Assert.Null(c.PlayerRegions.AtCapital("jaffa"));+ Assert.Same(r, c.PlayerRegions.AtHex(-3, 19));+ Assert.Null(c.PlayerRegions.AtLocation("tiberias"));+ Assert.NotEmpty(c.Regions); // Immigrant origins retain their own catalogue.+ }++ [Theory]+ [InlineData("id: tel_aviv_jaffa", "id: ''", "id")]+ [InlineData("capital_location: tel_aviv", "capital_location: tiberias", "capital_location")]+ [InlineData("capital_location: tel_aviv", "capital_location: ''", "capital_location")]+ [InlineData("[tel_aviv, jaffa]", "[]", "member_locations")]+ [InlineData("[tel_aviv, jaffa]", "[tel_aviv, tel_aviv]", "member_locations[1]")]+ [InlineData("[tel_aviv, jaffa]", "[tel_aviv, missing]", "member_locations[1]")]+ [InlineData("[{ q: -3, r: 19 }]", "[]", "member_hexes")]+ [InlineData("[{ q: -3, r: 19 }]", "[{ q: -3 }]", "member_hexes[0]")]+ [InlineData("[{ q: -3, r: 19 }]", "[{ q: -3, r: 19 }, { q: -3, r: 19 }]", "member_hexes[1]")]+ [InlineData("[{ q: -3, r: 19 }]", "[{ q: -4, r: 21 }]", "member_locations[0]")]+ [InlineData("value: null", "value: inferred", "opening_control.value")]+ [InlineData("NEEDS-RESEARCH, value: null", "PARTIAL-EVIDENCE, value: inferred", "opening_control.value")]+ [InlineData("NEEDS-RESEARCH, value: null", "SOURCED, value: null", "opening_control.value")]+ [InlineData("NEEDS-RESEARCH, value: null", "SOURCED, value: [inferred]", "opening_control.value")]+ [InlineData("capital_approval: APPROVED", "capital_approval: inferred", "capital_approval")]+ [InlineData("binding_status: NEEDS-RESEARCH", "binding_status: inferred", "binding_status")]+ [InlineData(" sources: ['content/map/settlement_hexes.yaml:5-6', 'owner 27 October 2026: approved capital Tel Aviv']", " sources: []", "sources")]+ public void InvalidRowIsRejectedBeforeContentIsExposed(string from, string to, string field)+ {+ var e = Assert.Throws<ContentException>(() => Load("player_regions:\n" + TelAviv.Replace(from, to)));+ Assert.Equal("regions.yaml", e.File); Assert.Equal("player_regions[0]." + field, e.Field);+ }++ [Theory]+ [InlineData("{}", "player_regions")]+ [InlineData("player_regions: null", "player_regions")]+ [InlineData("player_regions: [null]", "player_regions[0]")]+ public void MissingOrNullCollectionsAreRefused(string text, string field)+ {+ var e = Assert.Throws<ContentException>(() => Load(text));+ Assert.Equal("regions.yaml", e.File); Assert.Equal(field, e.Field);+ }++ [Fact]+ public void DuplicateRegionAndOverlappingGeographyAreRefused()+ {+ var duplicate = Assert.Throws<ContentException>(() => Load("player_regions:\n" + TelAviv + TelAviv));+ Assert.Equal("player_regions[1].id", duplicate.Field);+ var overlap = Assert.Throws<ContentException>(() => Load("player_regions:\n" + TelAviv + TelAviv.Replace("id: tel_aviv_jaffa", "id: central_plain")));+ Assert.Equal("player_regions[1].member_hexes[0]", overlap.Field);+ var duplicatePlace = Assert.Throws<ContentException>(() => Load("player_regions:\n" + TelAviv + Central.Replace("[rishon_lezion]", "[rishon_lezion, tel_aviv]")));+ Assert.Equal("player_regions[1].member_locations[1]", duplicatePlace.Field);+ }++ [Fact]+ public void SeaAndAbsentHexesAreRefused()+ {+ var sea = Load(null).Hexes.First(h => !h.Land);+ foreach (var pair in new[] { (sea.Q, sea.R), (int.MaxValue, int.MaxValue) })+ {+ var replacement = FormattableString.Invariant($"{{ q: {pair.Item1}, r: {pair.Item2} }}");+ var e = Assert.Throws<ContentException>(() => Load("player_regions:\n" + TelAviv.Replace("{ q: -3, r: 19 }", replacement)));+ Assert.Equal("regions.yaml", e.File); Assert.Equal("player_regions[0].member_hexes[0]", e.Field);+ }+ }++ [Fact]+ public void FinalPlacementAndAmbiguousDualIdentityAreChecked()+ {+ var e = Assert.Throws<ContentException>(() => Load(overrideText: "terrain: []\ncontrol: []\nlocations: [{ id: tel_aviv, hex: { q: -4, r: 21 } }]\n"));+ Assert.Equal("regions.yaml", e.File); Assert.Equal("player_regions[0].member_locations[0]", e.Field);+ var c = Load(null);+ c.MapLocations.Add(new MapLocation { Id = "tel_aviv", Q = -4, R = 21 });+ e = Assert.Throws<ContentException>(() => PlayerRegionCatalogue.Validate(c, new[] { Definition() }));+ Assert.Equal("player_regions[0].member_locations[0]", e.Field);+ }++ internal static PlayerRegionDefinition Definition() => new PlayerRegionDefinition {+ Id = "tel_aviv_jaffa", CapitalLocation = "tel_aviv", MemberHexes = new() { new() { Q = -3, R = 19 } },+ MemberLocations = new() { "tel_aviv", "jaffa" }, DesignNote = "Named-place projection for testing",+ Sources = new() { "content/map/settlement_hexes.yaml:5-6" }, CapitalApproval = "APPROVED", BindingStatus = "NEEDS-RESEARCH",+ OpeningControl = new() { Status = "NEEDS-RESEARCH", Value = null }+ };++ [Fact]+ public void ValidatedGeographyDoesNotAliasMutableInput()+ {+ var row = Definition(); var catalogue = PlayerRegionCatalogue.Validate(Load(null), new[] { row });+ row.MemberHexes[0].Q = -4; row.MemberLocations.Clear(); row.Sources.Clear();+ Assert.Equal(-3, catalogue.Regions["tel_aviv_jaffa"].MemberHexes[0].Q);+ Assert.Equal(2, catalogue.Regions["tel_aviv_jaffa"].MemberLocations.Count);+ Assert.Single(catalogue.Regions["tel_aviv_jaffa"].Sources);+ }++ [Fact]+ public void PartialEvidenceStaysNullAndTiberiasKeepsItsApprovedDesignation()+ {+ const string valleys = @"+ - id: valleys+ capital_location: tiberias+ member_hexes: [{ q: 10, r: 8 }]+ member_locations: [tiberias]+ design_note: 'Named-place projection for testing; not a historical boundary'+ sources: ['content/map/settlement_hexes.yaml:9', 'owner 27 October 2026: approved capital Tiberias']+ capital_approval: APPROVED+ binding_status: NEEDS-RESEARCH+ opening_control: { status: NEEDS-RESEARCH, value: null }+";+ var c = Load("player_regions:\n" + TelAviv + Central + valleys);+ Assert.Equal("tiberias", c.PlayerRegions.Regions["valleys"].CapitalLocation);+ Assert.Equal("APPROVED", c.PlayerRegions.Regions["valleys"].CapitalApproval);+ Assert.Equal("rishon_lezion", c.PlayerRegions.Regions["central_plain"].CapitalLocation);+ Assert.Equal("APPROVED", c.PlayerRegions.Regions["central_plain"].CapitalApproval);+ Assert.All(c.PlayerRegions.Regions.Values, r => Assert.Null(r.OpeningController));+ var partial = Load("player_regions:\n" + TelAviv.Replace("NEEDS-RESEARCH, value: null", "PARTIAL-EVIDENCE, value: null"));+ Assert.Equal("PARTIAL-EVIDENCE", partial.PlayerRegions.Regions["tel_aviv_jaffa"].ControlStatus);+ Assert.Null(partial.PlayerRegions.Regions["tel_aviv_jaffa"].OpeningController);+ }++ [Fact]+ public void OnlyExactNewIdentityConsumesAndHashesGeography()+ {+ var reads = new List<string>();+ var old = Load(modern: false, onRead: reads.Add);+ Assert.DoesNotContain("regions.yaml", reads); Assert.Empty(old.PlayerRegions.Regions);+ Assert.Equal(old.Hash, Load("malformed: [", modern: false).Hash);+ Assert.NotEqual(Load().Hash, Load("player_regions:\n" + TelAviv + "\n# consumed provenance\n").Hash);+ Assert.Empty(Load(null).PlayerRegions.Regions);+ // Legacy also has no read, even when an unrelated file is present and malformed.+ var files = new Dictionary<string, string>(Fixture.Files) { ["regions.yaml"] = "malformed: [" };+ reads.Clear();+ var legacy = ContentLoader.Load(rel => { reads.Add(rel); return files.TryGetValue(rel, out var text) ? text : null; }, Array.Empty<string>());+ Assert.DoesNotContain("regions.yaml", reads); Assert.Empty(legacy.PlayerRegions.Regions);+ files.Remove("regions.yaml");+ Assert.Equal(legacy.Hash, ContentLoader.Load(rel => files.TryGetValue(rel, out var text) ? text : null, Array.Empty<string>()).Hash);+ }+}diff --git a/sim/Statecraft.Sim.Tests/PlayerRegionsTests.cs b/sim/Statecraft.Sim.Tests/PlayerRegionsTests.csnew file mode 100644index 000000000..4f32d5f23--- /dev/null+++ b/sim/Statecraft.Sim.Tests/PlayerRegionsTests.cs@@ -0,0 +1,139 @@+using Statecraft.Sim;+using System.Globalization;++/// <summary>R-CITY-006, R-POP-003: explicit fixture state only; capacities are arbitrary test quantities.</summary>+public class PlayerRegionsTests+{+ const string A = "tel_aviv_jaffa", B = "central_plain";+ static Content Content() => PlayerRegionsContentTests.Load("player_regions:\n" + PlayerRegionsContentTests.TelAviv + PlayerRegionsContentTests.Central);+ static PlayerRegionPool Pool(string id, int housing = 7, decimal condition = .4m,+ IEnumerable<PlayerRegionFacility>? facilities = null) => new PlayerRegionPool(id, housing, condition, 3, 2,+ facilities ?? Array.Empty<PlayerRegionFacility>());+ static PopulationUnit Person(string region, int q, int r) => new PopulationUnit(0, PopulationStatus.FreeCivilian,+ 0, new PopulationLocation(region, q, r), PopulationAssignment.Unassigned,+ CivilianProfession.None, CivilianTier.None, 0, "", 0, PopulationEquipment.None);+ static IEnumerable<PopulationInventoryRow> People(bool reverse = false)+ {+ var rows = new[] { new PopulationInventoryRow("fixture", 0, Person(A, -3, 19)),+ new PopulationInventoryRow("fixture", 1, Person(B, -4, 21)) };+ return reverse ? rows.Reverse() : rows;+ }+ static PopulationTarget[] Targets() => new[] { new PopulationTarget("fixture-a-job", PopulationAssignmentKind.Work, A),+ new PopulationTarget("fixture-b-job", PopulationAssignmentKind.Work, B) };+ static GameState State(Content c, IEnumerable<PlayerRegionPool>? pools = null, bool reverse = false) =>+ PlayerRegions.CreateFixture(c, pools ?? new[] { Pool(A), Pool(B) }, People(reverse), Targets(), Array.Empty<string>(), Array.Empty<string>());++ [Fact]+ public void OneRegionBaselineAndTwoRegionPoolsDoNotUseTownAggregates()+ {+ var c = PlayerRegionsContentTests.Load();+ var one = PlayerRegions.CreateFixture(c, new[] { Pool(A) }, People().Take(1), Targets().Take(1), Array.Empty<string>(), Array.Empty<string>());+ Assert.Single(one.PlayerRegions); Assert.Empty(one.Cities);+ Assert.Equal(1, PlayerRegions.PresentPopulation(one, A));+ Assert.Equal(7, one.PlayerRegions[A].OrdinaryHousing);+ var two = State(Content());+ Assert.Equal(new[] { B, A }, two.PlayerRegions.Keys);+ Assert.Equal(1, PlayerRegions.PresentPopulation(two, A)); Assert.Equal(1, PlayerRegions.PresentPopulation(two, B));+ Assert.Equal(2, two.PopulationLedger.Units.Count); two.PopulationLedger.Reconcile();+ Assert.Throws<ArgumentException>(() => PlayerRegions.PresentPopulation(two, "jaffa"));+ }++ [Fact]+ public void IndustryWorkshopAndDedicatedHousingStaySeparateAndContributeOnce()+ {+ var facilities = new List<PlayerRegionFacility> {+ new("fixture-industry", "tel_aviv", PlayerRegionFacilityKind.Industry, 5),+ new("fixture-workshop", "jaffa", PlayerRegionFacilityKind.Workshop, 11),+ new("fixture-reception", "tel_aviv", PlayerRegionFacilityKind.Reception, 13),+ new("fixture-training", "jaffa", PlayerRegionFacilityKind.Training, 17) };+ var c = Content(); var a = Pool(A, facilities: facilities);+ facilities.Clear();+ var s = State(c, new[] { a, Pool(B) });+ Assert.Equal(7, a.OrdinaryHousing); Assert.Equal(8, a.IndustrySlots); Assert.Equal(13, a.WorkshopSlots);+ Assert.Equal(13, a.ReceptionBeds); Assert.Equal(17, a.TrainingBeds); Assert.Equal(4, a.Facilities.Count);+ Assert.Equal(3, s.PlayerRegions[B].IndustrySlots); Assert.Equal(2, s.PlayerRegions[B].WorkshopSlots);+ Assert.Equal(0, s.PlayerRegions[B].ReceptionBeds); Assert.Equal(0, s.PlayerRegions[B].TrainingBeds);+ Assert.Equal(1, PlayerRegions.PresentPopulation(s, A)); // Two places and four facilities add no people.+ var changed = State(c, new[] { Pool(A, housing: 19, facilities: a.Facilities), Pool(B) }); // only housing differs+ Assert.NotEqual(s.Hash(), changed.Hash());+ Assert.Equal(s.PlayerRegions[B].Canonical(), changed.PlayerRegions[B].Canonical());+ }++ [Fact]+ public void LedgerRemainsTheOnlyPersonAndAssignmentAuthority()+ {+ var s = State(Content()); var l = s.PopulationLedger;+ l.ChangeAssignment(0, new PopulationAssignment(PopulationAssignmentKind.Work, "fixture-a-job"));+ Assert.Equal(1, PlayerRegions.Assigned(s, A, PopulationAssignmentKind.Work));+ Assert.Equal(0, PlayerRegions.Assigned(s, B, PopulationAssignmentKind.Work));+ l.ChangeAssignment(0, PopulationAssignment.Unassigned); // released, so only the cross-region check can refuse the B job+ var before = s.Describe();+ Assert.Throws<ArgumentException>(() => l.ChangeAssignment(0, new PopulationAssignment(PopulationAssignmentKind.Work, "fixture-b-job")));+ Assert.Equal(before, s.Describe()); Assert.Equal(0, PlayerRegions.Assigned(s, B, PopulationAssignmentKind.Work)); l.Reconcile();+ Assert.Equal(0, l.Get(0).Id); Assert.Equal(2, l.Units.Count);+ // This exercises existing ledger region validation, not a new reservation command or slot-capacity policy.+ }++ [Fact]+ public void ClonesAndInsertionOrderPreserveCanonicalStateAcrossCultures()+ {+ var c = Content(); var a = State(c); var b = State(c, new[] { Pool(B), Pool(A) }, reverse: true);+ Assert.Equal(a.Describe(), b.Describe());+ var clone = a.Clone(); var before = a.Describe();+ clone.PopulationLedger.RegisterCombatLoss(0, "fixture-loss");+ Assert.Equal(before, a.Describe()); Assert.NotEqual(before, clone.Describe());+ Assert.Equal(1, PlayerRegions.PresentPopulation(a, A)); Assert.Equal(0, PlayerRegions.PresentPopulation(clone, A));+ Assert.Same(a.PlayerRegions[A], clone.PlayerRegions[A]); // Immutable records may be shared.+ var culture = CultureInfo.CurrentCulture;+ try+ {+ foreach (var name in new[] { "he-IL", "en-US", "de-DE" })+ {+ CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(name);+ Assert.Equal(before, a.Describe()); Assert.Equal(before, State(c).Describe());+ }+ }+ finally { CultureInfo.CurrentCulture = culture; }+ }++ [Theory]+ [InlineData(-1, 4, 3, 2)]+ [InlineData(7, -1, 3, 2)]+ [InlineData(7, 11, 3, 2)]+ [InlineData(7, 4, -1, 2)]+ [InlineData(7, 4, 3, -1)]+ public void InvalidCapacitiesAndConditionAreRefused(int housing, int conditionTenths, int industry, int workshop) =>+ Assert.Throws<ArgumentException>(() => new PlayerRegionPool(A, housing, conditionTenths / 10m, industry, workshop, Array.Empty<PlayerRegionFacility>()));++ [Fact]+ public void FacilityIdentityLocationAndExplicitStartCoverageAreRequired()+ {+ var c = Content();+ var f = new PlayerRegionFacility("fixture-facility", "tel_aviv", PlayerRegionFacilityKind.Industry, 1);+ Assert.Throws<ArgumentException>(() => Pool(A, facilities: new[] { f, f }));+ // Same id in two pools, each at a valid location of its own pool: only national facility uniqueness can refuse it.+ var twin = new PlayerRegionFacility("fixture-facility", "rishon_lezion", PlayerRegionFacilityKind.Industry, 1);+ Assert.Equal("Facility must have one owning region and a member location.",+ Assert.Throws<ArgumentException>(() => State(c, new[] { Pool(A, facilities: new[] { f }), Pool(B, facilities: new[] { twin }) })).Message);+ Assert.Throws<ArgumentException>(() => State(c, new[] { Pool(A) }));+ Assert.Throws<ArgumentException>(() => State(c, new[] { Pool(A), Pool(B), Pool(B) }));+ var outside = new PlayerRegionFacility("fixture-facility", "tiberias", PlayerRegionFacilityKind.Industry, 1);+ Assert.Throws<ArgumentException>(() => State(c, new[] { Pool(A, facilities: new[] { outside }), Pool(B) }));+ Assert.Throws<ArgumentException>(() => new PlayerRegionFacility("fixture-facility", "tel_aviv", PlayerRegionFacilityKind.Industry, -1));+ Assert.Throws<OverflowException>(() => new PlayerRegionPool(A, 1, 1m, int.MaxValue, 0, new[] { f }));+ }++ [Fact]+ public void GeographyDoesNotActivateAProductionPopulationOrBypassAggregateGuards()+ {+ var c = Content(); var production = Simulation.NewGame(c, 1, Mode.Historical);+ Assert.Empty(production.PlayerRegions); Assert.False(production.PopulationLedger.IsInitialized);+ var fixture = State(c); var before = fixture.Describe();+ const string guardMessage = "Population-ledger fixtures cannot run aggregate systems; gdd-0.3 integration is held.";+ Assert.Equal(guardMessage, Assert.Throws<NotSupportedException>(() => Cities.Init(c, fixture)).Message);+ Assert.Equal(guardMessage, Assert.Throws<NotSupportedException>(() => Simulation.Step(c, fixture, Array.Empty<Command>())).Message);+ Assert.Equal(before, fixture.Describe());+ Assert.Equal("Regional fixtures require gdd-0.3.",+ Assert.Throws<InvalidOperationException>(() => State(PlayerRegionsContentTests.Load(modern: false))).Message);+ }+}diff --git a/sim/Statecraft.Sim/Content.cs b/sim/Statecraft.Sim/Content.csindex aec51c573..e70b65684 100644--- a/sim/Statecraft.Sim/Content.cs+++ b/sim/Statecraft.Sim/Content.cs@@ -1330,6 +1330,8 @@ namespace Statecraft.Simpublic List<AliyahPeriod> Aliyah = new List<AliyahPeriod>();/// <summary>Origin groups of the aliyah series, with display names (aliyah.yaml regions).</summary>public List<Region> Regions = new List<Region>();+ /// <summary>Authored gameplay geography, separate from immigrant origins and historical overlays.</summary>+ public PlayerRegionCatalogue PlayerRegions { get; internal set; } = PlayerRegionCatalogue.Empty;/// <summary>Display names and currency prefixes of the treasury, debt and foreign currency reserves (model.yaml money).</summary>public List<MoneyAccount> Money = new List<MoneyAccount>();public List<PopulationAnchor> PopulationAnchors = new List<PopulationAnchor>();diff --git a/sim/Statecraft.Sim/ContentLoader.cs b/sim/Statecraft.Sim/ContentLoader.csindex 21828cc23..acdbc41a2 100644--- a/sim/Statecraft.Sim/ContentLoader.cs+++ b/sim/Statecraft.Sim/ContentLoader.cs@@ -48,6 +48,7 @@ namespace Statecraft.Simsealed class MapLocationsFile { public List<MapLocation> Locations { get; set; } = new List<MapLocation>(); }sealed class SettlementTargetsFile { public List<SettlementTarget> Targets { get; set; } = new List<SettlementTarget>(); }sealed class CitiesFile { public List<CityStart> Cities { get; set; } = new List<CityStart>(); }+ sealed class PlayerRegionsFile { public List<PlayerRegionDefinition> PlayerRegions { get; set; } = null!; }sealed class UnitTypesFile { public List<UnitType> Types { get; set; } = new List<UnitType>(); }sealed class SitesFile { public List<Site> Sites { get; set; } = new List<Site>(); }sealed class ProjectsFile { public List<ProjectKind> Projects { get; set; } = new List<ProjectKind>(); }@@ -393,6 +394,12 @@ namespace Statecraft.Sim// R-POP-001: validate the identity-specific scale without altering old content reads/hash inputs.if (c.UsesPopulationLedger) _ = c.PopulationPeoplePerUnit;ApplyMapOverrides(readFile, c, settlementIds); // after the map's own checks, before the GDD records that read it+ // R-CITY-006: no read or hash input in either old identity. Absence leaves the capability inactive.+ if (c.Ruleset == SaveGame.Gdd03Ruleset)+ {+ var regions = ReadOptional<PlayerRegionsFile>(readFile, PlayerRegionCatalogue.FileName);+ if (regions != null) c.PlayerRegions = PlayerRegionCatalogue.Validate(c, regions.PlayerRegions);+ }if (c.IsGdd){// GDD v0.1 city data (Phase 1 PR 3), read once eras.yaml is known to be valid. Only the GDD loop reads it, sodiff --git a/sim/Statecraft.Sim/GameState.cs b/sim/Statecraft.Sim/GameState.csindex 44b727614..5e7034116 100644--- a/sim/Statecraft.Sim/GameState.cs+++ b/sim/Statecraft.Sim/GameState.cs@@ -31,6 +31,17 @@ namespace Statecraft.Simreadonly bool usesAttention = true;public bool UsesPopulationLedger => Ruleset == SaveGame.Gdd03Ruleset;public PopulationLedger PopulationLedger { get; private set; } = new PopulationLedger(false);+ SortedDictionary<string, PlayerRegionPool> playerRegions = new SortedDictionary<string, PlayerRegionPool>(StringComparer.Ordinal);+ PlayerRegionCatalogue playerGeography = PlayerRegionCatalogue.Empty;+ public IReadOnlyDictionary<string, PlayerRegionPool> PlayerRegions =>+ new System.Collections.ObjectModel.ReadOnlyDictionary<string, PlayerRegionPool>(playerRegions);+ internal void InitializePlayerRegions(PlayerRegionCatalogue geography, SortedDictionary<string, PlayerRegionPool> pools)+ {+ if (!UsesPopulationLedger || !PopulationLedger.IsInitialized || playerRegions.Count != 0)+ throw new InvalidOperationException("Regional state needs an initialized gdd-0.3 fixture ledger.");+ playerGeography = geography;+ playerRegions = new SortedDictionary<string, PlayerRegionPool>(pools, StringComparer.Ordinal);+ }public GameState() { }internal GameState(Content c){@@ -136,6 +147,8 @@ namespace Statecraft.Simc.Budget = new Dictionary<string, double>(Budget);c.Population = new Dictionary<string, double>(Population);c.PopulationLedger = PopulationLedger.Clone();+ // Pool records, facilities and geography are immutable; only the owning collection needs a copy.+ c.playerRegions = new SortedDictionary<string, PlayerRegionPool>(playerRegions, StringComparer.Ordinal);c.FiredEvents = new SortedSet<string>(FiredEvents, StringComparer.Ordinal);c.PendingEvents = new List<string>(PendingEvents);c.ChosenOptions = new Dictionary<string, string>(ChosenOptions);@@ -270,6 +283,11 @@ namespace Statecraft.Simif (SoldiersHeld.Count > 0) Section("ownheld", '{', '}', Counts(SoldiersHeld));if (DisplacedByPlayer != 0) { Sep(); Nl(); sb.Append("displaced=").Append(DisplacedByPlayer.ToString(CultureInfo.InvariantCulture)); } // R-CTRL-019: only after a Deportif (UsesPopulationLedger) Section("population-ledger", '{', '}', PopulationLedger.Canonical());+ if (UsesPopulationLedger && playerRegions.Count > 0)+ {+ Section("player-geography", '{', '}', playerGeography.Regions.Values.SelectMany(r => r.Canonical()));+ Section("player-regions", '{', '}', playerRegions.Values.Select(r => r.Canonical()));+ }return sb.ToString();}}diff --git a/sim/Statecraft.Sim/GddState.cs b/sim/Statecraft.Sim/GddState.csindex c2191f715..96f829765 100644--- a/sim/Statecraft.Sim/GddState.cs+++ b/sim/Statecraft.Sim/GddState.cs@@ -5,6 +5,64 @@ using System.Linq;namespace Statecraft.Sim{+ public enum PlayerRegionFacilityKind { Industry, Workshop, Reception, Training }++ /// <summary>Explicit fixture capacity contribution. Its stable id may be counted only once nationally.</summary>+ public sealed class PlayerRegionFacility+ {+ public string Id { get; }+ public string Location { get; }+ public PlayerRegionFacilityKind Kind { get; }+ public int Capacity { get; }+ public PlayerRegionFacility(string id, string location, PlayerRegionFacilityKind kind, int capacity)+ {+ if (string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(location) || capacity < 0+ || !Enum.IsDefined(typeof(PlayerRegionFacilityKind), kind)) throw new ArgumentException("Explicit facility identity, kind and nonnegative capacity required.");+ PopulationText.ValidateText(id); PopulationText.ValidateText(location);+ Id = id; Location = location; Kind = kind; Capacity = capacity;+ }+ internal string Canonical() => PopulationText.Fields(Id, Location, Kind.ToString(), Capacity);+ }++ /// <summary>Immutable regional capacity record, with base values separate from uniquely owned contributions.+ /// All quantities must be supplied; there is no start allocation or old-city fallback.</summary>+ public sealed class PlayerRegionPool+ {+ public string Id { get; }+ public int BaseOrdinaryHousing { get; }+ public int BaseIndustrySlots { get; }+ public int BaseWorkshopSlots { get; }+ public decimal Condition { get; }+ public IReadOnlyList<PlayerRegionFacility> Facilities { get; }+ public int OrdinaryHousing => BaseOrdinaryHousing;+ public int IndustrySlots => checked(BaseIndustrySlots + Capacity(PlayerRegionFacilityKind.Industry));+ public int WorkshopSlots => checked(BaseWorkshopSlots + Capacity(PlayerRegionFacilityKind.Workshop));+ public int ReceptionBeds => Capacity(PlayerRegionFacilityKind.Reception);+ public int TrainingBeds => Capacity(PlayerRegionFacilityKind.Training);+ public PlayerRegionPool(string id, int ordinaryHousing, decimal condition, int industrySlots, int workshopSlots,+ IEnumerable<PlayerRegionFacility> facilities)+ {+ if (string.IsNullOrWhiteSpace(id) || ordinaryHousing < 0 || industrySlots < 0 || workshopSlots < 0 || condition < 0m || condition > 1m)+ throw new ArgumentException("Explicit region id, nonnegative capacities and a condition fraction from zero to one required.");+ PopulationText.ValidateText(id);+ Id = id; BaseOrdinaryHousing = ordinaryHousing; Condition = condition;+ BaseIndustrySlots = industrySlots; BaseWorkshopSlots = workshopSlots;+ var rows = facilities.OrderBy(f => f.Id, StringComparer.Ordinal).ToArray();+ if (rows.Select(f => f.Id).Distinct(StringComparer.Ordinal).Count() != rows.Length) throw new ArgumentException("Duplicate facility id.");+ Facilities = Array.AsReadOnly(rows);+ // Validate sums before a record can enter a state.+ _ = IndustrySlots; _ = WorkshopSlots; _ = ReceptionBeds; _ = TrainingBeds;+ }+ int Capacity(PlayerRegionFacilityKind kind)+ {+ int sum = 0;+ foreach (var f in Facilities) if (f.Kind == kind) sum = checked(sum + f.Capacity);+ return sum;+ }+ internal string Canonical() => PopulationText.Fields(Id, BaseOrdinaryHousing, Condition, BaseIndustrySlots,+ BaseWorkshopSlots, string.Join(";", Facilities.Select(f => f.Canonical())));+ }+/// <summary>One settlement's control state. Residents are a state, inhabited (the default) or depopulated, never a count/// or a combatant field (Q-CAP-2 (b); R-CTRL-003). Immutable so <see cref="GameState.Clone"/> can copy the containing map/// shallowly.</summary>diff --git a/sim/Statecraft.Sim/PlayerRegions.cs b/sim/Statecraft.Sim/PlayerRegions.csnew file mode 100644index 000000000..3d26bb76d--- /dev/null+++ b/sim/Statecraft.Sim/PlayerRegions.cs@@ -0,0 +1,193 @@+using System;+using System.Collections.Generic;+using System.Collections.ObjectModel;+using System.Linq;++namespace Statecraft.Sim+{+ /// <summary>Authored geography only. No capacities, residents, control predicate or production defaults.</summary>+ public sealed class PlayerRegionDefinition+ {+ public string Id { get; set; } = "";+ public string CapitalLocation { get; set; } = "";+ public List<PlayerRegionHex> MemberHexes { get; set; } = new List<PlayerRegionHex>();+ public List<string> MemberLocations { get; set; } = new List<string>();+ public string DesignNote { get; set; } = "";+ public List<string> Sources { get; set; } = new List<string>();+ public string CapitalApproval { get; set; } = "";+ public string BindingStatus { get; set; } = "";+ public PlayerRegionControl OpeningControl { get; set; } = new PlayerRegionControl();+ }++ public sealed class PlayerRegionHex+ {+ public int? Q { get; set; }+ public int? R { get; set; }+ }++ /// <summary>Evidence metadata, never an operational permission or inherited member control.</summary>+ public sealed class PlayerRegionControl+ {+ public string Status { get; set; } = "";+ // Object preserves YAML null through the loader's string normalization. Validation accepts only null or string.+ public object? Value { get; set; }+ }++ /// <summary>Frozen validated row. Consumers cannot mutate the authored DTO behind an index.</summary>+ public sealed class PlayerRegionGeography+ {+ public string Id { get; }+ public string CapitalLocation { get; }+ public IReadOnlyList<(int Q, int R)> MemberHexes { get; }+ public IReadOnlyList<string> MemberLocations { get; }+ public string DesignNote { get; }+ public IReadOnlyList<string> Sources { get; }+ public string CapitalApproval { get; }+ public string BindingStatus { get; }+ public string ControlStatus { get; }+ public string? OpeningController { get; }+ internal PlayerRegionGeography(PlayerRegionDefinition row)+ {+ Id = row.Id; CapitalLocation = row.CapitalLocation;+ MemberHexes = Array.AsReadOnly(row.MemberHexes.Select(h => (h.Q!.Value, h.R!.Value))+ .OrderBy(h => h.Item1).ThenBy(h => h.Item2).ToArray());+ MemberLocations = Array.AsReadOnly(row.MemberLocations.OrderBy(x => x, StringComparer.Ordinal).ToArray());+ DesignNote = row.DesignNote; Sources = Array.AsReadOnly(row.Sources.OrderBy(x => x, StringComparer.Ordinal).ToArray());+ CapitalApproval = row.CapitalApproval; BindingStatus = row.BindingStatus;+ ControlStatus = row.OpeningControl.Status;+ OpeningController = row.OpeningControl.Value as string;+ }+ internal IEnumerable<string> Canonical()+ {+ yield return PopulationText.Fields("region", Id, CapitalLocation);+ foreach (var h in MemberHexes) yield return PopulationText.Fields("hex", h.Q, h.R);+ foreach (var p in MemberLocations) yield return PopulationText.Fields("place", p);+ }+ }++ /// <summary>R-CITY-006. One validator and one immutable exact-identity geography index for all consumers.</summary>+ public sealed class PlayerRegionCatalogue+ {+ public const string FileName = "regions.yaml";+ readonly SortedDictionary<string, PlayerRegionGeography> regions = new SortedDictionary<string, PlayerRegionGeography>(StringComparer.Ordinal);+ readonly Dictionary<string, string> places = new Dictionary<string, string>(StringComparer.Ordinal);+ readonly Dictionary<string, string> capitals = new Dictionary<string, string>(StringComparer.Ordinal);+ readonly Dictionary<(int, int), string> hexes = new Dictionary<(int, int), string>();+ public IReadOnlyDictionary<string, PlayerRegionGeography> Regions { get; }+ public static PlayerRegionCatalogue Empty { get; } = new PlayerRegionCatalogue();+ PlayerRegionCatalogue() { Regions = new ReadOnlyDictionary<string, PlayerRegionGeography>(regions); }+ public PlayerRegionGeography? AtLocation(string id) => places.TryGetValue(id, out var r) ? regions[r] : null;+ public PlayerRegionGeography? AtCapital(string id) => capitals.TryGetValue(id, out var r) ? regions[r] : null;+ public PlayerRegionGeography? AtHex(int q, int r) => hexes.TryGetValue((q, r), out var id) ? regions[id] : null;++ internal static PlayerRegionCatalogue Validate(Content c, IEnumerable<PlayerRegionDefinition> rows)+ {+ var result = new PlayerRegionCatalogue();+ var placements = new Dictionary<string, (int, int)>(StringComparer.Ordinal);+ var conflicts = new HashSet<string>(StringComparer.Ordinal);+ void Place(string id, int q, int r)+ {+ if (placements.TryGetValue(id, out var prior) && prior != (q, r)) conflicts.Add(id);+ placements[id] = (q, r);+ }+ foreach (var p in c.SettlementHexes) Place(p.Id, p.Q, p.R);+ foreach (var p in c.MapLocations) Place(p.Id, p.Q, p.R);+ int index = 0;+ foreach (var row in rows)+ {+ var at = FormattableString.Invariant($"player_regions[{index++}]");+ void Fail(string field, string reason) => throw new ContentException(FileName, at + "." + field, reason);+ if (string.IsNullOrWhiteSpace(row.Id) || !Offices.OfficeId.IsMatch(row.Id)) Fail("id", "requires a stable id");+ if (result.regions.ContainsKey(row.Id)) Fail("id", "duplicate region id");+ if (string.IsNullOrWhiteSpace(row.DesignNote)) Fail("design_note", "required; geography is a design choice");+ if (row.Sources.Count == 0 || row.Sources.Any(string.IsNullOrWhiteSpace)) Fail("sources", "explicit provenance required");+ if (row.CapitalApproval != "APPROVED" && row.CapitalApproval != "NEEDS-RESEARCH") Fail("capital_approval", "must be APPROVED or NEEDS-RESEARCH");+ if (row.BindingStatus != "SOURCED" && row.BindingStatus != "PARTIAL-EVIDENCE" && row.BindingStatus != "NEEDS-RESEARCH") Fail("binding_status", "unknown evidence status");+ if (row.OpeningControl == null) Fail("opening_control", "required");+ var control = row.OpeningControl!;+ if (control.Status != "SOURCED" && control.Status != "PARTIAL-EVIDENCE" && control.Status != "NEEDS-RESEARCH") Fail("opening_control.status", "unknown evidence status");+ if (control.Status == "SOURCED" ? !(control.Value is string value) || string.IsNullOrWhiteSpace(value) : control.Value != null)+ Fail("opening_control.value", "SOURCED needs a string value; unconfirmed control must stay null");+ if (control.Value is string controller)+ {+ try { PopulationText.ValidateText(controller); }+ catch (ArgumentException) { Fail("opening_control.value", "must be well-formed UTF-16"); }+ }+ if (row.MemberHexes.Count == 0) Fail("member_hexes", "must not be empty");+ var ownHexes = new HashSet<(int, int)>();+ for (int i = 0; i < row.MemberHexes.Count; i++)+ {+ var h = row.MemberHexes[i]; var field = FormattableString.Invariant($"member_hexes[{i}]");+ if (!h.Q.HasValue || !h.R.HasValue) Fail(field, "q and r are required integers");+ var key = (h.Q!.Value, h.R!.Value);+ if (!ownHexes.Add(key)) Fail(field, "duplicate member hex");+ if (c.HexAt(key.Item1, key.Item2)?.Land != true) Fail(field, "must name an existing land hex");+ if (result.hexes.ContainsKey(key)) Fail(field, "hex already belongs to another region");+ }+ if (row.MemberLocations.Count == 0) Fail("member_locations", "must not be empty");+ var ownPlaces = new HashSet<string>(StringComparer.Ordinal);+ for (int i = 0; i < row.MemberLocations.Count; i++)+ {+ var id = row.MemberLocations[i]; var field = FormattableString.Invariant($"member_locations[{i}]");+ if (string.IsNullOrWhiteSpace(id) || !placements.TryGetValue(id, out var hex)) { Fail(field, "unknown place id"); continue; }+ if (conflicts.Contains(id)) Fail(field, "settlement and named location have inconsistent effective placements");+ if (!ownPlaces.Add(id)) Fail(field, "duplicate member location");+ if (result.places.ContainsKey(id)) Fail(field, "location already belongs to another region");+ if (!ownHexes.Contains(hex)) Fail(field, "effective location lies outside member_hexes");+ }+ if (string.IsNullOrWhiteSpace(row.CapitalLocation) || !ownPlaces.Contains(row.CapitalLocation)) Fail("capital_location", "must name a member location on a member hex");+ var frozen = new PlayerRegionGeography(row);+ result.regions.Add(row.Id, frozen); result.capitals.Add(row.CapitalLocation, row.Id);+ foreach (var h in ownHexes) result.hexes.Add(h, row.Id);+ foreach (var p in ownPlaces) result.places.Add(p, row.Id);+ }+ return result;+ }+ }++ /// <summary>Shared fixture boundary; production initialization, relocation and job commands have separate owners.</summary>+ public static class PlayerRegions+ {+ internal static GameState CreateFixture(Content c, IEnumerable<PlayerRegionPool> starts,+ IEnumerable<PopulationInventoryRow> people, IEnumerable<PopulationTarget> targets,+ IEnumerable<string> captors, IEnumerable<string> qualifications)+ {+ if (c.Ruleset != SaveGame.Gdd03Ruleset) throw new InvalidOperationException("Regional fixtures require gdd-0.3.");+ var pools = new SortedDictionary<string, PlayerRegionPool>(StringComparer.Ordinal);+ var facilities = new HashSet<string>(StringComparer.Ordinal);+ var locations = new List<PopulationLocation>();+ foreach (var r in c.PlayerRegions.Regions.Values)+ foreach (var h in r.MemberHexes) locations.Add(new PopulationLocation(r.Id, h.Q, h.R));+ foreach (var pool in starts)+ {+ if (!c.PlayerRegions.Regions.TryGetValue(pool.Id, out var region)) throw new ArgumentException("Unknown starting region.");+ pools.Add(pool.Id, pool);+ foreach (var f in pool.Facilities)+ {+ if (!facilities.Add(f.Id) || !region.MemberLocations.Contains(f.Location))+ throw new ArgumentException("Facility must have one owning region and a member location.");+ // A dedicated facility is an explicit ledger address, never an extra population pool.+ locations.Add(new PopulationLocation(region.Id, facilityOrPort: f.Id));+ }+ }+ if (!pools.Keys.SequenceEqual(c.PlayerRegions.Regions.Keys)) throw new ArgumentException("Every fixture region needs an explicit start.");+ var bindings = new PopulationBindings(locations, targets, captors, qualifications);+ var state = PopulationLedger.CreateFixture(c, bindings, people);+ state.InitializePlayerRegions(c.PlayerRegions, pools);+ return state;+ }++ /// <summary>All own people currently located here, not ordinary-housing occupancy or civilian eligibility.</summary>+ public static int PresentPopulation(GameState state, string region)+ {+ if (!state.PlayerRegions.ContainsKey(region)) throw new ArgumentException("Unknown initialized region.");+ return state.PopulationLedger.Units.Count(p => p.Location?.Region == region);+ }++ public static int Assigned(GameState state, string region, PopulationAssignmentKind kind)+ {+ if (!state.PlayerRegions.ContainsKey(region)) throw new ArgumentException("Unknown initialized region.");+ return state.PopulationLedger.Units.Count(p => p.Location?.Region == region && p.Assignment.Kind == kind);+ }+ }+}