From bc8a0b0189e43785402eb1e91f0879b12dd51faf Mon Sep 17 00:00:00 2001 From: Soar Qin Date: Wed, 21 Oct 2026 01:14:36 +0800 Subject: [PATCH] perf(uxassist): speed up miner search and honor native clearances Cache which seeds block each candidate for the replacement, repacking and refill passes, skip candidates that can no longer join a greedy pass, test repack option pairs only when reached, and reuse nearby nodes and obstacles across rotations at each candidate position. Recorded snapshots replay to identical layouts in sequential and parallel modes. Exclude positions the game refuses near the landing capsule and EM Rail Ejectors, and keep buried nodes near Dark Fog Planetary Bases buried, as native reform does. Remove the unused placement limit, duplicate ground checks and per-miner GPU buffer syncs; debug snapshots move to schema 3 with clearance rejections. --- UXAssist/Common/I18NKeys.cs | 2 +- .../Functions/Factory/MinerPlacementDebug.cs | 6 +- .../Factory/MinerPlacementGeometry.cs | 6 +- .../Functions/Factory/MinerPlacementSolver.cs | 476 ++++++++++-------- UXAssist/Functions/Factory/QuickMinerBuild.cs | 321 +++++++----- UXAssist/README.md | 8 +- tools/tests/QuickMinerPlacementTests.cs | 77 ++- 7 files changed, 499 insertions(+), 397 deletions(-) diff --git a/UXAssist/Common/I18NKeys.cs b/UXAssist/Common/I18NKeys.cs index 20edfd4..605dc33 100644 --- a/UXAssist/Common/I18NKeys.cs +++ b/UXAssist/Common/I18NKeys.cs @@ -449,7 +449,7 @@ You can set 2 shortcut keys in Settings panel: I18N.Add(DismantleAllBuildingsConfirm, "This operation will dismantle all buildings on this planet, are you sure?", "此操作将会拆除本行星上的所有建筑,确定吗?"); I18N.Add(QuickBuildOrbitalCollectors, "Quick build Orbital Collectors", "快速建造轨道采集器"); I18N.Add(QuickBuildMiningMachines, "Quick build Mining Machines", "快速铺设采矿机"); - I18N.Add(QuickBuildMiningMachinesTips, "Places ordinary Mining Machine prebuilds at the nearest solid vein group. Restores buried nodes when buildings do not obstruct them. Searches native collision shapes and maximizes the sum of each miner's vein count, counting shared nodes repeatedly. Every placed miner must retain at least 3 covered nodes after all planned burials. May bury unused nodes to improve the total. Places the full layout regardless of carried stock; missing miners remain as ghosts awaiting materials. Respects ground and construction range; does not lay belts or power poles. Click again to cancel the search.", "在最近的固体矿脉生成普通采矿机待建造对象。先还原未被建筑阻挡的掩埋矿点,按游戏实际碰撞体搜索布局,以各台矿机覆盖矿点数之和为目标,同一矿点被多台矿机覆盖时重复计数。所有计划掩埋完成后,每台矿机仍须覆盖至少 3 个矿点。允许掩埋未被现有矿机使用的矿点,以提高总覆盖数。布局数量不受库存限制,采矿机不足的位置保留待建造虚影,等待补充材料。遵守地面和建造范围要求,不铺设传送带和电力设施。计算期间再次点击可取消。"); + I18N.Add(QuickBuildMiningMachinesTips, "Places ordinary Mining Machine prebuilds at the nearest solid vein group. Restores buried nodes when no building obstructs them and no Dark Fog Planetary Base is nearby. Searches native collision shapes and maximizes the sum of each miner's vein count, counting shared nodes repeatedly. Every placed miner must retain at least 3 covered nodes after all planned burials. May bury unused nodes to improve the total. Places the full layout regardless of carried stock; missing miners remain as ghosts awaiting materials. Respects ground and construction range; does not lay belts or power poles. Click again to cancel the search.", "在最近的固体矿脉生成普通采矿机待建造对象。先还原未被建筑阻挡且不在黑雾行星基地附近的掩埋矿点,按游戏实际碰撞体搜索布局,以各台矿机覆盖矿点数之和为目标,同一矿点被多台矿机覆盖时重复计数。所有计划掩埋完成后,每台矿机仍须覆盖至少 3 个矿点。允许掩埋未被现有矿机使用的矿点,以提高总覆盖数。布局数量不受库存限制,采矿机不足的位置保留待建造虚影,等待补充材料。遵守地面和建造范围要求,不铺设传送带和电力设施。计算期间再次点击可取消。"); I18N.Add(QuickMinerCancelSearch, "Cancel miner layout search", "取消采矿机布局计算"); I18N.Add(QuickMinerSearching, "Searching for a dense miner layout... Click the button again to cancel.", "正在计算密集采矿机布局,再次点击按钮可取消。"); I18N.Add(QuickMinerCancelled, "Miner layout search cancelled", "已取消采矿机布局计算"); diff --git a/UXAssist/Functions/Factory/MinerPlacementDebug.cs b/UXAssist/Functions/Factory/MinerPlacementDebug.cs index cf3e188..a7f2110 100644 --- a/UXAssist/Functions/Factory/MinerPlacementDebug.cs +++ b/UXAssist/Functions/Factory/MinerPlacementDebug.cs @@ -14,7 +14,7 @@ internal static class MinerPlacementDebug [Serializable] internal sealed class Snapshot { - public int schema = 2; + public int schema = 3; public string algorithm = "parallel-repack-v5-pose-exploration-min3-unlimited-stock"; public int minimumCoverage = MinerPlacementSolver.MinimumCoverage; public string version, gameVersion, startedUtc, outcome, error; @@ -105,8 +105,6 @@ internal static class MinerPlacementDebug { public string name; public int candidateCount, passes, score; - // Unlimited-stock snapshots may omit the legacy placement cap. - public int limit = int.MaxValue; public long elapsedMilliseconds, searchMilliseconds; public int[] selected; } @@ -122,7 +120,7 @@ internal static class MinerPlacementDebug [Serializable] internal sealed class Rejections { - public int attempted, range, mixedType, noCoverage, veinCollision, buildingCollision, ground; + public int attempted, range, clearance, mixedType, noCoverage, veinCollision, buildingCollision, ground; } public static float[] Vector(Vector3 value) => [value.x, value.y, value.z]; diff --git a/UXAssist/Functions/Factory/MinerPlacementGeometry.cs b/UXAssist/Functions/Factory/MinerPlacementGeometry.cs index 04e2b3b..1fbbe82 100644 --- a/UXAssist/Functions/Factory/MinerPlacementGeometry.cs +++ b/UXAssist/Functions/Factory/MinerPlacementGeometry.cs @@ -29,7 +29,7 @@ internal static class MinerPlacementGeometry } } - public static bool Intersects(Box a, Box b) + public static bool Intersects(in Box a, in Box b) { var delta = b.Center - a.Center; // Reject distant individual colliders before the full separating-axis test. This @@ -50,7 +50,7 @@ internal static class MinerPlacementGeometry !Separated(Vector3.Cross(a.Z, b.Z), delta, a, b); } - private static bool Separated(Vector3 axis, Vector3 delta, Box a, Box b) + private static bool Separated(Vector3 axis, Vector3 delta, in Box a, in Box b) { if (axis.sqrMagnitude < 1e-10f) return false; var radius = a.Extents.x * Mathf.Abs(Vector3.Dot(axis, a.X)) + @@ -62,7 +62,7 @@ internal static class MinerPlacementGeometry return Mathf.Abs(Vector3.Dot(delta, axis)) > radius; } - public static bool Intersects(Box box, ColliderData collider) + public static bool Intersects(in Box box, ColliderData collider) { switch (collider.shape) { diff --git a/UXAssist/Functions/Factory/MinerPlacementSolver.cs b/UXAssist/Functions/Factory/MinerPlacementSolver.cs index f3cd981..ef2e5da 100644 --- a/UXAssist/Functions/Factory/MinerPlacementSolver.cs +++ b/UXAssist/Functions/Factory/MinerPlacementSolver.cs @@ -10,6 +10,8 @@ namespace UXAssist.Functions.Factory; internal sealed class MinerPlacementSolver { internal const int MinimumCoverage = 3; + // Coordinated repacking replaces at most this many nearby miners at once. + private const int RegionSize = 3; public static int WorkerCount => GetWorkerCount(Environment.ProcessorCount); internal static int GetWorkerCount(int processors) => Math.Min(4, Math.Max(0, processors / 2)); @@ -35,25 +37,23 @@ internal sealed class MinerPlacementSolver _nodeCount = nodeCount; } - public IEnumerator Search(int passes) => Search(int.MaxValue, passes); + public IEnumerator Search(int passes) => Search(passes, 0, CancellationToken.None); - public IEnumerator Search(int limit, int passes) => Search(limit, passes, 0, CancellationToken.None); - - public Task SearchAsync(int limit, int passes, CancellationToken cancellationToken, int workers = 4) + public Task SearchAsync(int passes, CancellationToken cancellationToken, int workers = 4) { workers = Math.Min(workers, WorkerCount); if (workers <= 0) throw new InvalidOperationException("Use the main-thread search when no worker is available."); // The caller must not mutate candidates until this task has completed. Workers only // read captured geometry; no Unity physics, game objects, or factory state is accessed. - return Task.Run(() => Drain(Search(limit, passes, workers, cancellationToken), cancellationToken), cancellationToken); + return Task.Run(() => Drain(Search(passes, workers, cancellationToken), cancellationToken), cancellationToken); } - private IEnumerator Search(int limit, int passes, int workers, CancellationToken cancellationToken) + private IEnumerator Search(int passes, int workers, CancellationToken cancellationToken) { // Keep a burial-free baseline, explore different packing orders, then try individual // replacements before the more expensive coordinated neighborhood search. var results = new SearchResult[passes]; - var work = RunBatch(passes, pass => GreedyPass(limit, pass, null, results, pass, cancellationToken), workers, cancellationToken); + var work = RunBatch(passes, pass => GreedyPass(pass, null, null, -1, results, pass, cancellationToken), workers, cancellationToken); while (work.MoveNext()) yield return null; foreach (var result in results) Accept(result); // Candidate indices shift when a few poses become invalid. Duplicated poses also @@ -65,24 +65,33 @@ internal sealed class MinerPlacementSolver if ((i & 127) == 0) { cancellationToken.ThrowIfCancellationRequested(); yield return null; } keys[i] = PoseKey(_candidates[i]); } - var additional = new SearchResult[Math.Max(0, passes - 2)]; - work = RunBatch(additional.Length, - index => GreedyPass(limit, index + 2, null, additional, index, cancellationToken, keys), workers, cancellationToken); - while (work.MoveNext()) yield return null; - foreach (var result in additional) Accept(result); - var seeds = new List(Best); - results = new SearchResult[seeds.Count]; - work = RunBatch(seeds.Count, index => GreedyPass(limit, passes + index, seeds, results, index, cancellationToken), workers, cancellationToken); + results = new SearchResult[Math.Max(0, passes - 2)]; + work = RunBatch(results.Length, index => GreedyPass(index + 2, keys, null, -1, results, index, cancellationToken), workers, cancellationToken); while (work.MoveNext()) yield return null; foreach (var result in results) Accept(result); - var repair = Repack(limit, workers, cancellationToken); - while (repair.MoveNext()) yield return null; + var seeds = new SeedCollisions(_candidates.Count); + work = TrackBest(seeds, workers, cancellationToken); + while (work.MoveNext()) yield return null; + results = new SearchResult[seeds.Seeds.Count]; + work = RunBatch(results.Length, index => GreedyPass(0, null, seeds, index, results, index, cancellationToken), workers, cancellationToken); + while (work.MoveNext()) yield return null; + foreach (var result in results) Accept(result); + for (var round = 0; round < 2 && Best.Count > 0; round++) + { + work = TrackBest(seeds, workers, cancellationToken); + while (work.MoveNext()) yield return null; + work = Repack(seeds, workers, cancellationToken); + while (work.MoveNext()) yield return null; + if (ReferenceEquals(seeds.Seeds, Best)) break; + } // A local replacement can open space beyond its neighborhood. Saturate the full // candidate set once more, preserving every selected miner's minimum coverage. - var refill = new SearchResult[1]; - work = GreedyPass(limit, 0, new List(Best), refill, 0, cancellationToken, keepAllSeeds: true); + work = TrackBest(seeds, workers, cancellationToken); while (work.MoveNext()) yield return null; - Accept(refill[0]); + results = new SearchResult[1]; + work = GreedyPass(0, null, seeds, -1, results, 0, cancellationToken); + while (work.MoveNext()) yield return null; + Accept(results[0]); } private static uint PoseKey(Candidate candidate) @@ -94,17 +103,30 @@ internal sealed class MinerPlacementSolver return unchecked((uint)(x * 73856093 ^ z * 19349663 ^ yaw * 83492791)); } - private IEnumerator GreedyPass(int limit, int pass, List seeds, SearchResult[] results, int resultIndex, - CancellationToken cancellationToken, uint[] keys = null, bool keepAllSeeds = false) + // Without seeds, fill an empty layout in the exploration order of pass, keyed by candidate + // index or by keys. With seeds, keep every seed except removed (all when negative) and + // refill greedily. + private IEnumerator GreedyPass(int pass, uint[] keys, SeedCollisions seeds, int removed, SearchResult[] results, int resultIndex, + CancellationToken cancellationToken) { - var selected = new List(); - var buried = new bool[_nodeCount]; - var uses = new int[_nodeCount]; - var score = 0; + var layout = new Layout(_nodeCount); + // Selected miners already proven compatible with each candidate, or -1 once it cannot + // join. Layouts and burials only grow during a pass, so every exclusion is permanent. + var verified = new int[_candidates.Count]; if (seeds != null) - for (var i = 0; i < seeds.Count && selected.Count < limit; i++) - if (keepAllSeeds || i != resultIndex) Add(seeds[i], selected, buried, uses, ref score); - while (selected.Count < limit) + { + for (var i = 0; i < seeds.Seeds.Count; i++) + if (i != removed) layout.Add(seeds.Seeds[i]); + for (var i = 0; i < verified.Length; i++) + verified[i] = (removed >= 0 && ReferenceEquals(_candidates[i], seeds.Seeds[removed])) || !seeds.AllowsWithout(i, removed) + ? -1 : layout.Selected.Count; + } + else if (pass == 0) + { + for (var i = 0; i < verified.Length; i++) + if (_candidates[i].Buried.Length != 0) verified[i] = -1; + } + while (true) { Candidate chosen = null; var priority = float.NegativeInfinity; @@ -115,31 +137,43 @@ internal sealed class MinerPlacementSolver cancellationToken.ThrowIfCancellationRequested(); yield return null; } + if (verified[i] < 0) continue; var candidate = _candidates[i]; - if (seeds != null && !keepAllSeeds && ReferenceEquals(candidate, seeds[resultIndex])) continue; - if (seeds == null && pass == 0 && candidate.Buried.Length != 0) continue; - var gain = Gain(candidate, buried, uses, out var coverage); - if (coverage < MinimumCoverage || gain <= 0) continue; - // Deterministic exploration without depending on the game's random stream. - var hash = (keys == null ? unchecked((uint)((i + 1) * 73856093)) : keys[i]) ^ - unchecked((uint)((pass + 1) * 19349663 ^ (selected.Count + 1) * 83492791)); - hash ^= hash >> 16; - hash = unchecked(hash * 0x7feb352dU); - hash ^= hash >> 15; - hash = unchecked(hash * 0x846ca68bU); - hash ^= hash >> 16; - var jitter = pass is 0 or 1 || seeds != null ? 1f : 0.65f + (hash & 65535) / 65535f * 0.7f; - var value = gain * jitter - candidate.Buried.Length * 0.0001f; - if (value > priority && Fits(candidate, selected) && PreservesCoverage(candidate, selected, buried)) + var gain = layout.Gain(candidate, out var coverage); + if (coverage < MinimumCoverage) { - chosen = candidate; - priority = value; + verified[i] = -1; + continue; } + if (gain <= 0) continue; + var jitter = 1f; + if (seeds == null && pass > 1) + { + // Deterministic exploration without depending on the game's random stream. + var hash = (keys?[i] ?? unchecked((uint)((i + 1) * 73856093))) ^ + unchecked((uint)((pass + 1) * 19349663 ^ (layout.Selected.Count + 1) * 83492791)); + hash ^= hash >> 16; + hash = unchecked(hash * 0x7feb352dU); + hash ^= hash >> 15; + hash = unchecked(hash * 0x846ca68bU); + hash ^= hash >> 16; + jitter = 0.65f + (hash & 65535) / 65535f * 0.7f; + } + var value = gain * jitter - candidate.Buried.Length * 0.0001f; + if (value <= priority) continue; + if (!layout.FitsFrom(candidate, verified[i]) || !layout.PreservesCoverage(candidate)) + { + verified[i] = -1; + continue; + } + verified[i] = layout.Selected.Count; + chosen = candidate; + priority = value; } if (chosen == null) break; - Add(chosen, selected, buried, uses, ref score); + layout.Add(chosen); } - results[resultIndex] = new SearchResult(selected, score, CountBuried(selected)); + results[resultIndex] = new SearchResult(layout.Selected, layout.Score, layout.BuriedCount); } private static void Drain(IEnumerator work, CancellationToken cancellationToken) @@ -169,6 +203,8 @@ internal sealed class MinerPlacementSolver public int Score = score, BuriedCount = buriedCount; } + // Accept replaces Best with a new list only for a strictly better layout, so an unchanged + // reference means no improvement. private void Accept(SearchResult result) { if (!IsBetter(result.Score, result.BuriedCount, result.Selected.Count, BestScore, _bestBuriedCount, Best.Count)) return; @@ -183,98 +219,141 @@ internal sealed class MinerPlacementSolver // A legal crossing may require moving several miners together. Removing only one and // greedily refilling cannot escape that local optimum. Repack up to three nearby miners // with bounded, spatially diverse alternatives, enumerating their compatible combinations. - private IEnumerator Repack(int limit, int workers, CancellationToken cancellationToken) + private IEnumerator Repack(SeedCollisions seeds, int workers, CancellationToken cancellationToken) { - for (var round = 0; round < 2 && Best.Count > 0; round++) + var regions = Regions(seeds.Seeds); + var results = new SearchResult[regions.Count]; + for (var i = 0; i < results.Length; i++) results[i] = new SearchResult(Best, BestScore, _bestBuriedCount); + var work = RunBatch(regions.Count, index => RepackRegion(seeds, regions[index], results[index], cancellationToken), workers, cancellationToken); + while (work.MoveNext()) yield return null; + // Merge in the original region order, independent of worker completion order. + foreach (var result in results) Accept(result); + } + + // Each miner alone, with each of its three nearest neighbors, and with each pair of them. + private static List<(int, int, int)> Regions(List seeds) + { + var regions = new List<(int, int, int)>(); + var unique = new HashSet<(int, int, int)>(); + for (var pivot = 0; pivot < seeds.Count; pivot++) { - var seeds = new List(Best); - var initialScore = BestScore; - var initialBuried = _bestBuriedCount; - var regions = new HashSet<(int, int, int)>(); - for (var pivot = 0; pivot < seeds.Count; pivot++) + Add((pivot, -1, -1)); + var neighbors = new List(); + for (var i = 0; i < seeds.Count; i++) if (i != pivot) neighbors.Add(i); + neighbors.Sort((a, b) => (seeds[a].Position - seeds[pivot].Position).sqrMagnitude.CompareTo( + (seeds[b].Position - seeds[pivot].Position).sqrMagnitude)); + if (neighbors.Count > 3) neighbors.RemoveRange(3, neighbors.Count - 3); + foreach (var neighbor in neighbors) Add((Math.Min(pivot, neighbor), Math.Max(pivot, neighbor), -1)); + for (var a = 0; a < neighbors.Count; a++) + for (var b = a + 1; b < neighbors.Count; b++) { - regions.Add((pivot, -1, -1)); - var neighbors = new List(); - for (var i = 0; i < seeds.Count; i++) if (i != pivot) neighbors.Add(i); - neighbors.Sort((a, b) => (seeds[a].Position - seeds[pivot].Position).sqrMagnitude.CompareTo( - (seeds[b].Position - seeds[pivot].Position).sqrMagnitude)); - if (neighbors.Count > 3) neighbors.RemoveRange(3, neighbors.Count - 3); - foreach (var neighbor in neighbors) regions.Add((Math.Min(pivot, neighbor), Math.Max(pivot, neighbor), -1)); - for (var a = 0; a < neighbors.Count; a++) - for (var b = a + 1; b < neighbors.Count; b++) - { - var indices = new[] { pivot, neighbors[a], neighbors[b] }; - Array.Sort(indices); - regions.Add((indices[0], indices[1], indices[2])); - } + var indices = new[] { pivot, neighbors[a], neighbors[b] }; + Array.Sort(indices); + Add((indices[0], indices[1], indices[2])); } - // Every region keeps a subset of the same seeds. Compute each candidate/seed - // collision once, instead of repeating the SAT tests for every overlapping region. - var fits = new bool[seeds.Count][]; - var cacheWork = RunBatch(seeds.Count, index => CacheSeedFits(index, seeds[index], fits, cancellationToken), workers, cancellationToken); - while (cacheWork.MoveNext()) yield return null; - var regionList = new List<(int, int, int)>(regions); - var results = new SearchResult[regionList.Count]; - for (var i = 0; i < results.Length; i++) results[i] = new SearchResult(Best, BestScore, _bestBuriedCount); - var regionWork = RunBatch(regionList.Count, - index => RepackRegion(limit, seeds, regionList[index], fits, results[index], cancellationToken), workers, cancellationToken); - while (regionWork.MoveNext()) yield return null; - // Merge in the original region order, independent of worker completion order. - foreach (var result in results) Accept(result); - if (BestScore == initialScore && _bestBuriedCount == initialBuried && Best.Count == seeds.Count) break; } - } + return regions; - private IEnumerator CacheSeedFits(int index, Candidate seed, bool[][] fits, CancellationToken cancellationToken) - { - var row = new bool[_candidates.Count]; - for (var i = 0; i < row.Length; i++) + void Add((int, int, int) region) { - if ((i & 127) == 0) { cancellationToken.ThrowIfCancellationRequested(); yield return null; } - row[i] = PairFits(_candidates[i], seed); + if (unique.Add(region)) regions.Add(region); } - fits[index] = row; } - private IEnumerator RepackRegion(int limit, List seeds, (int, int, int) region, bool[][] fits, - SearchResult result, CancellationToken cancellationToken) + private static bool InRegion(int seed, (int, int, int) region) => seed == region.Item1 || seed == region.Item2 || seed == region.Item3; + + // Seed passes, repacking regions and the final refill keep a subset of the same seeds. Find + // the seeds that block each candidate once per seed set, instead of repeating the SAT tests. + private sealed class SeedCollisions(int candidateCount) { - var state = new PartialLayout(_nodeCount); + public List Seeds; + // Counts saturate past RegionSize: no single removal can free such a candidate. + public readonly byte[] Counts = new byte[candidateCount]; + public readonly int[] Blockers = new int[candidateCount * RegionSize]; + + // A negative seed removes nothing, so only unblocked candidates qualify. + public bool AllowsWithout(int candidate, int seed) => + Counts[candidate] == 0 || Counts[candidate] == 1 && Blockers[candidate * RegionSize] == seed; + + public bool Allows(int candidate, (int, int, int) region) + { + var count = Counts[candidate]; + if (count > RegionSize) return false; + for (var i = 0; i < count; i++) + if (!InRegion(Blockers[candidate * RegionSize + i], region)) return false; + return true; + } + } + + // Best is replaced, never mutated, so an unchanged reference keeps the collisions valid. + private IEnumerator TrackBest(SeedCollisions seeds, int workers, CancellationToken cancellationToken) + { + if (ReferenceEquals(seeds.Seeds, Best)) yield break; + seeds.Seeds = Best; + var chunks = Math.Max(1, workers * 4); + var size = (_candidates.Count + chunks - 1) / chunks; + var work = RunBatch(chunks, chunk => FindCollisions(seeds, chunk * size, Math.Min(_candidates.Count, (chunk + 1) * size), cancellationToken), + workers, cancellationToken); + while (work.MoveNext()) yield return null; + } + + private IEnumerator FindCollisions(SeedCollisions seeds, int start, int end, CancellationToken cancellationToken) + { + for (var i = start; i < end; i++) + { + if (((i - start) & 31) == 0) + { + cancellationToken.ThrowIfCancellationRequested(); + yield return null; + } + var count = 0; + for (var seed = 0; seed < seeds.Seeds.Count && count <= RegionSize; seed++) + { + if (PairFits(_candidates[i], seeds.Seeds[seed])) continue; + if (count < RegionSize) seeds.Blockers[i * RegionSize + count] = seed; + count++; + } + seeds.Counts[i] = (byte)count; + } + } + + private IEnumerator RepackRegion(SeedCollisions seeds, (int, int, int) region, SearchResult result, CancellationToken cancellationToken) + { + var layout = new Layout(_nodeCount); var removed = new List(); var centerX = 0f; var centerZ = 0f; - for (var i = 0; i < seeds.Count; i++) + for (var i = 0; i < seeds.Seeds.Count; i++) { - if (i != region.Item1 && i != region.Item2 && i != region.Item3) state.Add(seeds[i]); + var seed = seeds.Seeds[i]; + if (!InRegion(i, region)) layout.Add(seed); else { - removed.Add(seeds[i]); - centerX += seeds[i].X; - centerZ += seeds[i].Z; + removed.Add(seed); + centerX += seed.X; + centerZ += seed.Z; } } centerX /= removed.Count; centerZ /= removed.Count; - var slots = Math.Min(3, limit - state.Selected.Count); - if (slots <= 0) yield break; var buckets = new List<(Candidate Candidate, int Gain)>[8]; for (var b = 0; b < buckets.Length; b++) buckets[b] = []; for (var i = 0; i < _candidates.Count; i++) { - if ((i & 127) == 0) { cancellationToken.ThrowIfCancellationRequested(); yield return null; } + if ((i & 127) == 0) + { + cancellationToken.ThrowIfCancellationRequested(); + yield return null; + } var candidate = _candidates[i]; if (candidate.Covered.Length < MinimumCoverage) continue; var nearby = false; foreach (var seed in removed) if ((candidate.Position - seed.Position).sqrMagnitude <= 36f) { nearby = true; break; } - if (!nearby) continue; - var legal = true; - for (var j = 0; j < seeds.Count; j++) - if (j != region.Item1 && j != region.Item2 && j != region.Item3 && !fits[j][i]) { legal = false; break; } - if (!legal) continue; + if (!nearby || !seeds.Allows(i, region)) continue; var angle = Math.Atan2(candidate.Z - centerZ, candidate.X - centerX) + Math.PI; var bucket = Math.Min(7, (int)(angle * 4 / Math.PI)); - buckets[bucket].Add((candidate, state.Gain(candidate))); + buckets[bucket].Add((candidate, layout.Gain(candidate, out _))); } var options = new List(removed); foreach (var bucket in buckets) @@ -297,56 +376,101 @@ internal sealed class MinerPlacementSolver } } options.Sort((a, b) => b.Covered.Length.CompareTo(a.Covered.Length)); - var compatible = new bool[options.Count, options.Count]; + // Pruning skips most option pairs, so test their collisions only when reached. + var pairs = new sbyte[options.Count * options.Count]; var operations = 0; for (var i = 0; i < options.Count; i++) - for (var j = i + 1; j < options.Count; j++) { - if ((operations++ & 127) == 0) { cancellationToken.ThrowIfCancellationRequested(); yield return null; } - compatible[i, j] = PairFits(options[i], options[j]); - } - for (var i = 0; i < options.Count; i++) - { - state.Add(options[i]); - if (!state.HasMinimumCoverage()) { state.RemoveLast(); continue; } - Consider(state, result); - for (var j = i + 1; slots > 1 && j < options.Count; j++) + if (!layout.CanAdd(options[i])) continue; + layout.Add(options[i]); + Consider(layout, result); + for (var j = i + 1; j < options.Count; j++) { - if ((operations++ & 127) == 0) { cancellationToken.ThrowIfCancellationRequested(); yield return null; } - if (state.RawScore + (slots - 1) * options[j].Covered.Length < result.Score) break; - if (!compatible[i, j]) continue; - state.Add(options[j]); - if (!state.HasMinimumCoverage()) { state.RemoveLast(); continue; } - Consider(state, result); - for (var k = j + 1; slots > 2 && k < options.Count; k++) + if ((operations++ & 127) == 0) { - if ((operations++ & 127) == 0) { cancellationToken.ThrowIfCancellationRequested(); yield return null; } - if (state.RawScore + options[k].Covered.Length < result.Score) break; - if (!compatible[i, k] || !compatible[j, k]) continue; - state.Add(options[k]); - if (state.HasMinimumCoverage()) Consider(state, result); - state.RemoveLast(); + cancellationToken.ThrowIfCancellationRequested(); + yield return null; } - state.RemoveLast(); + if (layout.RawScore + (RegionSize - 1) * options[j].Covered.Length < result.Score) break; + if (!Compatible(i, j) || !layout.CanAdd(options[j])) continue; + layout.Add(options[j]); + Consider(layout, result); + for (var k = j + 1; k < options.Count; k++) + { + if ((operations++ & 127) == 0) + { + cancellationToken.ThrowIfCancellationRequested(); + yield return null; + } + if (layout.RawScore + options[k].Covered.Length < result.Score) break; + if (!Compatible(i, k) || !Compatible(j, k) || !layout.CanAdd(options[k])) continue; + layout.Add(options[k]); + Consider(layout, result); + layout.RemoveLast(); + } + layout.RemoveLast(); } - state.RemoveLast(); + layout.RemoveLast(); + } + + bool Compatible(int first, int second) + { + var slot = first * options.Count + second; + if (pairs[slot] == 0) pairs[slot] = PairFits(options[first], options[second]) ? (sbyte)1 : (sbyte)-1; + return pairs[slot] > 0; } } - private sealed class PartialLayout(int nodeCount) + // A partial layout. Score counts each visible node once per covering miner; RawScore + // ignores burials and is therefore an upper bound for pruning. + private sealed class Layout(int nodeCount) { public readonly List Selected = []; private readonly int[] _buried = new int[nodeCount], _uses = new int[nodeCount]; public int Score, RawScore, BuriedCount; - public int Gain(Candidate candidate) + public int Gain(Candidate candidate, out int coverage) { - var gain = 0; - foreach (var index in candidate.Covered) if (_buried[index] == 0) gain++; + coverage = Coverage(candidate); + var gain = coverage; foreach (var index in candidate.Buried) if (_buried[index] == 0) gain -= _uses[index]; return gain; } + private int Coverage(Candidate candidate) + { + var coverage = 0; + foreach (var index in candidate.Covered) if (_buried[index] == 0) coverage++; + return coverage; + } + + public bool CanAdd(Candidate candidate) => Coverage(candidate) >= MinimumCoverage && PreservesCoverage(candidate); + + public bool FitsFrom(Candidate candidate, int start) + { + for (var i = start; i < Selected.Count; i++) + if (!PairFits(candidate, Selected[i])) return false; + return true; + } + + // A placement must not invalidate an earlier miner, even if the total gain is positive. + // Every selected miner already keeps the minimum, so only newly buried used nodes matter. + public bool PreservesCoverage(Candidate candidate) + { + var affected = false; + foreach (var index in candidate.Buried) + if (_buried[index] == 0 && _uses[index] > 0) { affected = true; break; } + if (!affected) return true; + foreach (var other in Selected) + { + var visible = 0; + foreach (var index in other.Covered) + if (_buried[index] == 0 && Array.IndexOf(candidate.Buried, index) < 0 && ++visible >= MinimumCoverage) break; + if (visible < MinimumCoverage) return false; + } + return true; + } + public void Add(Candidate candidate) { RawScore += candidate.Covered.Length; @@ -373,74 +497,14 @@ internal sealed class MinerPlacementSolver foreach (var index in candidate.Buried) if (--_buried[index] == 0) { Score += _uses[index]; BuriedCount--; } } - - public bool HasMinimumCoverage() - { - foreach (var candidate in Selected) - { - var visible = 0; - foreach (var index in candidate.Covered) - if (_buried[index] == 0 && ++visible >= MinimumCoverage) break; - if (visible < MinimumCoverage) return false; - } - return true; - } } - private static void Consider(PartialLayout state, SearchResult result) + private static void Consider(Layout layout, SearchResult result) { - if (!IsBetter(state.Score, state.BuriedCount, state.Selected.Count, result.Score, result.BuriedCount, result.Selected.Count)) return; - result.Selected = new List(state.Selected); - result.Score = state.Score; - result.BuriedCount = state.BuriedCount; - } - - private static int CountBuried(List selected) - { - var buried = new HashSet(); - foreach (var candidate in selected) buried.UnionWith(candidate.Buried); - return buried.Count; - } - - private static int Gain(Candidate candidate, bool[] buried, int[] uses, out int coverage) - { - coverage = 0; - foreach (var index in candidate.Covered) if (!buried[index]) coverage++; - var gain = coverage; - foreach (var index in candidate.Buried) if (!buried[index]) gain -= uses[index]; - return gain; - } - - private static void Add(Candidate candidate, List selected, bool[] buried, int[] uses, ref int score) - { - foreach (var index in candidate.Buried) - { - if (buried[index]) continue; - buried[index] = true; - score -= uses[index]; - uses[index] = 0; - } - foreach (var index in candidate.Covered) - { - if (buried[index]) continue; - uses[index]++; - score++; - } - selected.Add(candidate); - } - - private static bool PreservesCoverage(Candidate candidate, List selected, bool[] buried) - { - if (candidate.Buried.Length == 0) return true; - // A placement must not invalidate an earlier miner, even if the total gain is positive. - foreach (var other in selected) - { - var visible = 0; - foreach (var index in other.Covered) - if (!buried[index] && Array.IndexOf(candidate.Buried, index) < 0 && ++visible >= MinimumCoverage) break; - if (visible < MinimumCoverage) return false; - } - return true; + if (!IsBetter(layout.Score, layout.BuriedCount, layout.Selected.Count, result.Score, result.BuriedCount, result.Selected.Count)) return; + result.Selected = new List(layout.Selected); + result.Score = layout.Score; + result.BuriedCount = layout.BuriedCount; } public static bool Fits(Candidate candidate, List selected) @@ -461,9 +525,9 @@ internal sealed class MinerPlacementSolver private static bool Intersects(MinerPlacementGeometry.Box[] a, MinerPlacementGeometry.Box[] b) { - foreach (var first in a) - foreach (var second in b) - if (MinerPlacementGeometry.Intersects(first, second)) return true; + for (var i = 0; i < a.Length; i++) + for (var j = 0; j < b.Length; j++) + if (MinerPlacementGeometry.Intersects(in a[i], in b[j])) return true; return false; } } diff --git a/UXAssist/Functions/Factory/QuickMinerBuild.cs b/UXAssist/Functions/Factory/QuickMinerBuild.cs index 0b90e87..8623cf9 100644 --- a/UXAssist/Functions/Factory/QuickMinerBuild.cs +++ b/UXAssist/Functions/Factory/QuickMinerBuild.cs @@ -22,7 +22,6 @@ namespace UXAssist.Functions.Factory; public static class QuickMinerBuild { private static Job _job; - private static IEnumerator _work; private static readonly Stopwatch FrameTimer = new(); private static UIRealtimeTip _resultTip; private static string _resultText; @@ -42,7 +41,7 @@ public static class QuickMinerBuild ReleaseResultTip(true); if (IsRunning) { - Cancel(); + Stop(); UIRealtimeTip.Popup(I18NKeys.QuickMinerCancelled.Translate()); return; } @@ -57,7 +56,6 @@ public static class QuickMinerBuild try { _job = new Job(player, planet); - _work = _job.Run(); UIRealtimeTip.Popup(I18NKeys.QuickMinerSearching.Translate()); } catch (Exception exception) @@ -72,7 +70,7 @@ public static class QuickMinerBuild if (_job == null) return; if (!_job.IsCurrent) { - Cancel(); + Stop(); return; } if (GameMain.isPaused) return; @@ -81,13 +79,12 @@ public static class QuickMinerBuild FrameTimer.Restart(); while (FrameTimer.ElapsedMilliseconds < 6) { - if (_work.MoveNext()) + if (!_job.Step()) { - if (_job.WaitingForWorkers) break; - continue; + Stop(); + break; } - Cancel(); - break; + if (_job.WaitingForWorkers) break; } } catch (Exception exception) @@ -100,21 +97,21 @@ public static class QuickMinerBuild { UXAssist.Logger.LogError($"Quick miner placement failed: {exception}"); _job?.RecordFailure(exception); - Cancel(); + Stop(); UIRealtimeTip.Popup(I18NKeys.QuickMinerFailed.Translate()); } - private static void Cancel() + // Completion, failure and cancellation all finish the job, which records its debug data. + private static void Stop() { - _job?.Cancel(); - (_work as IDisposable)?.Dispose(); - _work = null; + var job = _job; _job = null; + job?.Finish(); } private static void OnGameEnd() { - Cancel(); + Stop(); ReleaseResultTip(true); } @@ -168,28 +165,36 @@ public static class QuickMinerBuild private sealed class Job { + // IsTargetVeinInRange accepts nodes within 7.75m horizontally and 2m vertically of a + // point 1.2m behind the miner, after scaling both positions to a 200m radius. + private const float MaxVeinReach = 9.25f; private readonly Player _player; private readonly PlanetData _planet; private readonly PlanetFactory _factory; private readonly PlanetPhysics _physics; private readonly ItemProto _item; private readonly List _nodes = []; - private readonly List _obstacles = []; + private readonly List _obstacles = [], _nearObstacles = []; + private readonly List _ejectors = []; private readonly List _candidates = []; - private readonly List _covered = [], _buried = []; + private readonly List _covered = [], _buried = [], _reachable = [], _touching = []; private readonly Box[] _buildBoxes, _obstacleBoxes; private readonly ColliderData[] _nativeObstacles; - private readonly float _footprintRadius; + private readonly ColliderData _body; + private readonly float _footprintRadius, _halfDiagonal; + private readonly bool _capsule; private readonly MinerPlacementDebug.Snapshot _debug = new(); private readonly List _phases = []; private readonly List _placements = []; private readonly Stopwatch _timer = Stopwatch.StartNew(); private readonly CancellationTokenSource _cancellation = new(); private readonly int _workers = MinerPlacementSolver.WorkerCount; + private IEnumerator _work; private Task _search; - private long _searchMilliseconds; private string _result; - private Vector3 _center, _right, _forward; + private Vector3 _center, _right, _forward, _probe; + private float _probeX = float.NaN, _probeZ = float.NaN; + private bool _probeRestricted; private EVeinType _type; private float _minX, _maxX, _minZ, _maxZ; @@ -206,6 +211,7 @@ public static class QuickMinerBuild _item = LDB.items.Select(ItemIds.MiningMachine); var desc = _item.prefabDesc; _buildBoxes = new Box[desc.buildColliders.Length]; + _body = desc.buildColliders.OrderByDescending(c => c.ext.x * c.ext.y * c.ext.z).First(); var obstacles = new List(); foreach (var collider in desc.colliders) { @@ -216,6 +222,9 @@ public static class QuickMinerBuild } _nativeObstacles = obstacles.ToArray(); _obstacleBoxes = new Box[_nativeObstacles.Length]; + // Native clearance checks measure from the encompassing build collider. + _halfDiagonal = Mathf.Sqrt(desc.buildCollider.ext.x * desc.buildCollider.ext.x + desc.buildCollider.ext.z * desc.buildCollider.ext.z); + _capsule = planet.id == planet.galaxy.birthPlanetId && GameMain.history.SpaceCapsuleExist(); _debug.version = PluginInfo.PLUGIN_VERSION; _debug.gameVersion = GameConfig.gameVersion.ToString(); _debug.startedUtc = DateTime.UtcNow.ToString("O"); @@ -233,30 +242,7 @@ public static class QuickMinerBuild _debug.outcome = "cancelled"; } - public IEnumerator Run() - { - try - { - var work = RunCore(); - try - { - while (true) - { - bool next; - try { next = work.MoveNext(); } - catch (Exception exception) { RecordFailure(exception); throw; } - if (!next) break; - yield return null; - } - } - finally { (work as IDisposable)?.Dispose(); } - } - finally - { - var location = WriteDebug(); - if (_result != null) ShowResult(_result + "\n" + location); - } - } + public bool Step() => (_work ??= Run()).MoveNext(); public void RecordFailure(Exception exception) { @@ -264,7 +250,7 @@ public static class QuickMinerBuild _debug.error = exception.ToString(); } - public void Cancel() + public void Finish() { _cancellation.Cancel(); if (_search == null || _search.IsCompleted) @@ -277,27 +263,12 @@ public static class QuickMinerBuild if (task.IsFaulted) _ = task.Exception; _cancellation.Dispose(); }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + (_work as IDisposable)?.Dispose(); + var location = WriteDebug(); + if (_result != null) ShowResult(_result + "\n" + location); } - private IEnumerator Search(MinerPlacementSolver solver, int passes) - { - var timer = Stopwatch.StartNew(); - if (_workers > 0) - { - _search = solver.SearchAsync(int.MaxValue, passes, _cancellation.Token, _workers); - while (!_search.IsCompleted) yield return null; - _search.GetAwaiter().GetResult(); - _search = null; - } - else - { - var work = solver.Search(passes); - while (work.MoveNext()) yield return null; - } - _searchMilliseconds = timer.ElapsedMilliseconds; - } - - private IEnumerator RunCore() + private IEnumerator Run() { if (!FindNodes()) { @@ -321,36 +292,42 @@ public static class QuickMinerBuild } } var solver = new MinerPlacementSolver(_candidates, _nodes.Count); - var search = Search(solver, 10); - while (search.MoveNext()) yield return null; - RecordPhase("coarse", solver, 10); - var packing = PackingNeighbors(solver.Best); - while (packing.MoveNext()) yield return null; - var refine = Refine(solver.Best, 0.35f, 3f); - while (refine.MoveNext()) yield return null; - search = Search(solver, 6); - while (search.MoveNext()) yield return null; - RecordPhase("refine-position", solver, 6); - packing = PackingNeighbors(solver.Best); - while (packing.MoveNext()) yield return null; - refine = Refine(solver.Best, 0.12f, 1f); - while (refine.MoveNext()) yield return null; - search = Search(solver, 4); - while (search.MoveNext()) yield return null; - RecordPhase("refine-angle", solver, 4); - if (IsCurrent) - { - _debug.outcome = "completed"; - Commit(solver.Best); - } + var work = Search(solver, "coarse", 10); + while (work.MoveNext()) yield return null; + work = Expand(solver.Best, 0.35f, 3f); + while (work.MoveNext()) yield return null; + work = Search(solver, "refine-position", 6); + while (work.MoveNext()) yield return null; + work = Expand(solver.Best, 0.12f, 1f); + while (work.MoveNext()) yield return null; + work = Search(solver, "refine-angle", 4); + while (work.MoveNext()) yield return null; + _debug.outcome = "completed"; + Commit(solver.Best); } - private void RecordPhase(string name, MinerPlacementSolver solver, int passes) => _phases.Add(new MinerPlacementDebug.Phase + private IEnumerator Search(MinerPlacementSolver solver, string phase, int passes) { - name = name, candidateCount = _candidates.Count, limit = int.MaxValue, passes = passes, score = solver.BestScore, - searchMilliseconds = _searchMilliseconds, - selected = solver.Best.Select(candidate => _candidates.IndexOf(candidate)).ToArray(), elapsedMilliseconds = _timer.ElapsedMilliseconds - }); + var timer = Stopwatch.StartNew(); + if (_workers > 0) + { + _search = solver.SearchAsync(passes, _cancellation.Token, _workers); + while (!_search.IsCompleted) yield return null; + _search.GetAwaiter().GetResult(); + _search = null; + } + else + { + var work = solver.Search(passes); + while (work.MoveNext()) yield return null; + } + _phases.Add(new MinerPlacementDebug.Phase + { + name = phase, candidateCount = _candidates.Count, passes = passes, score = solver.BestScore, + searchMilliseconds = timer.ElapsedMilliseconds, elapsedMilliseconds = _timer.ElapsedMilliseconds, + selected = solver.Best.Select(candidate => _candidates.IndexOf(candidate)).ToArray() + }); + } private string WriteDebug() { @@ -442,6 +419,7 @@ public static class QuickMinerBuild _obstacles.Add(collider); } } + FindEjectors(radius); var reserved = ReservedNodes(); for (var i = 1; i < _factory.veinCursor; i++) { @@ -485,6 +463,29 @@ public static class QuickMinerBuild return _nodes.Count > 0; } + // Ejectors and their prebuilds near the search area; see Restricted. + private void FindEjectors(float radius) + { + if (_center.magnitude - _planet.realRadius + _item.prefabDesc.cullingHeight <= 4.9f) return; + var bound = radius + 7.2f + _halfDiagonal; + var factorySystem = _factory.factorySystem; + for (var i = 1; i < factorySystem.ejectorCursor; i++) + { + if (factorySystem.ejectorPool[i].id == i) Add(_factory.entityPool[factorySystem.ejectorPool[i].entityId].pos); + } + for (var i = 1; i < _factory.prebuildCursor; i++) + { + ref var prebuild = ref _factory.prebuildPool[i]; + if (prebuild.id == i && LDB.items.Select(prebuild.protoId)?.prefabDesc.isEjector == true) Add(prebuild.pos); + } + return; + + void Add(Vector3 position) + { + if ((position - _center).sqrMagnitude <= bound * bound) _ejectors.Add(position); + } + } + private HashSet ReservedNodes() { var reserved = new HashSet(); @@ -502,9 +503,19 @@ public static class QuickMinerBuild private void RestoreTargetVeins() { var changed = false; + var bases = _factory.enemySystem.bases; foreach (var node in _nodes) { if (!node.Target || node.Visible) continue; + // Like native reform, keep nodes buried within reach of Dark Fog ground bases. + var reformPoint = node.Position.normalized * _planet.realRadius; + var nearBase = false; + for (var i = 1; i < bases.cursor && !nearBase; i++) + { + var dfBase = bases.buffer[i]; + nearBase = dfBase != null && dfBase.id == i && (reformPoint - (Vector3)_factory.enemyPool[dfBase.enemyId].pos).sqrMagnitude < 136.5625f; + } + if (nearBase) continue; var surface = node.Position.normalized * (_planet.data.QueryModifiedHeight(node.Position) - 0.13f); var collider = node.Collider; collider.pos = surface + surface.normalized * 0.4f; @@ -536,8 +547,30 @@ public static class QuickMinerBuild if (changed) RefreshVeins(2); } - private IEnumerator Refine(List seeds, float distance, float angle) + // Seed the next search around the current best layout: body-width neighbors whose feet + // can interleave, then a local grid of positions and rotations. + private IEnumerator Expand(List seeds, float distance, float angle) { + foreach (var seed in seeds) + for (var turn = -15f; turn <= 15f; turn += 5f) + for (var side = -1; side <= 1; side++) + for (var clearance = 0.03f; clearance <= 0.14f; clearance += 0.05f) + for (var stagger = -2; stagger <= 2; stagger++) + { + if (side == 0 && clearance > 0.03f) continue; + // The legal interleaving gap is narrower than the coarse grid. Derive nearby + // rows from the actual body width instead of expanding a rectangle over the feet. + var rotation = seed.Rotation * Quaternion.AngleAxis(turn, Vector3.up); + var offset = rotation * _body.q * new Vector3(side * (_body.ext.x * 2f + clearance), 0f, stagger * 0.6f); + var x = seed.X + Vector3.Dot(offset, _right); + var z = seed.Z + Vector3.Dot(offset, _forward); + var frame = Maths.SphericalRotation(SurfacePoint(x, z), 0f); + var forward = rotation * Vector3.forward; + // Preserve the neighbor's surface heading across the planet's changing local frame. + var yaw = Mathf.Atan2(Vector3.Dot(forward, frame * Vector3.right), Vector3.Dot(forward, frame * Vector3.forward)) * Mathf.Rad2Deg; + TryCandidate(x, z, yaw); + yield return null; + } foreach (var seed in seeds) for (var x = -2; x <= 2; x++) for (var z = -2; z <= 2; z++) @@ -548,47 +581,24 @@ public static class QuickMinerBuild } } - private IEnumerator PackingNeighbors(List seeds) - { - var body = _item.prefabDesc.buildColliders.OrderByDescending(c => c.ext.x * c.ext.y * c.ext.z).First(); - foreach (var seed in seeds) - for (var angle = -15f; angle <= 15f; angle += 5f) - for (var side = -1; side <= 1; side++) - for (var clearance = 0.03f; clearance <= 0.14f; clearance += 0.05f) - for (var stagger = -2; stagger <= 2; stagger++) - { - if (side == 0 && clearance > 0.03f) continue; - // The legal interleaving gap is narrower than the coarse grid. Derive nearby - // rows from the actual body width instead of expanding a rectangle over the feet. - var rotation = seed.Rotation * Quaternion.AngleAxis(angle, Vector3.up); - var bodyRotation = rotation * body.q; - var offset = bodyRotation * new Vector3(side * (body.ext.x * 2f + clearance), 0f, stagger * 0.6f); - var x = seed.X + Vector3.Dot(offset, _right); - var z = seed.Z + Vector3.Dot(offset, _forward); - var position = (_center + _right * x + _forward * z).normalized * (_planet.realRadius + 0.2f); - var frame = Maths.SphericalRotation(position, 0f); - var forward = rotation * Vector3.forward; - // Preserve the neighbor's surface heading across the planet's changing local frame. - var yaw = Mathf.Atan2(Vector3.Dot(forward, frame * Vector3.right), Vector3.Dot(forward, frame * Vector3.forward)) * Mathf.Rad2Deg; - TryCandidate(x, z, yaw); - yield return null; - } - } + private Vector3 SurfacePoint(float x, float z) => (_center + _right * x + _forward * z).normalized * (_planet.realRadius + 0.2f); private void TryCandidate(float x, float z, float yaw) { _debug.rejections.attempted++; - var pos = (_center + _right * x + _forward * z).normalized * (_planet.realRadius + 0.2f); + if (x != _probeX || z != _probeZ) Probe(x, z); + var pos = _probe; if (!FactoryPatch.RemoveBuildRangeLimitEnabled.Value && (pos - _player.position).sqrMagnitude > _player.mecha.buildArea * _player.mecha.buildArea) { _debug.rejections.range++; return; } + if (_probeRestricted) { _debug.rejections.clearance++; return; } var rotation = Maths.SphericalRotation(pos, yaw); var pose = new Pose(pos, rotation); _covered.Clear(); - for (var i = 0; i < _nodes.Count; i++) + foreach (var i in _reachable) { var node = _nodes[i]; - if (!node.Visible || node.Type == EVeinType.Oil || !MinerComponent.IsTargetVeinInRange(node.Position, pose, _item.prefabDesc)) continue; + if (!MinerComponent.IsTargetVeinInRange(node.Position, pose, _item.prefabDesc)) continue; if (node.Type != _type) { _debug.rejections.mixedType++; return; } _covered.Add(i); } @@ -596,16 +606,16 @@ public static class QuickMinerBuild for (var i = 0; i < _buildBoxes.Length; i++) _buildBoxes[i] = new Box(_item.prefabDesc.buildColliders[i].BindToObject(0, 0, EObjectType.None, pos, rotation)); _buried.Clear(); - for (var i = 0; i < _nodes.Count; i++) + foreach (var i in _touching) { var node = _nodes[i]; - if (!node.Visible || !Hits(node.Collider)) continue; + if (!Hits(node.Collider)) continue; if (!node.CanBury) { _debug.rejections.veinCollision++; return; } _buried.Add(i); } foreach (var index in _buried) _covered.Remove(index); if (_covered.Count < MinerPlacementSolver.MinimumCoverage) { _debug.rejections.noCoverage++; return; } - foreach (var obstacle in _obstacles) + foreach (var obstacle in _nearObstacles) if (Hits(obstacle)) { _debug.rejections.buildingCollision++; return; } if (!HasGround(pos, rotation)) { _debug.rejections.ground++; return; } for (var i = 0; i < _nativeObstacles.Length; i++) @@ -618,6 +628,49 @@ public static class QuickMinerBuild }); } + // Candidate positions repeat across yaw angles. Keep only the nodes and obstacles that can + // interact with a miner here; the rest fail the native range and collision tests anyway. + private void Probe(float x, float z) + { + _probeX = x; + _probeZ = z; + _probe = SurfacePoint(x, z); + _probeRestricted = Restricted(_probe); + var rangePoint = _probe.normalized * 200f; + _reachable.Clear(); + _touching.Clear(); + _nearObstacles.Clear(); + for (var i = 0; i < _nodes.Count; i++) + { + var node = _nodes[i]; + if (!node.Visible) continue; + if (node.Type != EVeinType.Oil && (node.Position.normalized * 200f - rangePoint).sqrMagnitude <= MaxVeinReach * MaxVeinReach) + _reachable.Add(i); + if (Near(node.Collider)) _touching.Add(i); + } + foreach (var obstacle in _obstacles) + if (Near(obstacle)) _nearObstacles.Add(obstacle); + } + + // Native placement keeps buildings clear of the birth planet's landing capsule and, when + // they are tall enough to obstruct launches, of EM Rail Ejectors. + private bool Restricted(Vector3 position) + { + if (_capsule && (position - _planet.birthPoint).magnitude - _halfDiagonal < 3.7f) return true; + var clearance = 7.2f + _halfDiagonal; + foreach (var ejector in _ejectors) + if ((ejector - position).sqrMagnitude < clearance * clearance) return true; + return false; + } + + // Every build box lies within the footprint radius of the probe, so a farther collider + // also fails each box's bounding-sphere test in Hits. + private bool Near(ColliderData collider) + { + var bound = _footprintRadius + collider.ext.magnitude + collider.radius + 0.01f; + return (collider.pos - _probe).sqrMagnitude <= bound * bound; + } + private bool Hits(ColliderData collider) { foreach (var box in _buildBoxes) @@ -649,6 +702,12 @@ public static class QuickMinerBuild private void Commit(List layout) { + if (layout.Count == 0) + { + _debug.outcome = "no-placement"; + _result = I18NKeys.QuickMinerNoPlacement.Translate(); + return; + } if (!NodesUnchanged(layout)) { _debug.outcome = "veins-changed"; @@ -658,12 +717,6 @@ public static class QuickMinerBuild var placed = new List<(Candidate Candidate, int Prebuild, MinerPlacementDebug.Placement Debug)>(); var plannedBurial = layout.SelectMany(candidate => candidate.Buried).Select(index => _nodes[index].Id).ToHashSet(); var hidden = new Dictionary(); - if (layout.Count == 0) - { - _debug.outcome = "no-placement"; - _result = I18NKeys.QuickMinerNoPlacement.Translate(); - return; - } var coverage = 0; var buriedCount = 0; var validator = new BuildTool_Click(); @@ -677,9 +730,8 @@ public static class QuickMinerBuild validator.tmpPackage = new StorageComponent(1); var preview = new BuildPreview(); validator.buildPreviews.Add(preview); - for (var i = 0; i < layout.Count; i++) + foreach (var candidate in layout) { - var candidate = layout[i]; var debug = new MinerPlacementDebug.Placement { candidate = _candidates.IndexOf(candidate), outcome = "pending", nativeCondition = "not-checked", nativeVeins = [], plannedVeins = [], finalVeins = [] @@ -694,7 +746,8 @@ public static class QuickMinerBuild hidden.Add(node.Id, vein.pos); SetVeinPosition(node.Id, vein.pos.normalized * (_planet.realRadius - 50f)); } - RefreshVeins(0); + // Validation needs current Unity colliders; GPU buffers are synced once at the end. + _physics.RefreshColliders(); if (!Validate(validator, preview, candidate, plannedBurial, debug)) continue; var itemId = ItemIds.MiningMachine; var count = 1; @@ -773,10 +826,10 @@ public static class QuickMinerBuild return true; } + // CheckBuildConditions repeats the search's land-point tests, so ground needs no separate check. private bool Validate(BuildTool_Click validator, BuildPreview preview, Candidate candidate, HashSet plannedBurial, MinerPlacementDebug.Placement debug) { debug.outcome = "native-rejected"; - if (!HasGround(candidate.Position, candidate.Rotation)) { debug.outcome = "ground-changed"; return false; } preview.ResetAll(); preview.item = _item; preview.desc = _item.prefabDesc; diff --git a/UXAssist/README.md b/UXAssist/README.md index 51dc40d..967eca2 100644 --- a/UXAssist/README.md +++ b/UXAssist/README.md @@ -83,10 +83,10 @@ * Set a maximum number to build per operation; 0 builds as many as possible * Quick build Mining Machines * Use the button on the Factory tab near Quick build Orbital Collectors. Places the full ordinary Mining Machine layout at the nearest solid vein group regardless of carried stock. Uses available miners from the inventory and hand; missing miners remain as ghosts awaiting materials. Every placed miner must retain at least 3 covered nodes after all planned burials; miners below that minimum are invalid. - * Restores buried nodes unless obstructed by buildings, then searches individual native collision shapes so the miner's feet can interleave where the game permits. + * Restores buried nodes unless obstructed by buildings or near Dark Fog Planetary Bases, then searches individual native collision shapes so the miner's feet can interleave where the game permits. * Uses multiple packing orders, exploration keyed by placement pose as well as candidate index, local position/rotation refinement, body-width neighbor candidates, and coordinated repacking of up to three nearby miners to seek a high sum of vein counts across all placed miners. A final pass fills remaining compatible candidates when they increase total coverage while preserving the three-node minimum. Shared nodes count once per miner; this bounded search does not guarantee a global optimum. * Reuses collision checks and runs independent layout searches on up to 4 background workers, capped at half the available logical processors. Systems with one logical processor keep the search on the main thread with a frame budget. Native terrain checks and placement stay on the main thread; worker scheduling preserves the same layout as sequential search. - * May bury unused nodes when that improves total coverage. Nodes already assigned to miners or miner prebuilds are protected. Ground, water, existing buildings, and construction range still apply. + * May bury unused nodes when that improves total coverage. Nodes already assigned to miners or miner prebuilds are protected. Ground, water, existing buildings, construction range, and the game's other placement clearances still apply. * Click again during calculation to cancel. Changing planets or leaving the game cancels automatically. Construction drones finish the prebuilds; belts and power supply are not placed. * While tuning this feature, each calculation writes a timestamped JSON snapshot to `BepInEx/debug/UXAssist/QuickMiner/` in the active game profile, including nodes, native colliders, accepted candidates, search phases and their search times, logical processor and worker counts, existing miners, and native placement results. The completion tip stays visible for about 8 seconds; the log also records the result summary and full file path. Replay and compare sequential/parallel results without loading a save using `powershell -File tools/tests/Test-QuickMinerPlacement.ps1 -Snapshot ` from the repository root. Replay fails if total coverage falls below the recorded result; add `-MinimumTotalCoverage ` to require a higher total. * Belt signals for buy out dark fog items automatically @@ -283,10 +283,10 @@ * 可设置单次建造数量上限;设为 0 时尽可能多地建造 * 快速铺设采矿机 * 点击「工厂」页中轨道采集器按钮附近的按钮,在最近的固体矿脉生成完整的普通采矿机布局,数量不受库存限制。有采矿机时正常消耗背包和手持物品,不足的位置保留待建造虚影,等待补充材料。所有计划掩埋完成后,每台矿机仍须覆盖至少 3 个矿点;少于 3 个的视为无效,不予铺设。 - * 先还原未被建筑阻挡的掩埋矿点,再按原版独立碰撞体搜索布局,保留游戏允许的矿机脚部交叉空间。 + * 先还原未被建筑阻挡且不在黑雾行星基地附近的掩埋矿点,再按原版独立碰撞体搜索布局,保留游戏允许的矿机脚部交叉空间。 * 比较多种铺设顺序,同时按候选序号及位置朝向探索不同布局,细调位置和朝向,按机身宽度补充紧邻候选,并允许邻近的两三台矿机一起重新布局,尽量提高各台矿机覆盖矿点数之和。结束前再扫描全部候选,继续补入能提高总覆盖数、且不破坏每台至少覆盖 3 点要求的矿机。同一矿点被多台矿机覆盖时重复计数。计算有界,不保证全局最优。 * 复用碰撞检查结果,使用最多 4 个后台线程并行搜索独立布局,线程数不超过可用逻辑线程数的一半。单逻辑线程系统继续在主线程按每帧预算计算。原生地形检查和实际铺设保留在主线程;并行调度与顺序搜索生成相同布局。 - * 允许掩埋未被使用的矿点来提高总覆盖数;保护已有矿机及待建造矿机使用的矿点。仍需满足地面、水面、现有建筑和建造范围要求。 + * 允许掩埋未被使用的矿点来提高总覆盖数;保护已有矿机及待建造矿机使用的矿点。仍需满足地面、水面、现有建筑、建造范围及游戏的其他放置间距要求。 * 计算期间再次点击可取消,切换行星或退出游戏自动取消。待建造对象由建设机器人完成,不自动铺设传送带和电力设施。 * 功能调试期间,每次计算都会在当前游戏配置目录的 `BepInEx/debug/UXAssist/QuickMiner/` 下写入带时间戳的 JSON 文件,记录矿点、原生碰撞体、有效候选、搜索阶段及其搜索耗时、逻辑线程数和工作线程数、现有矿机和原生铺设校验结果。完成提示保留约 8 秒,日志也会记录结果摘要和文件的完整路径。在仓库根目录运行 `powershell -File tools/tests/Test-QuickMinerPlacement.ps1 -Snapshot `,即可离线重放并比较顺序与并行搜索结果,无需读取存档。总覆盖数低于记录结果时,重放检查会失败;可追加 `-MinimumTotalCoverage <数量>`,要求达到更高的总覆盖数。 * 用于自动购买黑雾物品的传送带信号 diff --git a/tools/tests/QuickMinerPlacementTests.cs b/tools/tests/QuickMinerPlacementTests.cs index 1cd7293..8f32a32 100644 --- a/tools/tests/QuickMinerPlacementTests.cs +++ b/tools/tests/QuickMinerPlacementTests.cs @@ -40,22 +40,21 @@ internal static class QuickMinerPlacementTests ObstacleBoxes = [new Box(Collider(new Vector3(x, 0, 0), new Vector3(halfWidth, 0.4f, 0.4f), Quaternion.identity))] }; - private static MinerPlacementSolver Solve(List candidates, int nodes, int? limit = null, int passes = 12) + private static MinerPlacementSolver Solve(List candidates, int nodes, int passes = 12) { var solver = new MinerPlacementSolver(candidates, nodes); - var search = limit.HasValue ? solver.Search(limit.Value, passes) : solver.Search(passes); + var search = solver.Search(passes); var steps = 0; while (search.MoveNext()) if (++steps > 2000000) throw new InvalidOperationException("Search did not terminate."); if (MinerPlacementSolver.WorkerCount > 0) { var parallel = new MinerPlacementSolver(candidates, nodes); - parallel.SearchAsync(limit ?? int.MaxValue, passes, CancellationToken.None).GetAwaiter().GetResult(); + parallel.SearchAsync(passes, CancellationToken.None).GetAwaiter().GetResult(); Check(parallel.BestScore == solver.BestScore && parallel.Best.SequenceEqual(solver.Best), "Parallel scheduling must preserve the exact sequential layout, including ties."); } var buried = solver.Best.SelectMany(c => c.Buried).ToHashSet(); var expected = solver.Best.Sum(c => c.Covered.Count(n => !buried.Contains(n))); - Check(solver.Best.Count <= (limit ?? int.MaxValue), "Explicit placement limit exceeded."); Check(solver.BestScore == expected, "Score does not match the final burial union."); for (var i = 0; i < solver.Best.Count; i++) { @@ -63,17 +62,14 @@ internal static class QuickMinerPlacementTests "Placed a miner below the minimum after the full burial union."); Check(MinerPlacementSolver.Fits(solver.Best[i], solver.Best.Take(i).ToList()), "Plan contains colliding miners."); } - if (solver.Best.Count < (limit ?? int.MaxValue)) + var canImprove = candidates.Any(candidate => { - var canImprove = candidates.Any(candidate => - { - if (candidate.Covered.Length < MinerPlacementSolver.MinimumCoverage || !MinerPlacementSolver.Fits(candidate, solver.Best)) return false; - var trialBurial = buried.Concat(candidate.Buried).ToHashSet(); - var counts = solver.Best.Append(candidate).Select(c => c.Covered.Count(n => !trialBurial.Contains(n))).ToArray(); - return counts.All(count => count >= MinerPlacementSolver.MinimumCoverage) && counts.Sum() > expected; - }); - Check(!canImprove, "Search left a legal positive-gain miner unplaced in its candidate set."); - } + if (candidate.Covered.Length < MinerPlacementSolver.MinimumCoverage || !MinerPlacementSolver.Fits(candidate, solver.Best)) return false; + var trialBurial = buried.Concat(candidate.Buried).ToHashSet(); + var counts = solver.Best.Append(candidate).Select(c => c.Covered.Count(n => !trialBurial.Contains(n))).ToArray(); + return counts.All(count => count >= MinerPlacementSolver.MinimumCoverage) && counts.Sum() > expected; + }); + Check(!canImprove, "Search left a legal positive-gain miner unplaced in its candidate set."); return solver; } @@ -84,43 +80,39 @@ internal static class QuickMinerPlacementTests "Workers must not exceed four or half of the available logical processors."); Check(MinerPlacementSolver.GetWorkerCount(1) == 0, "Single-core machines must use the main-thread fallback."); var shared = new List { Placement(0, [0, 1, 2]), Placement(2, [0, 1, 2]), Placement(4, [0, 1, 2]) }; - Check(Solve(shared, 3).BestScore == 9, "Default planning must include every compatible miner and count shared nodes per miner."); - // Explicit limits remain supported for replaying older stock-limited snapshots. - Check(Solve(shared, 3, 1).BestScore == 3, "An explicit one-miner limit must still be replayable."); - Check(Solve(shared, 3, 0).Best.Count == 0, "An explicit zero limit must still be replayable."); + Check(Solve(shared, 3).BestScore == 9, "Planning must include every compatible miner and count shared nodes per miner."); if (MinerPlacementSolver.WorkerCount > 0) { var oneWorker = new MinerPlacementSolver(shared, 3); - oneWorker.SearchAsync(int.MaxValue, 12, CancellationToken.None, 1).GetAwaiter().GetResult(); + oneWorker.SearchAsync(12, CancellationToken.None, 1).GetAwaiter().GetResult(); Check(oneWorker.BestScore == 9, "A two-logical-processor machine must work with just one background worker."); } var dense = new List { Placement(0, [0, 1, 2, 3, 4], halfWidth: 1.1f), Placement(-1.4f, [0, 1, 2]), Placement(1.4f, [2, 3, 4]) }; - Check(Solve(dense, 5).BestScore == 6, "Default planning must prefer two smaller miners regardless of carried stock."); - Check(Solve(dense, 5, 1).BestScore == 5, "An older one-miner limit must preserve its different optimal layout."); + Check(Solve(dense, 5).BestScore == 6, "Planning must prefer two smaller miners regardless of carried stock."); var costlyBurial = new List { Placement(0, [0, 1, 2]), Placement(2, [0, 1, 2]), Placement(4, [1, 2, 3], [0]) }; - Check(Solve(costlyBurial, 4, 3).BestScore == 6, "A higher total must not justify reducing existing miners from three nodes to two."); - Check(Solve(costlyBurial, 4, 3).Best.All(c => c.Buried.Length == 0), "Keep the valid burial-free layout."); + Check(Solve(costlyBurial, 4).BestScore == 6, "A higher total must not justify reducing existing miners from three nodes to two."); + Check(Solve(costlyBurial, 4).Best.All(c => c.Buried.Length == 0), "Keep the valid burial-free layout."); var goodBurial = new List { Placement(0, [0, 1, 2, 3]), Placement(2, [1, 2, 3, 4], [0]) }; - Check(Solve(goodBurial, 5, 2).BestScore == 7, "A beneficial burial must remain possible when every miner retains three nodes."); + Check(Solve(goodBurial, 5).BestScore == 7, "A beneficial burial must remain possible when every miner retains three nodes."); var lowAfterBurial = new List { Placement(0, [0, 1, 2]), Placement(2, [3, 4, 5, 6], [0]) }; - Check(Solve(lowAfterBurial, 7, 2).Best.Count == 1, "Replace a miner instead of leaving it with only two nodes."); + Check(Solve(lowAfterBurial, 7).Best.Count == 1, "Replace a miner instead of leaving it with only two nodes."); var manyNodes = new List { Placement(0, [0, 64, 100, 129]), Placement(2, [0, 100, 129], [64]) }; - Check(Solve(manyNodes, 130, 2).BestScore == 6, "Coverage and burial must support groups larger than 64 nodes."); + Check(Solve(manyNodes, 130).BestScore == 6, "Coverage and burial must support groups larger than 64 nodes."); var manyMiners = Enumerable.Range(0, 65).Select(index => Placement(index * 2, [0, 1, 2])).ToList(); Check(Solve(manyMiners, 3).BestScore == 195, "The collision cache must support more than 64 selected miners."); - Check(Solve([], 5, 10).BestScore == 0, "An obstructed patch should produce an empty plan."); - Check(Solve([Placement(0, [0]), Placement(2, [0, 1])], 2, 20).Best.Count == 0, + Check(Solve([], 5).BestScore == 0, "An obstructed patch should produce an empty plan."); + Check(Solve([Placement(0, [0]), Placement(2, [0, 1])], 2).Best.Count == 0, "One- and two-node miners must be invalid even when stock is abundant."); var valid = Placement(4, [0, 1, 2]); - Check(Solve([Placement(0, [0]), Placement(2, [0, 1]), valid], 3, 20).Best.SequenceEqual([valid]), + Check(Solve([Placement(0, [0]), Placement(2, [0, 1]), valid], 3).Best.SequenceEqual([valid]), "Do not append marginal miners to an otherwise valid layout."); var burialCycle = new List { Placement(0, [0, 1, 2], [6]), Placement(2, [3, 4, 5], [0]), Placement(4, [6, 7, 8], [3]) }; - Check(Solve(burialCycle, 9, 20).BestScore == 3, + Check(Solve(burialCycle, 9).BestScore == 3, "Reject cyclic burials that would repeatedly invalidate an earlier miner."); // Three columns all block three alternative rows. Duplicated high-scoring column @@ -141,7 +133,7 @@ internal static class QuickMinerPlacementTests var coordinated = Enumerable.Range(0, 96).Select(_ => Bar(-2, 0, 0.4f, 4, 9)).ToList(); coordinated.AddRange([Bar(0, 0, 0.4f, 4, 6), Bar(2, 0, 0.4f, 4, 6)]); coordinated.AddRange([Bar(0, -2, 4, 0.4f, 8), Bar(0, 0, 4, 0.4f, 8), Bar(0, 2, 4, 0.4f, 8)]); - Check(Solve(coordinated, 9, 3).BestScore == 24, "Must repack all three miners together to escape the 21-point layout."); + Check(Solve(coordinated, 9).BestScore == 24, "Must repack all three miners together to escape the 21-point layout."); // Four columns block all four better rows, beyond the three-miner repair radius. // Repeated poses must not bias every exploratory pass toward the strongest column. @@ -163,7 +155,7 @@ internal static class QuickMinerPlacementTests var sharedBurial = new List { Placement(-4, Enumerable.Range(0, 8).ToArray()) }; sharedBurial.AddRange([Placement(0, [8, 9, 10, 11, 12], [0, 1, 2, 3, 4, 5, 6, 7]), Placement(2, [8, 9, 10, 11, 12], [0, 1, 2, 3, 4, 5, 6, 7])]); - Check(Solve(sharedBurial, 13, 3).BestScore == 10, "Joint search must replace the invalidated miner and charge shared burial only once."); + Check(Solve(sharedBurial, 13).BestScore == 10, "Joint search must replace the invalidated miner and charge shared burial only once."); } private static bool CornerOracle(ColliderData a, ColliderData b) @@ -289,7 +281,7 @@ internal static class QuickMinerPlacementTests if (beforeStart) cancellation.Cancel(); else cancellation.CancelAfter(10); var solver = new MinerPlacementSolver(candidates, 3); - var work = solver.SearchAsync(int.MaxValue, 64, cancellation.Token); + var work = solver.SearchAsync(64, cancellation.Token); try { work.GetAwaiter().GetResult(); @@ -328,9 +320,9 @@ internal static class QuickMinerPlacementTests }).ToArray(), candidates = Enumerable.Repeat(record, 4000).ToArray(), buildColliders = colliders.Take(3).ToArray(), minerColliders = colliders, obstacles = [], existingMiners = [new MinerPlacementDebug.ExistingMiner { entityId = 2, minerId = 0, prebuild = true, position = record.position, rotation = record.rotation, veins = [1, 2, 3] }], - phases = [new MinerPlacementDebug.Phase { name = "roundtrip", candidateCount = 4000, limit = int.MaxValue, passes = 2, score = 3, elapsedMilliseconds = 1, searchMilliseconds = 1, selected = [0] }], + phases = [new MinerPlacementDebug.Phase { name = "roundtrip", candidateCount = 4000, passes = 2, score = 3, elapsedMilliseconds = 1, searchMilliseconds = 1, selected = [0] }], placements = [new MinerPlacementDebug.Placement { candidate = 0, prebuildId = 1, coverObjectId = 0, itemRequired = 1, outcome = "placed", nativeCondition = "Ok", nativeVeins = [1, 2, 3], plannedVeins = [1, 2, 3], finalVeins = [1, 2, 3] }], - rejections = new MinerPlacementDebug.Rejections { attempted = 1, range = 0, mixedType = 0, noCoverage = 0, veinCollision = 0, buildingCollision = 0, ground = 0 } + rejections = new MinerPlacementDebug.Rejections { attempted = 1, range = 0, clearance = 0, mixedType = 0, noCoverage = 0, veinCollision = 0, buildingCollision = 0, ground = 0 } }; var path = Path.Combine(AppContext.BaseDirectory, "replay-smoke.json"); MinerPlacementDebug.Write(path, snapshot); @@ -341,9 +333,9 @@ internal static class QuickMinerPlacementTests document.RootElement.GetProperty("buildColliders").GetArrayLength() == 3, "The production writer must serialize internal nested records, not just summary fields."); var roundtrip = JsonSerializer.Deserialize(snapshotJson, ReplayJson); - Check(roundtrip.schema == 2 && roundtrip.minimumCoverage == 3 && roundtrip.existingMiners[0].prebuild && + Check(roundtrip.schema == 3 && roundtrip.minimumCoverage == 3 && roundtrip.existingMiners[0].prebuild && roundtrip.workerCount <= roundtrip.logicalProcessors / 2 && roundtrip.phases[0].searchMilliseconds == 1 && - roundtrip.initialStock == 0 && roundtrip.phases[0].limit == int.MaxValue && roundtrip.placements[0].itemRequired == 1 && + roundtrip.initialStock == 0 && roundtrip.placements[0].itemRequired == 1 && roundtrip.placements[0].plannedVeins.Length == 3 && roundtrip.placements[0].finalVeins[0] == 1 && roundtrip.rejections.attempted == 1, "Replay schema must retain existing miners, native placements and rejection counters."); Replay(path); @@ -352,6 +344,7 @@ internal static class QuickMinerPlacementTests private static void Replay(string path, int minimumTotalCoverage = 0) { var snapshot = JsonSerializer.Deserialize(File.ReadAllText(path), ReplayJson); + // Schema 2 snapshots also recorded a stock limit, which the current search does not use. Check(snapshot.schema is 1 or 2 or 3, "Unsupported debug snapshot schema."); Check(snapshot.nodes != null && snapshot.candidates != null && snapshot.buildColliders != null && snapshot.minerColliders != null && snapshot.phases != null, "This snapshot contains summary data only and cannot be replayed. Run quick miner placement again with the updated build."); @@ -365,26 +358,20 @@ internal static class QuickMinerPlacementTests { while (candidates.Count < phase.candidateCount) candidates.Add(snapshot.candidates[candidates.Count].Restore(snapshot.buildColliders, snapshot.minerColliders)); - if (phase.name == "stock-changed") - { - solver = new MinerPlacementSolver(candidates, snapshot.nodes.Length); - parallel = new MinerPlacementSolver(candidates, snapshot.nodes.Length); - } var timer = Stopwatch.StartNew(); - var search = phase.limit == int.MaxValue ? solver.Search(phase.passes) : solver.Search(phase.limit, phase.passes); + var search = solver.Search(phase.passes); while (search.MoveNext()) { } var sequentialMilliseconds = timer.ElapsedMilliseconds; long parallelMilliseconds = 0; if (MinerPlacementSolver.WorkerCount > 0) { timer.Restart(); - parallel.SearchAsync(phase.limit, phase.passes, CancellationToken.None).GetAwaiter().GetResult(); + parallel.SearchAsync(phase.passes, CancellationToken.None).GetAwaiter().GetResult(); parallelMilliseconds = timer.ElapsedMilliseconds; Check(parallel.BestScore == solver.BestScore && parallel.Best.SequenceEqual(solver.Best), "Recorded multi-stage replay must select the exact same layout on the worker pool."); } var buried = solver.Best.SelectMany(c => c.Buried).ToHashSet(); - Check(solver.Best.Count <= phase.limit, "Replay exceeded the recorded placement limit."); Check(solver.BestScore == solver.Best.Sum(c => c.Covered.Count(n => !buried.Contains(n))), "Replay score differs from summed coverage after burial."); for (var i = 0; i < solver.Best.Count; i++) {