diff --git a/UXAssist/CHANGELOG.md b/UXAssist/CHANGELOG.md index 95e6347..c250f6b 100644 --- a/UXAssist/CHANGELOG.md +++ b/UXAssist/CHANGELOG.md @@ -4,7 +4,7 @@ ## Changlog * 1.6.3 - Unreleased - * `Quick build Mining Machines`: Add a Factory-tab button that restores available buried nodes at the nearest solid vein group and searches dense layouts using native collision shapes, including interleaving feet and joint placement of nearby miners. Optimizes summed vein coverage, requires at least 3 covered nodes per miner after burial, may bury unused nodes, and places the full ordinary miner layout regardless of stock, leaving ghosts awaiting missing materials. Accelerates layout searches with up to 4 background workers, capped at half the available logical processors. Writes replayable JSON snapshots during feature tuning and keeps the completion tip visible for about 8 seconds. + * `Quick build Mining Machines`: Add a Factory-tab button that restores available buried nodes at the nearest solid vein group and searches dense layouts using native collision shapes, including interleaving feet, joint placement of nearby miners, and a final pass to fill remaining compatible positions. Optimizes summed vein coverage, requires at least 3 covered nodes per miner after burial, may bury unused nodes, and places the full ordinary miner layout regardless of stock, leaving ghosts awaiting missing materials. Accelerates layout searches with up to 4 background workers, capped at half the available logical processors. Writes replayable JSON snapshots during feature tuning and keeps the completion tip visible for about 8 seconds. * 1.6.2 * `Increase maximum power usage in Logistic Stations and Advanced Mining Machines`: Fix zero or corrupted mining speeds when adjusting an Advanced Mining Machine's speed slider with the option enabled. * `Tweak building buffers`: Restore the Ray Receiver Graviton Lens buffer setting on DSP 0.10.35.29104 and later, and correct the displayed native buffer value to 2. @@ -437,7 +437,7 @@ ## 更新日志 * 1.6.3 - Unreleased - * `快速铺设采矿机`:在「工厂」页增加按钮,还原最近固体矿脉中可还原的掩埋矿点,并按游戏实际碰撞体搜索密集布局,支持脚部交错和邻近矿机联动调整。以各台矿机覆盖矿点数之和为目标,要求每台在掩埋后仍覆盖至少 3 个矿点,允许掩埋未被使用的矿点,不受库存限制地生成完整布局,缺少采矿机的位置保留待建造虚影。使用最多 4 个后台线程加速布局搜索,线程数不超过可用逻辑线程数的一半。功能调试期间输出可离线重放的 JSON 数据,完成提示保留约 8 秒。 + * `快速铺设采矿机`:在「工厂」页增加按钮,还原最近固体矿脉中可还原的掩埋矿点,并按游戏实际碰撞体搜索密集布局,支持脚部交错、邻近矿机联动调整及结束前补入剩余可用位置。以各台矿机覆盖矿点数之和为目标,要求每台在掩埋后仍覆盖至少 3 个矿点,允许掩埋未被使用的矿点,不受库存限制地生成完整布局,缺少采矿机的位置保留待建造虚影。使用最多 4 个后台线程加速布局搜索,线程数不超过可用逻辑线程数的一半。功能调试期间输出可离线重放的 JSON 数据,完成提示保留约 8 秒。 * 1.6.2 * `提升物流塔和大型采矿机的最大功耗`:修复启用后调整大型采矿机开采速度时出现 0% 或异常速度的问题。 * `调整建筑输入缓冲`:修复 DSP 0.10.35.29104 及后续版本中射线接收器透镜缓冲设置不生效的问题,并将显示的游戏原始值更正为 2。 diff --git a/UXAssist/Functions/Factory/MinerPlacementDebug.cs b/UXAssist/Functions/Factory/MinerPlacementDebug.cs index c9dd7a1..cf3e188 100644 --- a/UXAssist/Functions/Factory/MinerPlacementDebug.cs +++ b/UXAssist/Functions/Factory/MinerPlacementDebug.cs @@ -15,7 +15,7 @@ internal static class MinerPlacementDebug internal sealed class Snapshot { public int schema = 2; - public string algorithm = "parallel-repack-v3-min3-unlimited-stock"; + public string algorithm = "parallel-repack-v5-pose-exploration-min3-unlimited-stock"; public int minimumCoverage = MinerPlacementSolver.MinimumCoverage; public string version, gameVersion, startedUtc, outcome, error; public int planetId, veinType, veinGroup, initialStock, placedCount, totalCoverage, buriedCount; @@ -104,7 +104,9 @@ internal static class MinerPlacementDebug internal sealed class Phase { public string name; - public int candidateCount, limit, passes, score; + 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; } diff --git a/UXAssist/Functions/Factory/MinerPlacementSolver.cs b/UXAssist/Functions/Factory/MinerPlacementSolver.cs index 267322e..f3cd981 100644 --- a/UXAssist/Functions/Factory/MinerPlacementSolver.cs +++ b/UXAssist/Functions/Factory/MinerPlacementSolver.cs @@ -56,6 +56,20 @@ internal sealed class MinerPlacementSolver var work = RunBatch(passes, pass => GreedyPass(limit, pass, null, 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 + // get extra lottery tickets with index-based jitter. Keep the existing starts and + // add pose-based starts whose priorities survive filtering and duplicate candidates. + var keys = new uint[_candidates.Count]; + for (var i = 0; i < keys.Length; i++) + { + 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); @@ -63,9 +77,25 @@ internal sealed class MinerPlacementSolver foreach (var result in results) Accept(result); var repair = Repack(limit, workers, cancellationToken); while (repair.MoveNext()) yield return null; + // 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); + while (work.MoveNext()) yield return null; + Accept(refill[0]); } - private IEnumerator GreedyPass(int limit, int pass, List seeds, SearchResult[] results, int resultIndex, CancellationToken cancellationToken) + private static uint PoseKey(Candidate candidate) + { + // Quantize only the exploration key, never the geometry or collision tests. + var x = (int)Math.Round(candidate.X * 1000f); + var z = (int)Math.Round(candidate.Z * 1000f); + var yaw = (int)Math.Round(((candidate.Yaw % 360f + 360f) % 360f) * 10f); + 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) { var selected = new List(); var buried = new bool[_nodeCount]; @@ -73,7 +103,7 @@ internal sealed class MinerPlacementSolver var score = 0; if (seeds != null) for (var i = 0; i < seeds.Count && selected.Count < limit; i++) - if (i != resultIndex) Add(seeds[i], selected, buried, uses, ref score); + if (keepAllSeeds || i != resultIndex) Add(seeds[i], selected, buried, uses, ref score); while (selected.Count < limit) { Candidate chosen = null; @@ -86,12 +116,13 @@ internal sealed class MinerPlacementSolver yield return null; } var candidate = _candidates[i]; - if (seeds != null && ReferenceEquals(candidate, seeds[resultIndex])) continue; + 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 = unchecked((uint)((i + 1) * 73856093 ^ (pass + 1) * 19349663 ^ (selected.Count + 1) * 83492791)); + 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; diff --git a/UXAssist/README.md b/UXAssist/README.md index ae84aee..51dc40d 100644 --- a/UXAssist/README.md +++ b/UXAssist/README.md @@ -84,11 +84,11 @@ * 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. - * Uses multiple packing orders, 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. Shared nodes count once per miner; this bounded search does not guarantee a global optimum. + * 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. * 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. + * 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 * 6 belt signals are added to the signal panel, which can be used to buy out dark fog items automatically. * Generated items are stacked in 4 items. @@ -284,11 +284,11 @@ * 快速铺设采矿机 * 点击「工厂」页中轨道采集器按钮附近的按钮,在最近的固体矿脉生成完整的普通采矿机布局,数量不受库存限制。有采矿机时正常消耗背包和手持物品,不足的位置保留待建造虚影,等待补充材料。所有计划掩埋完成后,每台矿机仍须覆盖至少 3 个矿点;少于 3 个的视为无效,不予铺设。 * 先还原未被建筑阻挡的掩埋矿点,再按原版独立碰撞体搜索布局,保留游戏允许的矿机脚部交叉空间。 - * 比较多种铺设顺序,细调位置和朝向,按机身宽度补充紧邻候选,并允许邻近的两三台矿机一起重新布局,尽量提高各台矿机覆盖矿点数之和;同一矿点被多台矿机覆盖时重复计数。计算有界,不保证全局最优。 + * 比较多种铺设顺序,同时按候选序号及位置朝向探索不同布局,细调位置和朝向,按机身宽度补充紧邻候选,并允许邻近的两三台矿机一起重新布局,尽量提高各台矿机覆盖矿点数之和。结束前再扫描全部候选,继续补入能提高总覆盖数、且不破坏每台至少覆盖 3 点要求的矿机。同一矿点被多台矿机覆盖时重复计数。计算有界,不保证全局最优。 * 复用碰撞检查结果,使用最多 4 个后台线程并行搜索独立布局,线程数不超过可用逻辑线程数的一半。单逻辑线程系统继续在主线程按每帧预算计算。原生地形检查和实际铺设保留在主线程;并行调度与顺序搜索生成相同布局。 * 允许掩埋未被使用的矿点来提高总覆盖数;保护已有矿机及待建造矿机使用的矿点。仍需满足地面、水面、现有建筑和建造范围要求。 * 计算期间再次点击可取消,切换行星或退出游戏自动取消。待建造对象由建设机器人完成,不自动铺设传送带和电力设施。 - * 功能调试期间,每次计算都会在当前游戏配置目录的 `BepInEx/debug/UXAssist/QuickMiner/` 下写入带时间戳的 JSON 文件,记录矿点、原生碰撞体、有效候选、搜索阶段及其搜索耗时、逻辑线程数和工作线程数、现有矿机和原生铺设校验结果。完成提示保留约 8 秒,日志也会记录结果摘要和文件的完整路径。在仓库根目录运行 `powershell -File tools/tests/Test-QuickMinerPlacement.ps1 -Snapshot `,即可离线重放并比较顺序与并行搜索结果,无需读取存档。 + * 功能调试期间,每次计算都会在当前游戏配置目录的 `BepInEx/debug/UXAssist/QuickMiner/` 下写入带时间戳的 JSON 文件,记录矿点、原生碰撞体、有效候选、搜索阶段及其搜索耗时、逻辑线程数和工作线程数、现有矿机和原生铺设校验结果。完成提示保留约 8 秒,日志也会记录结果摘要和文件的完整路径。在仓库根目录运行 `powershell -File tools/tests/Test-QuickMinerPlacement.ps1 -Snapshot `,即可离线重放并比较顺序与并行搜索结果,无需读取存档。总覆盖数低于记录结果时,重放检查会失败;可追加 `-MinimumTotalCoverage <数量>`,要求达到更高的总覆盖数。 * 用于自动购买黑雾物品的传送带信号 * 在信号面板上添加了6个传送带信号,可以用于自动购买黑雾道具。 * 生成的物品堆叠数为4。 diff --git a/tools/tests/QuickMinerPlacementTests.cs b/tools/tests/QuickMinerPlacementTests.cs index 8b88723..1cd7293 100644 --- a/tools/tests/QuickMinerPlacementTests.cs +++ b/tools/tests/QuickMinerPlacementTests.cs @@ -40,16 +40,16 @@ 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) + private static MinerPlacementSolver Solve(List candidates, int nodes, int? limit = null, int passes = 12) { var solver = new MinerPlacementSolver(candidates, nodes); - var search = limit.HasValue ? solver.Search(limit.Value, 12) : solver.Search(12); + var search = limit.HasValue ? solver.Search(limit.Value, passes) : 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, 12, CancellationToken.None).GetAwaiter().GetResult(); + parallel.SearchAsync(limit ?? int.MaxValue, 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."); } @@ -63,6 +63,17 @@ 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 => + { + 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; } @@ -132,6 +143,22 @@ internal static class QuickMinerPlacementTests 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."); + // 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. + var duplicated = Enumerable.Range(0, 96).Select(_ => Bar(-3, 0, 0.4f, 5, 9)).ToList(); + duplicated.AddRange([Bar(-1, 0, 0.4f, 5, 6), Bar(1, 0, 0.4f, 5, 6), Bar(3, 0, 0.4f, 5, 6)]); + duplicated.AddRange([Bar(0, -3, 5, 0.4f, 8), Bar(0, -1, 5, 0.4f, 8), Bar(0, 1, 5, 0.4f, 8), Bar(0, 3, 5, 0.4f, 8)]); + Check(Solve(duplicated, 9).BestScore == 32, "Pose-based starts must escape the duplicated 27-point column layout."); + duplicated.InsertRange(0, Enumerable.Range(0, 4).Select(index => Placement(100 + index * 2, [0]))); + Check(Solve(duplicated, 9).BestScore == 32, "Filtering unrelated invalid poses must not destroy the better exploration path."); + + // Local repacking can free a distant spot outside every six-meter neighborhood. + // The final layout must refill that spot instead of stopping after a local repair. + var refill = Enumerable.Range(0, 96).Select(_ => Bar(0, 0, 12, 0.4f, 200)).ToList(); + refill.AddRange([Placement(-2, Enumerable.Range(0, 100).ToArray()), Placement(0, Enumerable.Range(0, 100).ToArray()), + Placement(2, Enumerable.Range(0, 100).ToArray()), Placement(10, [100, 101, 102])]); + Check(Solve(refill, 200, passes: 2).BestScore == 303, "Refill a valid miner outside the repacked neighborhood after freeing its footprint."); + // A burial can be individually harmful but worthwhile when two replacements share it. 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]), @@ -322,10 +349,10 @@ internal static class QuickMinerPlacementTests Replay(path); } - private static void Replay(string path) + private static void Replay(string path, int minimumTotalCoverage = 0) { var snapshot = JsonSerializer.Deserialize(File.ReadAllText(path), ReplayJson); - Check(snapshot.schema is 1 or 2, "Unsupported debug snapshot schema."); + 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."); Console.WriteLine($"Snapshot: outcome={snapshot.outcome}, nodes={snapshot.nodes.Length}, candidates={snapshot.candidates.Length}, placed={snapshot.placedCount}, actual coverage={snapshot.totalCoverage}"); @@ -367,11 +394,13 @@ internal static class QuickMinerPlacementTests } Console.WriteLine($"Replay {phase.name}: recorded={phase.score}, current={solver.BestScore}, miners={solver.Best.Count}, candidates={candidates.Count}, sequential={sequentialMilliseconds}ms, workers={MinerPlacementSolver.WorkerCount}, parallel={parallelMilliseconds}ms"); } + Check(solver.BestScore >= Math.Max(snapshot.totalCoverage, minimumTotalCoverage), + $"Replay reduced total coverage: recorded={snapshot.totalCoverage}, required={minimumTotalCoverage}, current={solver.BestScore}."); } public static void Main(string[] args) { - if (args.Length > 0) { Replay(args[0]); return; } + if (args.Length > 0) { Replay(args[0], args.Length > 1 ? int.Parse(args[1]) : 0); return; } GeometryChecks(); SolverChecks(); CancellationChecks(); diff --git a/tools/tests/Test-QuickMinerPlacement.ps1 b/tools/tests/Test-QuickMinerPlacement.ps1 index e7f9ea2..069e434 100644 --- a/tools/tests/Test-QuickMinerPlacement.ps1 +++ b/tools/tests/Test-QuickMinerPlacement.ps1 @@ -1,7 +1,7 @@ #requires -Version 5.1 # Runs the production geometry and solver against the original game assemblies, without Unity. [CmdletBinding()] -param([string]$GameRoot, [string]$Snapshot) +param([string]$GameRoot, [string]$Snapshot, [ValidateRange(0, 2147483647)][int]$MinimumTotalCoverage = 0) Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' @@ -56,7 +56,7 @@ Set-Content -LiteralPath $project -Encoding UTF8 -Value @" "@ if ($Snapshot) { $snapshotPath = (Resolve-Path -LiteralPath $Snapshot).Path - & dotnet run --project $project -c Release -- $snapshotPath + & dotnet run --project $project -c Release -- $snapshotPath $MinimumTotalCoverage } else { & dotnet run --project $project -c Release }