diff --git a/CLAUDE.md b/CLAUDE.md index 5c3caae..d9f07e5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -6,7 +6,7 @@ tests in `OptimizedLocalHousing.Tests/`, packaging in `package.ps1`, the website PR → merge. - **Tests (what CI runs, `.github/workflows/tests.yml`, SDK 8):** `dotnet run --project OptimizedLocalHousing.Tests -c Release` - must end with `40 checks passed.` (41 exist; the compiled-adapter check needs the built mod and the game, so it runs + must end with `45 checks passed.` (46 exist; the compiled-adapter check needs the built mod and the game, so it runs only locally with two extra arguments; see `DEVELOPING.md`). - **Build and package** (needs a local Timberborn install; never done in CI): see `DEVELOPING.md`, then `./package.ps1`. @@ -152,7 +152,7 @@ When asked to "update the website for the latest release, consistent with the de `ul.checks.never`; tested / not yet → `.status-grid` `ul.checks` / `ul.checks.open`; a log message → a troubleshooting table row plus a `details.q` with an `id`; a question → `details.q` with `div.answer` in the right FAQ group; evidence → `dl.fields`; install steps → `ol.steps`. Don't restyle anything. -4. Test: `dotnet run --project OptimizedLocalHousing.Tests -c Release` (ends `40 checks passed.`). There is no site +4. Test: `dotnet run --project OptimizedLocalHousing.Tests -c Release` (ends `45 checks passed.`). There is no site test in CI; check the contracts in PRODUCT.md by hand, the release.js hash above, and the seating demo numbers. 5. Preview: `python -m http.server 8784 -d docs` (background), then open http://localhost:8784/. Capture light, dark and a 390px phone. If the personal `impeccable-site-flow` skill is available, use diff --git a/DEVELOPING.md b/DEVELOPING.md index 2e12e11..91d1487 100644 --- a/DEVELOPING.md +++ b/DEVELOPING.md @@ -17,8 +17,9 @@ dotnet run --project OptimizedLocalHousing.Tests -c Release -- OptimizedLocalHou ./package.ps1 ``` -The tests cover the solver against brute force, pause/resume at every row, cycle splitting, optimality on -random colonies with one to three districts, route queries that stay inside a district, each district solved on +The tests cover the solver against brute force, pause/resume at every row, splitting moves into cycles and chains, +optimality on random colonies with one to three districts, with and without empty beds, homes that can breed never +fewer after a pass, route queries that stay inside a district, each district solved on its own (the same homes as a colony of that district alone, in no more ticks), the safety rules in the README, stale-world handling, route costs carried from one pass to the next and priced again when they come due, determinism between peers, save/reload at every tick of three passes (the first, the next, and the one where the @@ -31,22 +32,33 @@ the installed game's component blacklist. Omitting the two arguments skips the c `GameAdapter.cs` is the thin bridge to the game; `PassEngine.cs` and `Assignment.cs` hold everything else. Each pass: -1. **Capture.** Every housed adult beaver, its home, and its assigned workplace. +1. **Capture.** Every housed adult beaver, its home, and its assigned workplace, and every usable home with an + empty bed. 2. **Price.** For every workplace, real route costs (`Accessible.FindRoadPath`, so ziplines and stairs count) from the 32 nearest homes in its district. Homes in other districts are never queried, because the game's route search never leaves a district. Homes farther away are estimated, and any move to one is re-checked with a real route before it is allowed. -3. **Solve.** The optimal way to reassign the adults to the beds that adults occupy today (the Hungarian - algorithm). Nobody moves between districts, so each district is solved on its own, one after another. In a +3. **Solve.** The optimal way to reassign the adults to the district's beds: the ones adults occupy today and the + empty ones (the Hungarian algorithm, with more beds than adults). Children keep their beds. As in the game, a + third of a home's beds (rounded down) are for children and the rest for adults, and the game moves an adult out of + a home with more adults than adult beds. So the empty beds an adult may take are the free beds, but no more than + the adult beds left (`HomeRules.FreeForAdults`). Nobody moves between districts, so each district is solved on its own, one after another. In a colony with several districts that takes far fewer ticks and far less memory than solving them as one (47 solve ticks instead of 157 for four districts of 300 adults), and reaches the same optimum. 4. **Verify.** Every proposed move is re-priced with fresh routes. A whole cycle of moves is dropped if it would - leave a beaver who can reach work today unable to, and each cycle must save at least half a route-cost unit in - total. The fresh costs of homes beyond the 32 nearest are remembered in place of estimates, so a move that was + leave a beaver who can reach work today unable to, and each cycle or chain must save at least half a route-cost + unit in total. A chain is also dropped if it would leave the colony fewer homes that can breed. The rule is the + Folktails' (`ProcreationHouse`, `HomeRules.CanBreed`): at least two adults, a free bed, and fewer children than + the home's child beds and than half its adults, rounded down. The game then rolls an 18.75% chance each time an + adult comes home. The solver doesn't know this rule, so a chain it drops is proposed again the next day + and dropped again, until the colony changes. The fresh costs of homes beyond the 32 nearest are remembered in place of estimates, so a move that was turned down is not proposed again every day (anything proposed is still re-priced first). A remembered cost is used for seven passes. The seventh prices it again, and keeps it, if one of that workplace's workers lives in the home or if there was no route (so a road that comes back is noticed); otherwise it lapses to the estimate. -5. **Apply.** Moves are applied as whole cycles (A takes B's bed, B takes C's, C takes A's), in one game tick. +5. **Apply.** Moves are applied as whole cycles (A takes B's bed, B takes C's, C takes A's) or chains (A takes an + empty bed, B takes A's, C takes B's), in one game tick. A cycle keeps every home's head count; a chain frees a bed + where it starts and fills one where it ends. If the game has filled that empty bed since the snapshot, the chain + is skipped as stale. Each beaver gets a one-route-cost-unit bonus for staying put (`StayBonus`), so a rearrangement must save at least one unit for every beaver it moves. diff --git a/OptimizedLocalHousing.Tests/Program.cs b/OptimizedLocalHousing.Tests/Program.cs index ae0230e..35e8697 100644 --- a/OptimizedLocalHousing.Tests/Program.cs +++ b/OptimizedLocalHousing.Tests/Program.cs @@ -23,12 +23,26 @@ public Snapshot Capture() foreach (var p in people) { if (!p.Adult || !Homes.TryGetValue(p.Home, out var h) || !h.Usable) continue; - b.AddHome(p.Home, h.District, h.X, h.Y, h.Z); + b.AddHome(p.Home, h.District, h.X, h.Y, h.Z, h.Capacity, AdultsIn(p.Home), ChildrenIn(p.Home)); var work = Job(p); if (work != Guid.Empty) b.AddWork(work, Works[work].X, Works[work].Y, Works[work].Z); b.AddAdult(p.Id, p.Home, work, p.District); } + // Like the game, every usable home, lived in or not. + foreach (var h in Reverse ? Homes.Reverse() : Homes) if (h.Value.Usable) b.AddHome(h.Key, h.Value.District, h.Value.X, h.Value.Y, h.Value.Z, h.Value.Capacity, AdultsIn(h.Key), ChildrenIn(h.Key)); return b.Build(); } + // Like the game (Dwelling): a third of the beds, rounded down, are for children, the rest for adults. + public int AdultsIn(Guid home) => People.Values.Count(p => p.Adult && p.Home == home); + public int ChildrenIn(Guid home) => People.Values.Count(p => !p.Adult && p.Home == home); + public int AdultBeds(Guid home) => Homes[home].Capacity - Homes[home].Capacity / 3; + // Like the Folktails' ProcreationHouse: two adults, a free bed, and fewer children than the child beds and than + // half the adults. + public bool CanBreed(Guid home) + { + int adults = AdultsIn(home), children = ChildrenIn(home), beds = Homes[home].Capacity; + return adults >= 2 && adults + children < beds && children < beds / 3 && children < adults / 2; + } + public int BreedingHomes() => Homes.Keys.Count(CanBreed); public Guid DistrictOf(Guid work) => WorkDistrict.TryGetValue(work, out var d) ? d : G(9000); // Like the game, a workplace in another district is no job at all. public Guid Job(Person p) => p.Work != Guid.Empty && Works.ContainsKey(p.Work) && DistrictOf(p.Work) == p.District ? p.Work : Guid.Empty; @@ -52,6 +66,8 @@ public bool ApplyCycle(Move[] cycle) delta[m.From] = delta.GetValueOrDefault(m.From) - 1; delta[m.To] = delta.GetValueOrDefault(m.To) + 1; } foreach (var d in delta) if (People.Values.Count(p => p.Home == d.Key) + d.Value > Homes[d.Key].Capacity) return false; + // The game moves an adult out of a home with more adults than adult beds, so the adapter never makes one. + foreach (var d in delta) if (d.Value > 0 && AdultsIn(d.Key) + d.Value > AdultBeds(d.Key)) return false; foreach (var m in cycle) People[m.Adult].Home = m.To; Applied.Add(string.Join(",", cycle.Select(m => $"{m.Adult.ToString()[..4]}>{m.To.ToString()[..4]}"))); return true; @@ -92,6 +108,16 @@ static Fake Colony(int seed, int homes, int adults, int works, int children = 0, foreach (var h in keys) f.Homes[h].Capacity = f.People.Values.Count(p => p.Home == h); return f; } + // Adds empty beds: a spare bed in about one home in four, and a few empty homes in each district (laid out as Colony does). + static Fake Spare(Fake f, int seed, int emptyHomes = 3, int width = 60) + { + var rng = new Random(seed); var districts = f.Homes.Values.Select(h => h.District).Distinct().OrderBy(d => d).ToList(); + foreach (var h in f.Homes.OrderBy(h => h.Key)) if (rng.Next(0, 4) == 0) h.Value.Capacity++; + for (int d = 0; d < districts.Count; d++) + for (int k = 0; k < emptyHomes; k++) + f.Homes[G(7000 + 10 * d + k)] = new Home { Capacity = rng.Next(1, 4), X = (BitConverter.ToInt32(districts[d].ToByteArray(), 0) - 9000) * width + rng.Next(0, width), Y = rng.Next(0, 60), Z = rng.Next(0, 3), District = districts[d] }; + return f; + } // Fills the homes in turn with adults; each works in its own district, as the game requires, or 1 in 8 has no job. static void Populate(Fake f, Random rng, int adults) { @@ -181,21 +207,25 @@ static int LearnedInUse(PassState state) } return used; } - // Best objective any arrangement of the adults into the existing beds can reach (route cost minus stay bonuses). + // Best objective any arrangement of the adults into the district's beds, occupied or empty, can reach (route cost + // minus stay bonuses). Children keep their beds, and paused homes their adults. static long Best(Fake f) { var adults = f.People.Values.Where(p => p.Adult).OrderBy(p => p.Id).ToList(); int n = adults.Count; - var beds = adults.Select(a => a.Home).ToList(); long best = long.MaxValue; var perm = Enumerable.Range(0, n).ToArray(); + var homes = f.Homes.Keys.OrderBy(k => k).ToList(); + // An adult keeps its bed, and may take an empty one while the home has adult beds to spare. + var room = homes.Select(h => f.Homes[h].Usable ? Math.Max(f.AdultsIn(h), Math.Min(f.Homes[h].Capacity - f.ChildrenIn(h), f.AdultBeds(h))) : 0).ToArray(); + long best = long.MaxValue; long Cost1(Person a, Guid bed) => (f.Job(a) != Guid.Empty ? Cost.Fixed(f.Route(bed, a.Work)) : 0) - (bed == a.Home ? Cost.StayBonus : 0); void Go(int k, long sum) { if (k == n) { best = Math.Min(best, sum); return; } - for (int i = k; i < n; i++) + var a = adults[k]; + if (!f.Homes[a.Home].Usable) { Go(k + 1, sum + Cost1(a, a.Home)); return; } // a paused home's adult stays + for (int h = 0; h < homes.Count; h++) { - if (f.Homes[beds[perm[i]]].District != adults[k].District) continue; // nobody crosses districts - (perm[k], perm[i]) = (perm[i], perm[k]); - Go(k + 1, sum + Cost1(adults[k], beds[perm[k]])); - (perm[k], perm[i]) = (perm[i], perm[k]); + if (room[h] == 0 || f.Homes[homes[h]].District != a.District) continue; // nobody crosses districts + room[h]--; Go(k + 1, sum + Cost1(a, homes[h])); room[h]++; } } Go(0, 0); return best; @@ -260,6 +290,36 @@ static void Run(string[] args) bool threw = false; try { Cycles.Split(3, new[] { 0 }, new[] { 1 }); } catch (InvalidOperationException) { threw = true; } Check(threw, "Unbalanced graph accepted"); }); + Test("moves into empty beds split into chains and cycles, each applicable on its own", () => { + var rng = new Random(4); + for (int trial = 0; trial < 300; trial++) + { + // Adults in random homes with random spare beds, each sent to a random home with room for them all. + int nodes = rng.Next(2, 8); var room = Enumerable.Range(0, nodes).Select(_ => rng.Next(0, 4)).ToArray(); + var home = new List(); for (int h = 0; h < nodes; h++) for (int k = rng.Next(0, 4); k > 0; k--) home.Add(h); + var count = new int[nodes]; foreach (int h in home) count[h]++; + var cap = count.Select((c, h) => c + room[h]).ToArray(); var fill = new int[nodes]; + var from = new List(); var to = new List(); + foreach (int h in home) + { + var open = Enumerable.Range(0, nodes).Where(x => fill[x] < cap[x]).ToList(); int target = open[rng.Next(open.Count)]; fill[target]++; + if (target != h) { from.Add(h); to.Add(target); } + } + var a = Cycles.SplitChains(nodes, from.ToArray(), to.ToArray()); var b = Cycles.SplitChains(nodes, from.ToArray(), to.ToArray()); + Check(a.Count == b.Count && a.Zip(b).All(x => x.First.SequenceEqual(x.Second)), "Not deterministic"); + Check(a.SelectMany(x => x).OrderBy(x => x).SequenceEqual(Enumerable.Range(0, from.Count)), "Edges lost or repeated"); + foreach (var unit in a) + { + for (int i = 0; i + 1 < unit.Length; i++) Check(to[unit[i]] == from[unit[i + 1]], "Moves do not follow on"); + bool cycle = to[unit[^1]] == from[unit[0]]; + Check(unit.Select(e => from[e]).Distinct().Count() == unit.Length, "A home is left twice"); + // Alone, it keeps every home within its beds: a chain ends in a home with a spare bed. + var after = (int[])count.Clone(); foreach (int e in unit) { after[from[e]]--; after[to[e]]++; } + Check(Enumerable.Range(0, nodes).All(h => after[h] <= cap[h]), "Applied alone, a unit overfills a home"); + if (cycle) Check(after.SequenceEqual(count), "A cycle changed a head count"); + } + } + }); Test("the pass reaches the true optimum (brute force) on random small colonies", () => { for (int seed = 0; seed < 100; seed++) @@ -273,6 +333,94 @@ static void Run(string[] args) Check(kids.All(k => f.People[k.Key].Home == k.Value), "A child moved"); } }); + Test("with empty beds, the pass reaches the true optimum (brute force) unless the breeding rule turns a move down", () => { + for (int seed = 0; seed < 100; seed++) + { + var f = Colony(seed, homes: 3 + seed % 3, adults: 5 + seed % 3, works: 3, children: seed % 3, districts: seed < 60 ? 1 : 2 + seed % 2); + var rng = new Random(seed); + foreach (var h in f.Homes.Values) h.Capacity += rng.Next(0, 3) == 0 ? rng.Next(1, 3) : 0; + for (int k = 0; k < 1 + seed % 2; k++) + { + int d = rng.Next(0, seed < 60 ? 1 : 2 + seed % 2); // an empty home in district d, laid out as Colony does + f.Homes[G(900 + k)] = new Home { Capacity = rng.Next(1, 3), X = d * 60 + rng.Next(0, 60), Y = rng.Next(0, 60), District = G(9000 + d) }; + } + StartHome = f.People.ToDictionary(p => p.Key, p => p.Value.Home); + long best = Best(f); var kids = f.People.Values.Where(p => !p.Adult).ToDictionary(p => p.Id, p => p.Home); + int breeding = f.BreedingHomes(); var e = Run(f); + // The breeding rule can turn a chain down, and only then may the result fall short of the optimum. + Check(e.LastReport.Rejected > 0 ? Achieved(f) >= best : Achieved(f) == best, $"seed {seed}: objective {Achieved(f)} but optimum is {best}"); + Check(f.BreedingHomes() >= breeding, $"seed {seed}: fewer homes can breed"); + foreach (var h in f.Homes) Check(f.People.Values.Count(p => p.Home == h.Key) <= h.Value.Capacity, $"seed {seed}: home over capacity"); + Check(kids.All(k => f.People[k.Key].Home == k.Value), "A child moved"); + Check(f.People.Values.All(p => f.Homes[p.Home].District == p.District), "Someone crossed districts"); + } + }); + Test("a worker moves into an empty home beside the workplace, and a second pass changes nothing", () => { + var f = new Fake(); f.Works[G(500)] = (0, 0, 0); + f.Homes[G(1)] = new Home { Capacity = 2, X = 40 }; // the worker's lodge, far away and full + f.Homes[G(2)] = new Home { Capacity = 1, X = 1 }; // an empty mini lodge beside the workplace + f.Homes[G(3)] = new Home { Capacity = 1, X = 2, Usable = false }; // a paused one, nearer still than the lodge + f.People[G(10)] = new Person { Id = G(10), Home = G(1), Work = G(500), District = G(9000) }; + f.People[G(11)] = new Person { Id = G(11), Home = G(1), District = G(9000) }; // unemployed: stays + var e = Run(f); + Check(f.People[G(10)].Home == G(2) && f.People[G(11)].Home == G(1), "The worker was not moved beside work"); + Check(e.LastReport.Applied == 1 && e.LastReport.RouteCostSaved == 39, $"Report: {e.LastReport.Applied} applied, {e.LastReport.RouteCostSaved} saved"); + var fp = f.Fingerprint(); Run(f, Reload(e.State)); Check(f.Fingerprint() == fp, "A settled colony was reshuffled"); + // A lone adult is moved too. + f.People.Remove(G(11)); f.People[G(10)].Home = G(1); Run(f); Check(f.People[G(10)].Home == G(2), "A lone worker stayed far away"); + }); + Test("a move into an empty bed is turned down if it leaves fewer homes that can breed", () => { + // Two adults and an empty bed can breed: the worker stays, since the lodge beside work has one bed and can't. + var f = new Fake(); f.Works[G(500)] = (0, 0, 0); + f.Homes[G(1)] = new Home { Capacity = 3, X = 40 }; f.Homes[G(2)] = new Home { Capacity = 1, X = 1 }; + f.People[G(10)] = new Person { Id = G(10), Home = G(1), Work = G(500), District = G(9000) }; + f.People[G(11)] = new Person { Id = G(11), Home = G(1), District = G(9000) }; + var e = Run(f); Check(f.People[G(10)].Home == G(1) && e.LastReport.Rejected == 1, "A breeding home was broken up"); + // The same move into a two-bed home beside work that already holds an adult makes a new breeding home: allowed. + f.Homes[G(2)].Capacity = 3; f.People[G(12)] = new Person { Id = G(12), Home = G(2), District = G(9000) }; + Run(f); Check(f.People[G(10)].Home == G(2), "A move that keeps the breeding homes was turned down"); + // The empty bed of a three-bed home with two adults is a child's bed: the worker only swaps with an adult there, + // so the home still breeds. + var g = new Fake(); g.Works[G(500)] = (0, 0, 0); + g.Homes[G(1)] = new Home { Capacity = 1, X = 40 }; g.Homes[G(2)] = new Home { Capacity = 3, X = 1 }; + g.People[G(10)] = new Person { Id = G(10), Home = G(1), Work = G(500), District = G(9000) }; + for (int i = 0; i < 2; i++) g.People[G(20 + i)] = new Person { Id = G(20 + i), Home = G(2), District = G(9000) }; + Run(g); Check(g.AdultsIn(G(2)) == 2 && g.AdultsIn(G(1)) == 1 && g.CanBreed(G(2)), "An adult took the child's bed of a breeding home"); + // The game's rule: a home with as many children as half its adults can't breed, so a worker may leave it. + var h = new Fake(); h.Works[G(500)] = (0, 0, 0); + h.Homes[G(1)] = new Home { Capacity = 6, X = 40 }; h.Homes[G(2)] = new Home { Capacity = 1, X = 1 }; + h.People[G(10)] = new Person { Id = G(10), Home = G(1), Work = G(500), District = G(9000) }; + h.People[G(11)] = new Person { Id = G(11), Home = G(1), District = G(9000) }; + h.People[G(12)] = new Person { Id = G(12), Home = G(1), District = G(9000), Adult = false }; + e = Run(h); Check(h.People[G(10)].Home == G(2) && e.LastReport.Rejected == 0, "A worker was kept in a home that can't breed"); + // Without the child it can: the move is turned down. + h.People.Remove(G(12)); h.People[G(10)].Home = G(1); + e = Run(h); Check(h.People[G(10)].Home == G(1) && e.LastReport.Rejected == 1, "A breeding home of six beds was broken up"); + }); + Test("passes over colonies with empty beds never leave fewer homes that can breed", () => { + int moved = 0; + for (int seed = 0; seed < 60; seed++) + { + var f = Spare(Colony(seed, homes: 30, adults: 70, works: 25, children: 8, districts: 1 + seed % 3), seed, emptyHomes: 4); + foreach (var h in f.Homes.Values) if (h.Capacity > 1 && seed % 2 == 0) h.Capacity++; // more homes that can breed + int before = f.BreedingHomes(); var counts = f.AdultCounts(); var adultsBefore = f.Homes.Keys.ToDictionary(h => h, f.AdultsIn); var kids = f.People.Values.Where(p => !p.Adult).ToDictionary(p => p.Id, p => p.Home); + var e = Run(f); var state = e.State; + for (int day = 0; day < 3; day++) + { + // Nothing changes between capture and apply here, so a stale chain means the engine offered a bed the + // game would refuse, such as a child's bed. + Check(e.LastReport.Stale == 0, $"seed {seed}: {e.LastReport.Stale} stale on day {day}"); + Check(f.BreedingHomes() >= before, $"seed {seed}: homes that can breed fell from {before} to {f.BreedingHomes()}"); + foreach (var h in f.Homes) Check(f.People.Values.Count(p => p.Home == h.Key) <= h.Value.Capacity, $"seed {seed}: home over capacity"); + foreach (var h in f.Homes.Keys) Check(f.AdultsIn(h) <= Math.Max(adultsBefore[h], f.AdultBeds(h)), $"seed {seed}: an adult took a child's bed"); + before = f.BreedingHomes(); adultsBefore = f.Homes.Keys.ToDictionary(h => h, f.AdultsIn); e = Run(f, Reload(state)); state = e.State; + } + Check(kids.All(k => f.People[k.Key].Home == k.Value), "A child moved"); + if (!f.AdultCounts().OrderBy(x => x.Key).SequenceEqual(counts.OrderBy(x => x.Key))) moved++; + } + Check(moved >= 30, $"Adults moved into empty beds in only {moved} of 60 colonies"); + Console.WriteLine($" 60 colonies with empty beds: head counts changed in {moved}, homes that can breed never fewer"); + }); Test("a badly housed colony gets much shorter commutes and no home changes its head count", () => { var f = Colony(1, homes: 90, adults: 240, works: 120, children: 20); double before = f.Total(); var counts = f.AdultCounts(); var e = Run(f); @@ -314,7 +462,7 @@ static void Run(string[] args) // Two districts of 45 homes: the second pass takes costs the first one verified outside the candidate rows. // Eight passes: the eighth prices again the first pass's costs that are still needed (a rejected swap each). foreach (var (name, start) in new[] { ("1 district", Colony(8, 50, 130, 60, 8)), ("3 districts", Colony(8, 50, 130, 60, 8, 3)), ("2 districts of 45 homes", Colony(8, 90, 230, 80, 8, 2)), - ("2 districts, a rejected swap each", FarSwap(2)) }) + ("2 districts, a rejected swap each", FarSwap(2)), ("3 districts with empty beds", Spare(Colony(8, 50, 130, 60, 8, 3), 8)) }) { var a = start.Copy(); var b = start.Copy(); var ea = new PassEngine(a); var eb = new PassEngine(b); int passes = 1, used = 0, rechecked = 0; for (int t = 0; t < 5000 && (ea.Busy || ea.State.Requested || passes < DuePass); t++) @@ -339,7 +487,7 @@ static void Run(string[] args) // Passes 1, 2 and 8 are checked; the eighth prices again the first pass's costs that are still needed. foreach (var (name, colony) in new[] { ("1 district", Colony(9, 45, 110, 55, 6)), ("3 districts", Colony(9, 45, 110, 55, 6, 3)), ("2 districts of 45 homes", Colony(9, 90, 220, 90, 6, 2)), ("2 districts, a rejected swap each", FarSwap(2)), ("16 districts, a rejected swap each", FarSwap(16)), ("padding tail", PaddingTail()), - ("6 districts, a solve tick ends with a district", Colony(0, 120, 400, 100, 0, 6)) }) + ("6 districts, a solve tick ends with a district", Colony(0, 120, 400, 100, 0, 6)), ("3 districts with empty beds", Spare(Colony(9, 45, 110, 55, 6, 3), 9)) }) { var start = colony; PassState saved = null; bool skipOnly = false; int used = 0, rechecked = 0, midSolve = 0, between = 0; var rejected = new List(); for (int pass = 1; pass <= DuePass; pass++) diff --git a/OptimizedLocalHousing/Assignment.cs b/OptimizedLocalHousing/Assignment.cs index f91792e..3584001 100644 --- a/OptimizedLocalHousing/Assignment.cs +++ b/OptimizedLocalHousing/Assignment.cs @@ -28,7 +28,7 @@ public static int Distance(int[] a, int i, int[] b, int j) => Math.Abs(a[i * 3] - b[j * 3]) + Math.Abs(a[i * 3 + 1] - b[j * 3 + 1]) + 2 * Math.Abs(a[i * 3 + 2] - b[j * 3 + 2]); } -// Minimum-cost perfect assignment of n rows to n columns (Hungarian algorithm, O(n^3)). +// Minimum-cost assignment of n rows to distinct columns among m >= n (Hungarian algorithm, O(n^2 m)). // The whole solver state is u, v, p and the next row, so it can be paused between rows and saved. public static class Hungarian { @@ -37,30 +37,34 @@ public static class Hungarian // After completion p[j] (1-based) is the row assigned to column j-1. public static bool Step(long[,] cost, int n, long[] u, long[] v, int[] p, ref int row, long budget, Func prepareRow) { - long ops = 0; return Step(cost, n, u, v, p, ref row, ref ops, budget, prepareRow); + long ops = 0; return Step(cost, n, n, u, v, p, ref row, ref ops, budget, prepareRow); } // The same, counting on from the work already spent (ops), so that one budget can span several assignments. - public static bool Step(long[,] cost, int n, long[] u, long[] v, int[] p, ref int row, ref long ops, long budget, Func prepareRow) + public static bool Step(long[,] cost, int n, long[] u, long[] v, int[] p, ref int row, ref long ops, long budget, Func prepareRow) => + Step(cost, n, n, u, v, p, ref row, ref ops, budget, prepareRow); + // The same for n rows and m columns (u has n + 1 entries, v and p m + 1; a column no row takes keeps p[j] = 0), + // also counting on from ops. + public static bool Step(long[,] cost, int n, int m, long[] u, long[] v, int[] p, ref int row, ref long ops, long budget, Func prepareRow) { - var way = new int[n + 1]; var minv = new long[n + 1]; var used = new bool[n + 1]; + var way = new int[m + 1]; var minv = new long[m + 1]; var used = new bool[m + 1]; while (row <= n && ops < budget) { ops += prepareRow(row - 1); p[0] = row; int j0 = 0; - for (int j = 0; j <= n; j++) { minv[j] = long.MaxValue; used[j] = false; } + for (int j = 0; j <= m; j++) { minv[j] = long.MaxValue; used[j] = false; } do { used[j0] = true; int i0 = p[j0], j1 = 0; long delta = long.MaxValue; - for (int j = 1; j <= n; j++) + for (int j = 1; j <= m; j++) { if (used[j]) continue; long cur = cost[i0 - 1, j - 1] - u[i0] - v[j]; if (cur < minv[j]) { minv[j] = cur; way[j] = j0; } if (minv[j] < delta) { delta = minv[j]; j1 = j; } } - for (int j = 0; j <= n; j++) + for (int j = 0; j <= m; j++) if (used[j]) { u[p[j]] += delta; v[j] -= delta; } else minv[j] -= delta; - j0 = j1; ops += n; + j0 = j1; ops += m; } while (p[j0] != 0); do { int j1 = way[j0]; p[j0] = p[j1]; j0 = j1; } while (j0 != 0); row++; @@ -112,4 +116,37 @@ public static List Split(int nodes, int[] from, int[] to) } return result; } + + // Splits moves that may end in empty beds into units that can each be applied on its own: chains (A leaves home X + // for Y, Y's B leaves for Z, ..., the last one takes an empty bed) and cycles. A chain leaves one more bed free where + // it starts and one fewer where it ends; every other home keeps its head count. Chains start in homes the moves take + // more adults from than they bring, and end in homes they bring more to. Returns edge-id lists in a deterministic order. + public static List SplitChains(int nodes, int[] from, int[] to) + { + // A virtual node closes every chain into a cycle: it feeds each home that loses more adults than it gains and + // drains each home that gains more than it loses. Split returns simple cycles, so each passes it at most once. + int edges = from.Length; var net = new int[nodes]; + for (int e = 0; e < edges; e++) { net[from[e]]--; net[to[e]]++; } + var f = new List(from); var t = new List(to); + for (int h = 0; h < nodes; h++) + { + for (int k = 0; k < -net[h]; k++) { f.Add(nodes); t.Add(h); } + for (int k = 0; k < net[h]; k++) { f.Add(h); t.Add(nodes); } + } + var result = new List(); + foreach (var cycle in Split(nodes + 1, f.ToArray(), t.ToArray())) + { + var real = new List(cycle.Length); + foreach (int e in cycle) if (e < edges) real.Add(e); + // A cycle through the virtual node is a chain; rotate it so the moves run from its start to its end. + int cut = Array.FindIndex(cycle, e => e >= edges && f[e] == nodes); + if (cut >= 0) + { + real.Clear(); + for (int k = 1; k < cycle.Length; k++) { int e = cycle[(cut + k) % cycle.Length]; if (e < edges) real.Add(e); } + } + if (real.Count > 0) result.Add(real.ToArray()); + } + return result; + } } diff --git a/OptimizedLocalHousing/GameAdapter.cs b/OptimizedLocalHousing/GameAdapter.cs index 15938c4..b058898 100644 --- a/OptimizedLocalHousing/GameAdapter.cs +++ b/OptimizedLocalHousing/GameAdapter.cs @@ -33,7 +33,7 @@ public sealed class HousingConfigurator : Configurator public sealed class ModStarter : IModStarter { - public void StartMod(IModEnvironment environment) => Debug.Log("[OptimizedLocalHousing] 1.1.1 loaded."); + public void StartMod(IModEnvironment environment) => Debug.Log("[OptimizedLocalHousing] 1.2.0 loaded."); } // Thin bridge between the game and PassEngine: it enumerates beavers, answers route queries, and applies moves. @@ -86,10 +86,24 @@ public Snapshot Capture() { var builder = new SnapshotBuilder(); foreach (var district in _districts.FinishedDistrictCenters) + { foreach (var beaver in district.DistrictPopulation.Beavers) AddAdult(builder, beaver); + // Every usable home in the district, so an adult can move into an empty bed. + var registry = district.GetComponent(); + if (registry) foreach (var home in registry.GetEnabledBuildingsInstant()) AddHome(builder, home, Id(district)); + } return builder.Build(); } + private static bool AddHome(SnapshotBuilder builder, Dwelling home, Guid districtId) + { + if (!UsableHome(home) || Id(home.GetComponent()?.District) != districtId) return false; + var block = home.GetComponent(); if (!block) return false; + var at = block.Coordinates; + builder.AddHome(Id(home), districtId, at.x, at.y, at.z, home.MaxBeavers, home.NumberOfAdultDwellers, home.NumberOfChildDwellers); + return true; + } + private void AddAdult(SnapshotBuilder builder, Beaver beaver) { var character = beaver.GetComponent(); var dweller = beaver.GetComponent(); @@ -97,10 +111,7 @@ private void AddAdult(SnapshotBuilder builder, Beaver beaver) var home = dweller.Home; var district = beaver.GetComponent()?.AssignedDistrict; if (!home || !district || !district.Enabled) return; var districtId = Id(district); - if (!UsableHome(home) || Id(home.GetComponent()?.District) != districtId) return; - var block = home.GetComponent(); if (!block) return; - var at = block.Coordinates; - builder.AddHome(Id(home), districtId, at.x, at.y, at.z); + if (!AddHome(builder, home, districtId)) return; builder.AddAdult(Id(beaver), Id(home), JobOf(beaver, districtId, builder), districtId); } @@ -148,11 +159,14 @@ public bool ApplyCycle(Move[] cycle) change[m.From] = (change.TryGetValue(m.From, out var out1) ? out1 : 0) - 1; change[m.To] = (change.TryGetValue(m.To, out var in1) ? in1 : 0) + 1; } - // Whole cycles leave every home's head count unchanged; this only guards against a newborn taking the bed meanwhile. + // A cycle leaves every home's head count unchanged, and a chain ends in a bed that was empty at the snapshot; this + // guards against a newborn or a homeless beaver taking that bed meanwhile, or an adult a child's bed (the game + // would move an adult out of a home with more adults than adult beds). foreach (var pair in change) { var home = Component(pair.Key); if (!home || home.NumberOfDwellers + pair.Value > home.MaxBeavers) return false; + if (pair.Value > 0 && home.NumberOfAdultDwellers + pair.Value > home.AdultSlots) return false; } try { diff --git a/OptimizedLocalHousing/OptimizedLocalHousing.csproj b/OptimizedLocalHousing/OptimizedLocalHousing.csproj index b3d2051..51f5263 100644 --- a/OptimizedLocalHousing/OptimizedLocalHousing.csproj +++ b/OptimizedLocalHousing/OptimizedLocalHousing.csproj @@ -2,7 +2,7 @@ netstandard2.1 latest - 1.1.1 + 1.2.0 C:\Program Files (x86)\Steam\steamapps\common\Timberborn\Timberborn_Data\Managed diff --git a/OptimizedLocalHousing/PassEngine.cs b/OptimizedLocalHousing/PassEngine.cs index c7b6581..ec57680 100644 --- a/OptimizedLocalHousing/PassEngine.cs +++ b/OptimizedLocalHousing/PassEngine.cs @@ -12,8 +12,9 @@ public interface IPassWorld Snapshot Capture(); // A fresh route query. False when the home cannot reach the workplace. bool TryRoute(Guid home, Guid work, out float cost); - // Re-validates the cycle against the live game and applies it as a unit. False, with nothing changed, - // if anyone in it has moved, changed job or died since the snapshot, or a home can no longer take them. + // Re-validates the moves (a cycle, or a chain whose last move takes an empty bed) against the live game and applies + // them as a unit. False, with nothing changed, if anyone in it has moved, changed job or died since the snapshot, + // or a home can no longer take them. bool ApplyCycle(Move[] cycle); } @@ -23,8 +24,12 @@ public sealed class Snapshot public Guid[] AdultDistrict = new Guid[0]; public int[] AdultHome = new int[0]; // index into Homes public int[] AdultWork = new int[0]; // index into Works, -1 when there is no usable job - public Guid[] Homes = new Guid[0]; // ascending by ID; only homes with an adult in them + public Guid[] Homes = new Guid[0]; // ascending by ID; homes with an adult in them or an empty bed public Guid[] HomeDistrict = new Guid[0]; + public int[] HomeFree = new int[0]; // empty beds per home that an adult may take (HomeRules.FreeForAdults) + public int[] HomeBeds = new int[0]; // beds per home, and the adults and children living in it, all from the game + public int[] HomeAdults = new int[0]; + public int[] HomeChildren = new int[0]; public int[] HomePos = new int[0]; // x, y, z per home public Guid[] Works = new Guid[0]; // ascending by ID public int[] WorkPos = new int[0]; @@ -41,9 +46,13 @@ public sealed class SnapshotBuilder { private readonly List<(Guid Id, Guid Home, Guid Work, Guid District)> _adults = new List<(Guid, Guid, Guid, Guid)>(); private readonly HashSet _seen = new HashSet(); - private readonly Dictionary _homes = new Dictionary(); + private readonly Dictionary _homes = + new Dictionary(); private readonly Dictionary _works = new Dictionary(); - public void AddHome(Guid id, Guid district, int x, int y, int z) => _homes[id] = (district, x, y, z); + // beds, adults, children: the home's beds and who lives in it, as the game counts them. A home is kept when an adult + // lives in it, or it has a bed an adult may take in a district with adults. + public void AddHome(Guid id, Guid district, int x, int y, int z, int beds = 0, int adults = 0, int children = 0) => + _homes[id] = (district, x, y, z, beds, adults, children); public void AddWork(Guid id, int x, int y, int z) => _works[id] = (x, y, z); public void AddAdult(Guid id, Guid home, Guid work, Guid district) { if (_seen.Add(id)) _adults.Add((id, home, work, district)); } public Snapshot Build() @@ -53,14 +62,19 @@ public Snapshot Build() if (_homes.TryGetValue(a.Home, out var home) && home.District == a.District) adults.Add(a); adults.Sort((x, y) => x.Id.CompareTo(y.Id)); var homeIds = new SortedSet(); var workIds = new SortedSet(); - foreach (var a in adults) { homeIds.Add(a.Home); if (a.Work != Guid.Empty && _works.ContainsKey(a.Work)) workIds.Add(a.Work); } + var districts = new HashSet(); // looked up only, never enumerated + foreach (var a in adults) { homeIds.Add(a.Home); districts.Add(a.District); if (a.Work != Guid.Empty && _works.ContainsKey(a.Work)) workIds.Add(a.Work); } + foreach (var h in _homes) + if (HomeRules.FreeForAdults(h.Value.Beds, h.Value.Adults, h.Value.Children) > 0 && districts.Contains(h.Value.District)) homeIds.Add(h.Key); var s = new Snapshot { Homes = new Guid[homeIds.Count], Works = new Guid[workIds.Count] }; var homeIndex = new Dictionary(); var workIndex = new Dictionary(); - s.HomeDistrict = new Guid[s.Homes.Length]; s.HomePos = new int[s.Homes.Length * 3]; + s.HomeDistrict = new Guid[s.Homes.Length]; s.HomePos = new int[s.Homes.Length * 3]; s.HomeFree = new int[s.Homes.Length]; + s.HomeBeds = new int[s.Homes.Length]; s.HomeAdults = new int[s.Homes.Length]; s.HomeChildren = new int[s.Homes.Length]; int n = 0; foreach (var id in homeIds) { - var h = _homes[id]; s.Homes[n] = id; s.HomeDistrict[n] = h.District; + var h = _homes[id]; s.Homes[n] = id; s.HomeDistrict[n] = h.District; s.HomeFree[n] = HomeRules.FreeForAdults(h.Beds, h.Adults, h.Children); + s.HomeBeds[n] = h.Beds; s.HomeAdults[n] = h.Adults; s.HomeChildren[n] = h.Children; s.HomePos[n * 3] = h.X; s.HomePos[n * 3 + 1] = h.Y; s.HomePos[n * 3 + 2] = h.Z; homeIndex[id] = n++; } s.WorkPos = new int[s.Works.Length * 3]; n = 0; @@ -80,12 +94,29 @@ public Snapshot Build() } } +// How the game fills a home (Timberborn.DwellingSystem.Dwelling) and when a home can have a kit (the Folktails' +// Timberborn.Reproduction.ProcreationHouse). A third of a home's beds, rounded down, are for children, the rest for adults. +public static class HomeRules +{ + public static int ChildSlots(int beds) => beds / 3; + public static int AdultSlots(int beds) => beds - ChildSlots(beds); + // Empty beds an adult can move into and keep. The game moves adults out of a home with more adults than adult beds, + // so an adult never takes a child's bed. + public static int FreeForAdults(int beds, int adults, int children) => + Math.Max(0, Math.Min(beds - adults - children, AdultSlots(beds) - adults)); + // A home can have a kit when two of its adults can meet there, a bed is free, and it has fewer children than its + // child beds and than half its adults (rounded down). + public static bool CanBreed(int beds, int adults, int children) => + adults >= 2 && adults + children < beds && children < ChildSlots(beds) && children < adults / 2; +} + public sealed class PassState { - public const int CurrentVersion = 5; // 2: Near rows hold only the workplace's district, padded with -1 + public const int CurrentVersion = 6; // 2: Near rows hold only the workplace's district, padded with -1 // 3: route costs verified outside the Near rows are kept (Learned*) // 4: each district is solved on its own (District, Beds) // 5: per-tick budgets are set for each pass (QueryBudget, SolveBudget) + // 6: empty beds are solved for too (Snapshot.HomeFree; Beds holds homes) public int Version = CurrentVersion; public bool Requested = true; // start a pass at the next opportunity public int Stage; // 0 idle, 1 route costs, 2 assignment, 3 verification @@ -96,7 +127,7 @@ public sealed class PassState public int District; // stage 2: the district being solved, counted in ID order public int Row = 1; // stage 2: next row of that district's assignment public long[] U, V; public int[] P; // stage 2 solver state of that district - public int[] Beds; // stages 2-3: per adult, the adult whose bed it gets (itself until solved) + public int[] Beds; // stages 2-3: per adult, the home it gets (its own until solved) public int[] VerifyCurrent, VerifyTarget; // stage 3: fresh route costs per move public long Queries, Ticks; // of the running pass public long Passes, MovedAdults, AppliedCycles, RejectedCycles, StaleCycles; // lifetime @@ -114,9 +145,9 @@ public sealed class PassReport } // One pass = capture the colony, price each workplace's nearest homes in its district, solve each district's optimal -// assignment, re-check every proposed move against fresh routes, then apply whole cycles of moves. The re-checked costs -// of homes beyond the nearest are kept for the next passes, in place of estimates, and priced again when they come due -// while still needed. Each stage is spread over ticks with operation budgets set from the snapshot when the pass starts, +// assignment to its occupied and empty beds, re-check every proposed move against fresh routes, then apply whole cycles +// and chains of moves. The re-checked costs of homes beyond the nearest are kept for the next passes, in place of +// estimates, and priced again when they come due while still needed. Each stage is spread over ticks with operation budgets set from the snapshot when the pass starts, // and the entire state is serializable, so a pass resumes identically after a save/load and on every multiplayer peer. public sealed class PassEngine { @@ -157,9 +188,9 @@ private static PassState Restart(PassState old) Passes = old.Passes, MovedAdults = old.MovedAdults, AppliedCycles = old.AppliedCycles, RejectedCycles = old.RejectedCycles, StaleCycles = old.StaleCycles, }; - // Versions 3 and 4 kept the remembered costs just as this one does (only the solve stage and the budgets changed - // since), so they carry over and a cycle a route check turned down stays known. A pass changes them only when it - // finishes. + // Versions 3 to 5 kept the remembered costs just as this one does (only the solve stage, the budgets and the + // snapshot's empty beds changed since), so they carry over and a cycle a route check turned down stays known. A + // pass changes them only when it finishes. int count = old.LearnedWork?.Length ?? -1; if (old.Version >= 3 && old.Version <= PassState.CurrentVersion && count >= 0 && old.LearnedHome?.Length == count && old.LearnedCost?.Length == count && old.LearnedAge?.Length == count) { @@ -191,14 +222,14 @@ private void TickCore() default: throw new InvalidOperationException("Unknown pass stage " + State.Stage); } } - private void Forget() { _matrix = null; _built = 0; _members = null; _moves = null; _known = null; _far = null; } + private void Forget() { _matrix = null; _built = 0; _members = null; _columns = null; _moves = null; _known = null; _far = null; } private void Begin() { Forget(); State.Requested = false; State.Queries = 0; State.Ticks = 0; var snap = _world.Capture(); - if (snap.Adults.Length < 2 || snap.Works.Length == 0) { Finish(snap, new List(), null, null); return; } + if (snap.Adults.Length == 0 || snap.Works.Length == 0) { Finish(snap, new List(), null, null); return; } // The game's road routes never leave a district, so a workplace only ranks homes in its own district: the one // its workers live in (a job in another district does not count), taken from the lowest-ID worker. var workDistrict = new Guid[snap.Works.Length]; var seen = new bool[snap.Works.Length]; @@ -229,9 +260,9 @@ private void Begin() // The pass's budgets per tick, set from its snapshot alone and saved with it, so every peer, reloaded or not, does the // same work on every tick. Pricing asks one route per real candidate and per recheck; the route checks ask two per - // move, and at most every adult moves. Solving a district of n adults took about n^3 / 9 operations on the first pass - // over a randomly housed test colony (never more than about n^3 / 2), and far fewer once a colony is settled; n^3 / 8 - // is taken. + // move, and at most every adult moves. Solving a district of n adults and n beds took about n^3 / 9 operations on the + // first pass over a randomly housed test colony (never more than about n^3 / 2), and far fewer once a colony is + // settled; with m beds, occupied and empty, n^2 m / 8 is taken. private void Budget(Snapshot s) { long queries = s.RecheckCosts.Length; @@ -239,7 +270,7 @@ private void Budget(Snapshot s) long perTick = Math.Max((queries + PriceTicks - 1) / PriceTicks, (2L * s.Adults.Length + VerifyTicks - 1) / VerifyTicks); State.QueryBudget = (int)Math.Min(Math.Max(perTick, QueriesPerTick), MaxQueriesPerTick); long ops = 0; - foreach (var members in Districts()) { long n = members.Length; ops += n * n * n / 8; } + for (int d = 0; d < Districts().Length; d++) { long n = Districts()[d].Length, m = Columns(d).Length; ops += n * n * m / 8; } State.SolveBudget = Math.Min(Math.Max((ops + SolveTicks - 1) / SolveTicks, SolveOpsPerTick), MaxSolveOpsPerTick); } @@ -285,15 +316,34 @@ private void PriceStep() State.Queries++; q++; } if (State.Cursor < end) return; - State.Beds = new int[s.Adults.Length]; - for (int i = 0; i < State.Beds.Length; i++) State.Beds[i] = i; + State.Beds = (int[])s.AdultHome.Clone(); State.District = 0; StartDistrict(); State.Stage = 2; } // Nobody crosses districts, so the colony's assignment is one per district: each is solved on its own, in ID order, - // over its own adults and the beds they live in. The optimum is the same as for the whole colony at once, which - // scanned every district's beds for every adult; this takes fewer ticks and a far smaller matrix. + // over its own adults, the beds they live in and its empty beds. The optimum is the same as for the whole colony at + // once, which scanned every district's beds for every adult; this takes fewer ticks and a far smaller matrix. private int[] Members(int district) => Districts()[district]; + // A district's beds, as the home each column of its matrix stands for: first the beds its adults live in, in the + // adults' order, then its homes' empty beds in home order (at most one per adult in each home: no more can be used). + private int[][] _columns; + private int[] Columns(int district) + { + if (_columns == null) + { + var s = State.Snap; var all = Districts(); _columns = new int[all.Length][]; + var districts = new List(new SortedSet(s.AdultDistrict)); + for (int d = 0; d < all.Length; d++) + { + var columns = new List(); + foreach (int i in all[d]) columns.Add(s.AdultHome[i]); + for (int h = 0; h < s.Homes.Length; h++) + if (s.HomeDistrict[h] == districts[d]) for (int b = Math.Min(s.HomeFree[h], all[d].Length); b > 0; b--) columns.Add(h); + _columns[d] = columns.ToArray(); + } + } + return _columns[district]; + } private int[][] Districts() { if (_members == null) @@ -309,8 +359,8 @@ private int[][] Districts() } private void StartDistrict() { - int n = Members(State.District).Length; - State.U = new long[n + 1]; State.V = new long[n + 1]; State.P = new int[n + 1]; State.Row = 1; + int n = Members(State.District).Length, m = Columns(State.District).Length; + State.U = new long[n + 1]; State.V = new long[m + 1]; State.P = new int[m + 1]; State.Row = 1; } // Operations the latest solve tick charged, summed apart from the budget check. Only the tests read it; never saved. @@ -321,17 +371,17 @@ private void SolveStep() long ops = 0; SolveOps = 0; while (true) { - var members = Members(State.District); int n = members.Length; - if (_matrix == null) { _matrix = new long[n, n]; _built = 0; } + var members = Members(State.District); var columns = Columns(State.District); int n = members.Length, m = columns.Length; + if (_matrix == null) { _matrix = new long[n, m]; _built = 0; } // After a load the district's rows solved so far are rebuilt first; they are needed by the rows still to // come. That work is not charged to this tick's budget: how many rows a tick solves must depend on the saved // state alone, so a peer that loaded a save taken mid-pass keeps step, tick for tick, with a peer that did not. - while (_built < State.Row - 1) BuildRow(members, _built++); + while (_built < State.Row - 1) BuildRow(members, columns, _built++); long before = ops; - bool solved = Hungarian.Step(_matrix, n, State.U, State.V, State.P, ref State.Row, ref ops, State.SolveBudget, row => { BuildRow(members, row); _built = row + 1; return n; }); + bool solved = Hungarian.Step(_matrix, n, m, State.U, State.V, State.P, ref State.Row, ref ops, State.SolveBudget, row => { BuildRow(members, columns, row); _built = row + 1; return m; }); SolveOps += ops - before; if (!solved) return; - for (int j = 1; j <= n; j++) State.Beds[members[State.P[j] - 1]] = members[j - 1]; + for (int j = 1; j <= m; j++) if (State.P[j] > 0) State.Beds[members[State.P[j] - 1]] = columns[j - 1]; _matrix = null; if (++State.District == _members.Length) break; StartDistrict(); @@ -343,11 +393,11 @@ private void SolveStep() State.Cursor = 0; State.Stage = 3; } - // A row of the district's cost matrix: what each of the district's existing beds would cost that row's adult. + // A row of the district's cost matrix: what each of the district's beds, occupied or empty, would cost that row's adult. private Dictionary[] _known; private long[] _far; - private void BuildRow(int[] members, int row) + private void BuildRow(int[] members, int[] columns, int row) { - var s = State.Snap; int n = members.Length, k = s.NearK, i = members[row]; + var s = State.Snap; int m = columns.Length, k = s.NearK, i = members[row]; if (_known == null) { _known = new Dictionary[s.Works.Length]; _far = new long[s.Works.Length]; @@ -375,9 +425,9 @@ private void BuildRow(int[] members, int row) } } int own = s.AdultHome[i], work = s.AdultWork[i]; - for (int j = 0; j < n; j++) + for (int j = 0; j < m; j++) { - int bed = s.AdultHome[members[j]]; // the bed the district's adult j lives in today; beds in one home are alike + int bed = columns[j]; // beds in one home are alike long c = 0; if (work >= 0) c = _known[work].TryGetValue(bed, out var known) ? known @@ -395,7 +445,7 @@ private void EnsureMoves() _moves = new List(); for (int i = 0; i < n; i++) { - int to = s.AdultHome[State.Beds[i]]; + int to = State.Beds[i]; if (to != s.AdultHome[i]) _moves.Add(new[] { i, s.AdultHome[i], to }); } } @@ -414,7 +464,7 @@ private void VerifyStep() if (State.Cursor < _moves.Count) return; var edgesFrom = new int[_moves.Count]; var edgesTo = new int[_moves.Count]; for (int e = 0; e < _moves.Count; e++) { edgesFrom[e] = _moves[e][1]; edgesTo[e] = _moves[e][2]; } - Finish(s, Cycles.Split(s.Homes.Length, edgesFrom, edgesTo), State.VerifyCurrent, State.VerifyTarget); + Finish(s, Cycles.SplitChains(s.Homes.Length, edgesFrom, edgesTo), State.VerifyCurrent, State.VerifyTarget); } private int Price(Guid home, Guid work) { State.Queries++; return _world.TryRoute(home, work, out var route) ? Cost.Fixed(route) : Cost.Unreachable; } @@ -435,8 +485,15 @@ private void Finish(Snapshot s, List cycles, int[] current, int[] target) if (ok && gain >= Cost.MinimumGain) accepted.Add((cycle, gain)); else report.Rejected++; } accepted.Sort((x, y) => x.Gain != y.Gain ? y.Gain.CompareTo(x.Gain) : x.Edges[0].CompareTo(y.Edges[0])); + // Adults per home as the applied moves leave them, for the breeding rule below. + var adults = (int[])s.HomeAdults.Clone(); foreach (var (edges, gain) in accepted) { + // A chain moves one adult out of its first home and one into an empty bed of its last. It is turned down if + // it would leave the colony fewer homes that can breed (HomeRules.CanBreed); a cycle changes neither. + int start = _moves[edges[0]][1], end = _moves[edges[edges.Length - 1]][2]; bool chain = start != end; + if (chain && Breeding(s, start, adults[start] - 1) + Breeding(s, end, adults[end] + 1) + < Breeding(s, start, adults[start]) + Breeding(s, end, adults[end])) { report.Rejected++; continue; } var moves = new Move[edges.Length]; for (int i = 0; i < edges.Length; i++) { @@ -446,6 +503,7 @@ private void Finish(Snapshot s, List cycles, int[] current, int[] target) if (_world.ApplyCycle(moves)) { report.Applied++; + if (chain) { adults[start]--; adults[end]++; } foreach (int e in edges) { // Repaired only if the new home reaches work: a cut-off beaver can be moved along and stay cut off. @@ -463,6 +521,8 @@ private void Finish(Snapshot s, List cycles, int[] current, int[] target) LastReport = report; Reported?.Invoke(report); } + private static int Breeding(Snapshot s, int home, int adults) => HomeRules.CanBreed(s.HomeBeds[home], adults, s.HomeChildren[home]) ? 1 : 0; + // Keeps this pass's fresh route costs for homes outside the workplace's Near row, which the next pass would only // estimate again: without them a move the check turned down comes back every day. A newer cost replaces an older one // for the same pair (a move's check wins over a recheck); the rest age by a pass and go after LearnedPasses, or once diff --git a/OptimizedLocalHousing/manifest.json b/OptimizedLocalHousing/manifest.json index 109e24d..5701687 100644 --- a/OptimizedLocalHousing/manifest.json +++ b/OptimizedLocalHousing/manifest.json @@ -1,8 +1,8 @@ { "Name": "Optimized Local Housing", - "Version": "1.1.1", + "Version": "1.2.0", "Id": "Kyler.OptimizedLocalHousing", "MinimumGameVersion": "1.1.0.0", - "Description": "Once a day, re-houses adult beavers so total home-to-workplace travel is as short as possible, using an optimal assignment. Every home keeps its number of adults, children never move. Standalone; install the same version on every multiplayer peer.", + "Description": "Once a day, re-houses adult beavers so total home-to-workplace travel is as short as possible, using an optimal assignment. Adults can move into empty beds near work, but never in a way that leaves fewer homes able to breed; children never move. Standalone; install the same version on every multiplayer peer.", "RequiredMods": [] } diff --git a/README.md b/README.md index e1c57b2..af61cbe 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,10 @@ Build steps, how a pass works inside, costs, saved data and the test list are in ## Changelog +- **1.2.0**: adults can move into empty beds. A beaver whose workplace has an empty home beside it moves there + when that shortens the colony's total walk, so a home's number of adults can now change. A move is turned down if + it would leave fewer homes that can breed. Adults only take adult beds, so child beds stay free. Children still never move, and nobody moves into a paused, blocked or automation-off home. A pass that was running when an older save + was made starts over once after the update. All co-op players must update together. - **1.1.1**: maintenance release. The conflict check now covers only Housing Optimize and Commute Balancer. How passes work, and what is saved, are unchanged from 1.1.0. As always, every co-op player installs the same version.