diff --git a/UXAssist/CHANGELOG.md b/UXAssist/CHANGELOG.md index 1d5e197..95e6347 100644 --- a/UXAssist/CHANGELOG.md +++ b/UXAssist/CHANGELOG.md @@ -3,6 +3,8 @@ ## 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. * 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. @@ -434,6 +436,8 @@ ## 更新日志 +* 1.6.3 - Unreleased + * `快速铺设采矿机`:在「工厂」页增加按钮,还原最近固体矿脉中可还原的掩埋矿点,并按游戏实际碰撞体搜索密集布局,支持脚部交错和邻近矿机联动调整。以各台矿机覆盖矿点数之和为目标,要求每台在掩埋后仍覆盖至少 3 个矿点,允许掩埋未被使用的矿点,不受库存限制地生成完整布局,缺少采矿机的位置保留待建造虚影。使用最多 4 个后台线程加速布局搜索,线程数不超过可用逻辑线程数的一半。功能调试期间输出可离线重放的 JSON 数据,完成提示保留约 8 秒。 * 1.6.2 * `提升物流塔和大型采矿机的最大功耗`:修复启用后调整大型采矿机开采速度时出现 0% 或异常速度的问题。 * `调整建筑输入缓冲`:修复 DSP 0.10.35.29104 及后续版本中射线接收器透镜缓冲设置不生效的问题,并将显示的游戏原始值更正为 2。 diff --git a/UXAssist/Common/GameConstants/ItemIds.cs b/UXAssist/Common/GameConstants/ItemIds.cs index fa239b1..038f68a 100644 --- a/UXAssist/Common/GameConstants/ItemIds.cs +++ b/UXAssist/Common/GameConstants/ItemIds.cs @@ -63,6 +63,9 @@ public static class ItemIds /* Power generators */ public const int WindTurbine = 2203; + /* Mining */ + public const int MiningMachine = 2301; + /* Dark Fog items (combat expansion) */ public const int DarkFogMemoryUnit = 5201; public const int DarkFogSiliconNeuron = 5202; diff --git a/UXAssist/Common/I18NKeys.cs b/UXAssist/Common/I18NKeys.cs index 270b5e6..20edfd4 100644 --- a/UXAssist/Common/I18NKeys.cs +++ b/UXAssist/Common/I18NKeys.cs @@ -172,6 +172,19 @@ public static class I18NKeys public const string DismantleAllBuildings = "Dismantle All Buildings"; public const string DismantleAllBuildingsConfirm = "Dismantle All Buildings Confirm"; public const string QuickBuildOrbitalCollectors = "Quick build Orbital Collectors"; + public const string QuickBuildMiningMachines = "Quick build Mining Machines"; + public const string QuickBuildMiningMachinesTips = "Quick build Mining Machines tips"; + public const string QuickMinerCancelSearch = "Cancel miner layout search"; + public const string QuickMinerSearching = "Searching for a dense miner layout"; + public const string QuickMinerCancelled = "Miner layout search cancelled"; + public const string QuickMinerNeedPlanet = "Land on a rocky planet to place miners"; + public const string QuickMinerNoVeins = "No mineable vein group on this planet"; + public const string QuickMinerNoPlacement = "No valid miner placements; move closer and check available land"; + public const string QuickMinerFailed = "Miner placement stopped; check the log before retrying"; + public const string QuickMinerVeinsChanged = "Veins changed during miner layout search"; + public const string QuickMinerResult = "Placed {0} Mining Machines, {1} total vein coverage, {2} buried nodes"; + public const string QuickMinerDebugSaved = "Miner layout debug data: {0}"; + public const string QuickMinerDebugFailed = "Could not save miner layout debug data"; public const string MaximumCountToBuild = "Maximum count to build"; public const string Max = "max"; public const string StopEjectorsWhenAvailableNodesAreAllFilledUp = "Stop ejectors when available nodes are all filled up"; @@ -435,6 +448,19 @@ You can set 2 shortcut keys in Settings panel: I18N.Add(DismantleAllBuildings, "Dismantle all buildings", "拆除所有建筑"); 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(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", "已取消采矿机布局计算"); + I18N.Add(QuickMinerNeedPlanet, "Land on a rocky planet to place miners.", "请降落到有固体矿脉的行星后再铺设采矿机。"); + I18N.Add(QuickMinerNoVeins, "No mineable solid vein group on this planet.", "本行星没有可开采的固体矿脉。"); + I18N.Add(QuickMinerNoPlacement, "No valid miner placements with at least 3 nodes each. Move closer to the nearest vein group and check for buildings or water, then try again.", "没有满足每台至少覆盖 3 个矿点的有效位置,请靠近最近的矿脉,并检查建筑和水面阻挡后重试。"); + I18N.Add(QuickMinerFailed, "Miner placement stopped. Check the UXAssist log before retrying.", "采矿机铺设已停止,请查看 UXAssist 日志后重试。"); + I18N.Add(QuickMinerVeinsChanged, "The veins changed during calculation. Click the button again to recalculate the layout.", "计算期间矿点状态已变化,请再次点击按钮重新计算布局。"); + I18N.Add(QuickMinerResult, "Placed {0} Mining Machines; total vein coverage: {1} (shared nodes counted per miner); buried nodes: {2}.", "已铺设 {0} 台采矿机,总覆盖 {1} 个矿点(各台分别计数),掩埋 {2} 个矿点。"); + I18N.Add(QuickMinerDebugSaved, "Debug data: {0}", "调试数据:{0}"); + I18N.Add(QuickMinerDebugFailed, "Could not save debug data. Check the UXAssist log before retrying.", "调试数据保存失败,请查看 UXAssist 日志后重试。"); I18N.Add(MaximumCountToBuild, "Maximum count to build", "最大建造数量"); I18N.Add(Max, "max", "最大"); I18N.Add(StopEjectorsWhenAvailableNodesAreAllFilledUp, "Stop ejectors when available nodes are all filled up", "可用节点全部造完时停止弹射"); diff --git a/UXAssist/Functions/Factory/MinerPlacementDebug.cs b/UXAssist/Functions/Factory/MinerPlacementDebug.cs new file mode 100644 index 0000000..c9dd7a1 --- /dev/null +++ b/UXAssist/Functions/Factory/MinerPlacementDebug.cs @@ -0,0 +1,138 @@ +using System; +using System.IO; +using System.Runtime.Serialization.Json; +using UnityEngine; +using Box = UXAssist.Functions.Factory.MinerPlacementGeometry.Box; +using Candidate = UXAssist.Functions.Factory.MinerPlacementSolver.Candidate; + +namespace UXAssist.Functions.Factory; + +// Use the same serializer in game and offline checks. Unity's JsonUtility omits fields whose +// types are internal, including arrays of these nested records, without reporting an error. +internal static class MinerPlacementDebug +{ + [Serializable] + internal sealed class Snapshot + { + public int schema = 2; + public string algorithm = "parallel-repack-v3-min3-unlimited-stock"; + public int minimumCoverage = MinerPlacementSolver.MinimumCoverage; + public string version, gameVersion, startedUtc, outcome, error; + public int planetId, veinType, veinGroup, initialStock, placedCount, totalCoverage, buriedCount; + public int logicalProcessors, workerCount; + public float planetRadius, buildRange; + public bool unlimitedRange; + public long elapsedMilliseconds; + public float[] playerPosition, center, right, forward; + public Node[] nodes; + public Collider[] buildColliders, minerColliders, obstacles; + public ExistingMiner[] existingMiners; + public CandidateData[] candidates; + public Phase[] phases; + public Placement[] placements; + public Rejections rejections = new(); + } + + [Serializable] + internal sealed class Node + { + public int id, type; + public bool target, visible, canBury; + public float[] originalPosition, position; + public Collider collider; + } + + [Serializable] + internal sealed class Collider + { + public int idType, link; + public float[] position, extents, rotation; + public float radius; + + public static Collider Capture(ColliderData value) => new() + { + idType = value.idType, link = value.link, position = Vector(value.pos), + extents = Vector(value.ext), rotation = Rotation(value.q), radius = value.radius + }; + + public ColliderData Restore() => new() + { + idType = idType, link = link, pos = ReadVector(position), ext = ReadVector(extents), + q = ReadRotation(rotation), radius = radius + }; + } + + [Serializable] + internal sealed class ExistingMiner + { + public int entityId, minerId; + public bool prebuild; + public float[] position, rotation; + public int[] veins; + } + + [Serializable] + internal sealed class CandidateData + { + public float x, z, yaw, radius; + public float[] position, rotation; + public int[] covered, buried; + + public static CandidateData Capture(Candidate value) => new() + { + x = value.X, z = value.Z, yaw = value.Yaw, radius = value.Radius, + position = Vector(value.Position), rotation = Rotation(value.Rotation), + covered = value.Covered, buried = value.Buried + }; + + public Candidate Restore(Collider[] build, Collider[] obstacles) + { + var result = new Candidate + { + X = x, Z = z, Yaw = yaw, Radius = radius, Position = ReadVector(position), Rotation = ReadRotation(rotation), + Covered = covered, Buried = buried, BuildBoxes = new Box[build.Length], ObstacleBoxes = new Box[obstacles.Length] + }; + for (var i = 0; i < build.Length; i++) + result.BuildBoxes[i] = new Box(build[i].Restore().BindToObject(0, 0, EObjectType.None, result.Position, result.Rotation)); + for (var i = 0; i < obstacles.Length; i++) + result.ObstacleBoxes[i] = new Box(obstacles[i].Restore().BindToObject(0, 0, EObjectType.None, result.Position, result.Rotation)); + return result; + } + } + + [Serializable] + internal sealed class Phase + { + public string name; + public int candidateCount, limit, passes, score; + public long elapsedMilliseconds, searchMilliseconds; + public int[] selected; + } + + [Serializable] + internal sealed class Placement + { + public int candidate, prebuildId, coverObjectId, itemRequired; + public string outcome, nativeCondition; + public int[] nativeVeins, plannedVeins, finalVeins; + } + + [Serializable] + internal sealed class Rejections + { + public int attempted, range, mixedType, noCoverage, veinCollision, buildingCollision, ground; + } + + public static float[] Vector(Vector3 value) => [value.x, value.y, value.z]; + public static float[] Rotation(Quaternion value) => [value.x, value.y, value.z, value.w]; + + internal static void Write(string path, Snapshot snapshot) + { + using var stream = File.Create(path); + var serializer = new DataContractJsonSerializer(typeof(Snapshot), new DataContractJsonSerializerSettings { MaxItemsInObjectGraph = int.MaxValue }); + serializer.WriteObject(stream, snapshot); + } + + private static Vector3 ReadVector(float[] value) => new(value[0], value[1], value[2]); + private static Quaternion ReadRotation(float[] value) => new(value[0], value[1], value[2], value[3]); +} diff --git a/UXAssist/Functions/Factory/MinerPlacementGeometry.cs b/UXAssist/Functions/Factory/MinerPlacementGeometry.cs new file mode 100644 index 0000000..04e2b3b --- /dev/null +++ b/UXAssist/Functions/Factory/MinerPlacementGeometry.cs @@ -0,0 +1,124 @@ +using UnityEngine; + +namespace UXAssist.Functions.Factory; + +// Work with individual native colliders, never a bounding rectangle around the miner's feet. +internal static class MinerPlacementGeometry +{ + internal readonly struct Box + { + public readonly Vector3 Center, Extents, X, Y, Z, Bounds; + + public Box(ColliderData collider) + { + Center = collider.pos; + Extents = collider.ext; + X = collider.q * Vector3.right; + Y = collider.q * Vector3.up; + Z = collider.q * Vector3.forward; + Bounds = new Vector3( + Mathf.Abs(X.x) * Extents.x + Mathf.Abs(Y.x) * Extents.y + Mathf.Abs(Z.x) * Extents.z, + Mathf.Abs(X.y) * Extents.x + Mathf.Abs(Y.y) * Extents.y + Mathf.Abs(Z.y) * Extents.z, + Mathf.Abs(X.z) * Extents.x + Mathf.Abs(Y.z) * Extents.y + Mathf.Abs(Z.z) * Extents.z); + } + + public Vector3 ToLocal(Vector3 point) + { + var offset = point - Center; + return new Vector3(Vector3.Dot(offset, X), Vector3.Dot(offset, Y), Vector3.Dot(offset, Z)); + } + } + + public static bool Intersects(Box a, Box b) + { + var delta = b.Center - a.Center; + // Reject distant individual colliders before the full separating-axis test. This + // does not replace the independent foot colliders with one enclosing footprint. + if (Mathf.Abs(delta.x) > a.Bounds.x + b.Bounds.x + 0.00001f || + Mathf.Abs(delta.y) > a.Bounds.y + b.Bounds.y + 0.00001f || + Mathf.Abs(delta.z) > a.Bounds.z + b.Bounds.z + 0.00001f) return false; + if (Separated(a.X, delta, a, b) || Separated(a.Y, delta, a, b) || Separated(a.Z, delta, a, b) || + Separated(b.X, delta, a, b) || Separated(b.Y, delta, a, b) || Separated(b.Z, delta, a, b)) return false; + return !Separated(Vector3.Cross(a.X, b.X), delta, a, b) && + !Separated(Vector3.Cross(a.X, b.Y), delta, a, b) && + !Separated(Vector3.Cross(a.X, b.Z), delta, a, b) && + !Separated(Vector3.Cross(a.Y, b.X), delta, a, b) && + !Separated(Vector3.Cross(a.Y, b.Y), delta, a, b) && + !Separated(Vector3.Cross(a.Y, b.Z), delta, a, b) && + !Separated(Vector3.Cross(a.Z, b.X), delta, a, b) && + !Separated(Vector3.Cross(a.Z, b.Y), delta, a, b) && + !Separated(Vector3.Cross(a.Z, b.Z), delta, a, b); + } + + private static bool Separated(Vector3 axis, Vector3 delta, Box a, Box b) + { + if (axis.sqrMagnitude < 1e-10f) return false; + var radius = a.Extents.x * Mathf.Abs(Vector3.Dot(axis, a.X)) + + a.Extents.y * Mathf.Abs(Vector3.Dot(axis, a.Y)) + + a.Extents.z * Mathf.Abs(Vector3.Dot(axis, a.Z)) + + b.Extents.x * Mathf.Abs(Vector3.Dot(axis, b.X)) + + b.Extents.y * Mathf.Abs(Vector3.Dot(axis, b.Y)) + + b.Extents.z * Mathf.Abs(Vector3.Dot(axis, b.Z)); + return Mathf.Abs(Vector3.Dot(delta, axis)) > radius; + } + + public static bool Intersects(Box box, ColliderData collider) + { + switch (collider.shape) + { + case EColliderShape.Box: + return Intersects(box, new Box(collider)); + case EColliderShape.Sphere: + return PointDistanceSquared(box.ToLocal(collider.pos), box.Extents) <= collider.radius * collider.radius; + case EColliderShape.Capsule: + return SegmentDistanceSquared(box.ToLocal(collider.pos - collider.ext), + box.ToLocal(collider.pos + collider.ext), box.Extents) <= collider.radius * collider.radius; + default: + return true; + } + } + + private static float PointDistanceSquared(Vector3 p, Vector3 ext) + { + var x = Mathf.Max(0f, Mathf.Abs(p.x) - ext.x); + var y = Mathf.Max(0f, Mathf.Abs(p.y) - ext.y); + var z = Mathf.Max(0f, Mathf.Abs(p.z) - ext.z); + return x * x + y * y + z * z; + } + + // The distance is quadratic between the segment's crossings of the six box planes. + // Minimize each interval exactly, including zero-length segments and parallel axes. + internal static float SegmentDistanceSquared(Vector3 start, Vector3 end, Vector3 ext) + { + var direction = end - start; + var best = Mathf.Min(PointDistanceSquared(start, ext), PointDistanceSquared(end, ext)); + var t = 0f; + for (var interval = 0; interval < 7 && t < 1f; interval++) + { + var next = 1f; + for (var axis = 0; axis < 3; axis++) + { + var d = direction[axis]; + if (Mathf.Abs(d) < 1e-10f) continue; + var low = (-ext[axis] - start[axis]) / d; + var high = (ext[axis] - start[axis]) / d; + if (low > t && low < next) next = low; + if (high > t && high < next) next = high; + } + var midpoint = start + direction * ((t + next) * 0.5f); + var a = 0f; + var b = 0f; + for (var axis = 0; axis < 3; axis++) + { + if (Mathf.Abs(midpoint[axis]) <= ext[axis]) continue; + var boundary = midpoint[axis] < 0f ? -ext[axis] : ext[axis]; + a += direction[axis] * direction[axis]; + b += direction[axis] * (start[axis] - boundary); + } + var closest = a > 0f ? Mathf.Clamp(-b / a, t, next) : t; + best = Mathf.Min(best, PointDistanceSquared(start + direction * closest, ext)); + t = next; + } + return best; + } +} diff --git a/UXAssist/Functions/Factory/MinerPlacementSolver.cs b/UXAssist/Functions/Factory/MinerPlacementSolver.cs new file mode 100644 index 0000000..267322e --- /dev/null +++ b/UXAssist/Functions/Factory/MinerPlacementSolver.cs @@ -0,0 +1,438 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using UnityEngine; + +namespace UXAssist.Functions.Factory; + +internal sealed class MinerPlacementSolver +{ + internal const int MinimumCoverage = 3; + public static int WorkerCount => GetWorkerCount(Environment.ProcessorCount); + internal static int GetWorkerCount(int processors) => Math.Min(4, Math.Max(0, processors / 2)); + + internal sealed class Candidate + { + public float X, Z, Yaw, Radius; + public Vector3 Position; + public Quaternion Rotation; + public MinerPlacementGeometry.Box[] BuildBoxes, ObstacleBoxes; + // Covered excludes this candidate's own buried nodes. Repeated coverage is intentional. + public int[] Covered, Buried; + } + + private readonly List _candidates; + private readonly int _nodeCount; + private int _bestBuriedCount; + public List Best { get; private set; } = []; + public int BestScore { get; private set; } + + public MinerPlacementSolver(List candidates, int nodeCount) + { + _candidates = candidates; + _nodeCount = nodeCount; + } + + public IEnumerator Search(int passes) => Search(int.MaxValue, passes); + + 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) + { + 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); + } + + private IEnumerator Search(int limit, 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); + while (work.MoveNext()) yield return null; + foreach (var result in results) 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); + 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; + } + + private IEnumerator GreedyPass(int limit, int pass, List seeds, SearchResult[] results, int resultIndex, CancellationToken cancellationToken) + { + var selected = new List(); + var buried = new bool[_nodeCount]; + var uses = new int[_nodeCount]; + 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); + while (selected.Count < limit) + { + Candidate chosen = null; + var priority = float.NegativeInfinity; + for (var i = 0; i < _candidates.Count; i++) + { + if ((i & 127) == 0) + { + cancellationToken.ThrowIfCancellationRequested(); + yield return null; + } + var candidate = _candidates[i]; + if (seeds != null && 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)); + 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)) + { + chosen = candidate; + priority = value; + } + } + if (chosen == null) break; + Add(chosen, selected, buried, uses, ref score); + } + results[resultIndex] = new SearchResult(selected, score, CountBuried(selected)); + } + + private static void Drain(IEnumerator work, CancellationToken cancellationToken) + { + try { while (work.MoveNext()) cancellationToken.ThrowIfCancellationRequested(); } + finally { (work as IDisposable)?.Dispose(); } + } + + private static IEnumerator RunBatch(int count, Func create, int workers, CancellationToken cancellationToken) + { + if (workers > 0) + { + Parallel.For(0, count, new ParallelOptions { MaxDegreeOfParallelism = workers, CancellationToken = cancellationToken }, + index => Drain(create(index), cancellationToken)); + } + else for (var i = 0; i < count; i++) + { + var work = create(i); + try { while (work.MoveNext()) yield return null; } + finally { (work as IDisposable)?.Dispose(); } + } + } + + private sealed class SearchResult(List selected, int score, int buriedCount) + { + public List Selected = selected; + public int Score = score, BuriedCount = buriedCount; + } + + private void Accept(SearchResult result) + { + if (!IsBetter(result.Score, result.BuriedCount, result.Selected.Count, BestScore, _bestBuriedCount, Best.Count)) return; + Best = result.Selected; + BestScore = result.Score; + _bestBuriedCount = result.BuriedCount; + } + + private static bool IsBetter(int score, int buried, int count, int bestScore, int bestBuried, int bestCount) => + score > bestScore || score == bestScore && (buried < bestBuried || buried == bestBuried && count < bestCount); + + // 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) + { + for (var round = 0; round < 2 && Best.Count > 0; round++) + { + 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++) + { + 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])); + } + } + // 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; + } + } + + 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++) + { + if ((i & 127) == 0) { cancellationToken.ThrowIfCancellationRequested(); yield return null; } + row[i] = PairFits(_candidates[i], seed); + } + fits[index] = row; + } + + private IEnumerator RepackRegion(int limit, List seeds, (int, int, int) region, bool[][] fits, + SearchResult result, CancellationToken cancellationToken) + { + var state = new PartialLayout(_nodeCount); + var removed = new List(); + var centerX = 0f; + var centerZ = 0f; + for (var i = 0; i < seeds.Count; i++) + { + if (i != region.Item1 && i != region.Item2 && i != region.Item3) state.Add(seeds[i]); + else + { + removed.Add(seeds[i]); + centerX += seeds[i].X; + centerZ += seeds[i].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; } + 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; + 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))); + } + var options = new List(removed); + foreach (var bucket in buckets) + { + bucket.Sort((a, b) => b.Gain.CompareTo(a.Gain)); + var taken = 0; + foreach (var entry in bucket) + { + var candidate = entry.Candidate; + var duplicate = false; + foreach (var option in options) + { + var yaw = Math.Abs(candidate.Yaw - option.Yaw) % 360f; + if ((candidate.Position - option.Position).sqrMagnitude < 0.45f * 0.45f && Math.Min(yaw, 360f - yaw) < 6f) + { duplicate = true; break; } + } + if (duplicate) continue; + options.Add(candidate); + if (++taken == 12) break; + } + } + options.Sort((a, b) => b.Covered.Length.CompareTo(a.Covered.Length)); + var compatible = new bool[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 ((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) { 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(); + } + state.RemoveLast(); + } + state.RemoveLast(); + } + } + + private sealed class PartialLayout(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) + { + var gain = 0; + foreach (var index in candidate.Covered) if (_buried[index] == 0) gain++; + foreach (var index in candidate.Buried) if (_buried[index] == 0) gain -= _uses[index]; + return gain; + } + + public void Add(Candidate candidate) + { + RawScore += candidate.Covered.Length; + foreach (var index in candidate.Buried) + if (_buried[index]++ == 0) { Score -= _uses[index]; BuriedCount++; } + foreach (var index in candidate.Covered) + { + if (_buried[index] == 0) Score++; + _uses[index]++; + } + Selected.Add(candidate); + } + + public void RemoveLast() + { + var candidate = Selected[Selected.Count - 1]; + Selected.RemoveAt(Selected.Count - 1); + RawScore -= candidate.Covered.Length; + foreach (var index in candidate.Covered) + { + if (_buried[index] == 0) Score--; + _uses[index]--; + } + 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) + { + 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; + } + + public static bool Fits(Candidate candidate, List selected) + { + foreach (var other in selected) + { + if (!PairFits(candidate, other)) return false; + } + return true; + } + + private static bool PairFits(Candidate candidate, Candidate other) + { + var radius = candidate.Radius + other.Radius; + return (candidate.Position - other.Position).sqrMagnitude > radius * radius || + !Intersects(candidate.BuildBoxes, other.ObstacleBoxes) && !Intersects(other.BuildBoxes, candidate.ObstacleBoxes); + } + + 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; + return false; + } +} diff --git a/UXAssist/Functions/Factory/QuickMinerBuild.cs b/UXAssist/Functions/Factory/QuickMinerBuild.cs new file mode 100644 index 0000000..0b90e87 --- /dev/null +++ b/UXAssist/Functions/Factory/QuickMinerBuild.cs @@ -0,0 +1,867 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using BepInEx; +using UnityEngine; +using UXAssist.Common; +using UXAssist.Common.GameConstants; +using UXAssist.Common.ModFeatures; +using UXAssist.Patches.Factory; +using Candidate = UXAssist.Functions.Factory.MinerPlacementSolver.Candidate; +using Box = UXAssist.Functions.Factory.MinerPlacementGeometry.Box; +using GameLogicProc = UXAssist.Common.GameLogic; + +namespace UXAssist.Functions.Factory; + +[ModFeature("QuickMinerBuild")] +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; + private static float _resultTipUntil, _resultTipSpeed; + public static bool IsRunning => _job != null; + + public static void Init() => GameLogicProc.OnGameEnd += OnGameEnd; + + public static void Uninit() + { + OnGameEnd(); + GameLogicProc.OnGameEnd -= OnGameEnd; + } + + public static void Toggle() + { + ReleaseResultTip(true); + if (IsRunning) + { + Cancel(); + UIRealtimeTip.Popup(I18NKeys.QuickMinerCancelled.Translate()); + return; + } + var player = GameMain.mainPlayer; + var planet = GameMain.localPlanet; + if (!GameMain.isRunning || DSPGame.IsMenuDemo || player?.controller?.actionBuild == null || + planet?.factory == null || !planet.factoryLoaded || planet.physics == null || planet.type == EPlanetType.Gas) + { + UIRealtimeTip.Popup(I18NKeys.QuickMinerNeedPlanet.Translate()); + return; + } + try + { + _job = new Job(player, planet); + _work = _job.Run(); + UIRealtimeTip.Popup(I18NKeys.QuickMinerSearching.Translate()); + } + catch (Exception exception) + { + Fail(exception); + } + } + + public static void OnUpdate() + { + UpdateResultTip(); + if (_job == null) return; + if (!_job.IsCurrent) + { + Cancel(); + return; + } + if (GameMain.isPaused) return; + try + { + FrameTimer.Restart(); + while (FrameTimer.ElapsedMilliseconds < 6) + { + if (_work.MoveNext()) + { + if (_job.WaitingForWorkers) break; + continue; + } + Cancel(); + break; + } + } + catch (Exception exception) + { + Fail(exception); + } + } + + private static void Fail(Exception exception) + { + UXAssist.Logger.LogError($"Quick miner placement failed: {exception}"); + _job?.RecordFailure(exception); + Cancel(); + UIRealtimeTip.Popup(I18NKeys.QuickMinerFailed.Translate()); + } + + private static void Cancel() + { + _job?.Cancel(); + (_work as IDisposable)?.Dispose(); + _work = null; + _job = null; + } + + private static void OnGameEnd() + { + Cancel(); + ReleaseResultTip(true); + } + + private static void ShowResult(string message) + { + UXAssist.Logger.LogInfo($"Quick miner result: {message.Replace("\n", " | ")}"); + UIRealtimeTip.Popup(message); + foreach (var tip in UIRoot.instance.uiGame.generalTips.realtimeTips) + { + if (!tip.gameObject.activeSelf || tip.textComp.text != message) continue; + _resultTip = tip; + _resultText = message; + _resultTipSpeed = tip.upSpeed; + _resultTipUntil = Time.unscaledTime + 8f; + tip.upSpeed = 0f; + break; + } + } + + private static void UpdateResultTip() + { + if (!_resultTip) return; + if (!_resultTip.gameObject.activeSelf || _resultTip.textComp.text != _resultText || Time.unscaledTime >= _resultTipUntil) + { + ReleaseResultTip(false); + return; + } + // Native Update derives scale and alpha from lifeTime; values above 1 hide the tip. + _resultTip.lifeTime = 0.8f; + } + + private static void ReleaseResultTip(bool hide) + { + if (_resultTip && _resultTip.textComp.text == _resultText) + { + _resultTip.upSpeed = _resultTipSpeed; + if (hide) _resultTip.gameObject.SetActive(false); + } + _resultTip = null; + _resultText = null; + } + + private sealed class Node + { + public int Id; + public Vector3 Position, OriginalPosition; + public ColliderData Collider; + public bool Target, Visible, CanBury; + public EVeinType Type; + } + + private sealed class Job + { + 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 _candidates = []; + private readonly List _covered = [], _buried = []; + private readonly Box[] _buildBoxes, _obstacleBoxes; + private readonly ColliderData[] _nativeObstacles; + private readonly float _footprintRadius; + 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 Task _search; + private long _searchMilliseconds; + private string _result; + private Vector3 _center, _right, _forward; + private EVeinType _type; + private float _minX, _maxX, _minZ, _maxZ; + + public bool IsCurrent => GameMain.isRunning && GameMain.mainPlayer == _player && + GameMain.localPlanet == _planet && _planet.factory == _factory && _planet.physics == _physics && _planet.factoryLoaded; + public bool WaitingForWorkers => _search != null && !_search.IsCompleted; + + public Job(Player player, PlanetData planet) + { + _player = player; + _planet = planet; + _factory = planet.factory; + _physics = planet.physics; + _item = LDB.items.Select(ItemIds.MiningMachine); + var desc = _item.prefabDesc; + _buildBoxes = new Box[desc.buildColliders.Length]; + var obstacles = new List(); + foreach (var collider in desc.colliders) + { + if (!collider.isForBuild) continue; + if (collider.shape != EColliderShape.Box) throw new NotSupportedException("Mining Machine build collider is not a box."); + obstacles.Add(collider); + _footprintRadius = Mathf.Max(_footprintRadius, collider.pos.magnitude + collider.ext.magnitude); + } + _nativeObstacles = obstacles.ToArray(); + _obstacleBoxes = new Box[_nativeObstacles.Length]; + _debug.version = PluginInfo.PLUGIN_VERSION; + _debug.gameVersion = GameConfig.gameVersion.ToString(); + _debug.startedUtc = DateTime.UtcNow.ToString("O"); + _debug.logicalProcessors = Environment.ProcessorCount; + _debug.workerCount = _workers; + _debug.planetId = planet.id; + _debug.planetRadius = planet.realRadius; + _debug.initialStock = player.package.GetItemCount(ItemIds.MiningMachine) + + (player.inhandItemId == ItemIds.MiningMachine ? player.inhandItemCount : 0); + _debug.playerPosition = MinerPlacementDebug.Vector(player.position); + _debug.buildRange = player.mecha.buildArea; + _debug.unlimitedRange = FactoryPatch.RemoveBuildRangeLimitEnabled.Value; + _debug.buildColliders = desc.buildColliders.Select(MinerPlacementDebug.Collider.Capture).ToArray(); + _debug.minerColliders = _nativeObstacles.Select(MinerPlacementDebug.Collider.Capture).ToArray(); + _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 void RecordFailure(Exception exception) + { + _debug.outcome = "failed"; + _debug.error = exception.ToString(); + } + + public void Cancel() + { + _cancellation.Cancel(); + if (_search == null || _search.IsCompleted) + { + if (_search?.IsFaulted == true) _ = _search.Exception; + _cancellation.Dispose(); + } + else _search.ContinueWith(task => + { + if (task.IsFaulted) _ = task.Exception; + _cancellation.Dispose(); + }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + } + + 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() + { + if (!FindNodes()) + { + _debug.outcome = "no-veins"; + _result = I18NKeys.QuickMinerNoVeins.Translate(); + yield break; + } + RestoreTargetVeins(); + var reach = 9.5f * _planet.realRadius / 200f; + var width = _maxX - _minX + reach * 2; + var depth = _maxZ - _minZ + reach * 2; + // Bound the coarse search by 4,000 surface positions, then refine promising layouts. + var step = Mathf.Max(0.8f, Mathf.Sqrt(width * depth / 4000f)); + for (var x = _minX - reach; x <= _maxX + reach; x += step) + for (var z = _minZ - reach; z <= _maxZ + reach; z += step) + { + for (var yaw = 0f; yaw < 360f; yaw += 15f) + { + TryCandidate(x, z, yaw); + yield return null; + } + } + 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); + } + } + + private void RecordPhase(string name, MinerPlacementSolver solver, int passes) => _phases.Add(new MinerPlacementDebug.Phase + { + 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 + }); + + private string WriteDebug() + { + try + { + _debug.elapsedMilliseconds = _timer.ElapsedMilliseconds; + _debug.veinType = (int)_type; + _debug.center = MinerPlacementDebug.Vector(_center); + _debug.right = MinerPlacementDebug.Vector(_right); + _debug.forward = MinerPlacementDebug.Vector(_forward); + _debug.nodes = _nodes.Select(node => new MinerPlacementDebug.Node + { + id = node.Id, type = (int)node.Type, target = node.Target, visible = node.Visible, canBury = node.CanBury, + originalPosition = MinerPlacementDebug.Vector(node.OriginalPosition), position = MinerPlacementDebug.Vector(node.Position), + collider = MinerPlacementDebug.Collider.Capture(node.Collider) + }).ToArray(); + _debug.obstacles = _obstacles.Select(MinerPlacementDebug.Collider.Capture).ToArray(); + _debug.candidates = _candidates.Select(MinerPlacementDebug.CandidateData.Capture).ToArray(); + _debug.phases = _phases.ToArray(); + _debug.placements = _placements.ToArray(); + const string relative = "debug/UXAssist/QuickMiner"; + var directory = Path.Combine(Paths.BepInExRootPath, relative); + Directory.CreateDirectory(directory); + var file = Path.Combine(directory, $"{DateTime.UtcNow:yyyyMMdd-HHmmss-fff}-planet-{_debug.planetId}-{Guid.NewGuid():N}.json"); + MinerPlacementDebug.Write(file, _debug); + UXAssist.Logger.LogInfo($"Quick miner debug: {file}"); + return string.Format(I18NKeys.QuickMinerDebugSaved.Translate(), "BepInEx/" + relative); + } + catch (Exception exception) + { + UXAssist.Logger.LogWarning($"Quick miner debug export failed: {exception}"); + return I18NKeys.QuickMinerDebugFailed.Translate(); + } + } + + private bool FindNodes() + { + var nearest = float.PositiveInfinity; + var group = 0; + for (var i = 1; i < _factory.veinCursor; i++) + { + ref var vein = ref _factory.veinPool[i]; + if (vein.id != i || vein.amount <= 0 || vein.type is EVeinType.None or EVeinType.Oil) continue; + var distance = (vein.pos.normalized * _planet.realRadius - _player.position).sqrMagnitude; + if (distance >= nearest) continue; + nearest = distance; + group = vein.groupIndex; + _type = vein.type; + } + if (group == 0) return false; + _debug.veinGroup = group; + var count = 0; + for (var i = 1; i < _factory.veinCursor; i++) + { + ref var vein = ref _factory.veinPool[i]; + if (vein.id != i || vein.amount <= 0 || vein.groupIndex != group) continue; + _center += vein.pos.normalized; + count++; + } + if (count == 0) return false; + _center = _center.normalized * (_planet.realRadius + 0.2f); + var rotation = Maths.SphericalRotation(_center, 0f); + _right = rotation * Vector3.right; + _forward = rotation * Vector3.forward; + var radius = 0f; + for (var i = 1; i < _factory.veinCursor; i++) + { + ref var vein = ref _factory.veinPool[i]; + if (vein.id != i || vein.amount <= 0 || vein.groupIndex != group) continue; + var delta = vein.pos.normalized * (_planet.realRadius + 0.2f) - _center; + var x = Vector3.Dot(delta, _right); + var z = Vector3.Dot(delta, _forward); + _minX = Mathf.Min(_minX, x); + _maxX = Mathf.Max(_maxX, x); + _minZ = Mathf.Min(_minZ, z); + _maxZ = Mathf.Max(_maxZ, z); + radius = Mathf.Max(radius, delta.magnitude); + } + radius += 20f * _planet.realRadius / 200f + _footprintRadius; + // Read the native data, including inactive colliders outside the camera/player area. + // Physics queries alone can miss those colliders when the config window is open. + foreach (var chunk in _physics.colChunks) + { + for (var i = 1; i < chunk.cursor; i++) + { + var collider = chunk.colliderPool[i]; + var bound = radius + collider.ext.magnitude + collider.radius; + if (collider.idType != 0 && collider.isForBuild && (collider.pos - _center).sqrMagnitude <= bound * bound) + _obstacles.Add(collider); + } + } + var reserved = ReservedNodes(); + for (var i = 1; i < _factory.veinCursor; i++) + { + ref var vein = ref _factory.veinPool[i]; + if (vein.id != i || vein.amount <= 0 || vein.colliderId <= 0) continue; + var surface = vein.pos.normalized * (_planet.realRadius + 0.2f); + if ((surface - _center).sqrMagnitude > radius * radius) continue; + _nodes.Add(new Node + { + Id = i, Target = vein.groupIndex == group, Type = vein.type, + Position = vein.pos, OriginalPosition = vein.pos, Collider = _physics.GetColliderData(vein.colliderId), + Visible = vein.pos.magnitude >= _planet.realRadius - 40f, + CanBury = vein.groupIndex == group && vein.minerCount == 0 && !reserved.Contains(i) + }); + } + var existing = new List(); + for (var i = 1; i < _factory.entityCursor; i++) + { + ref var entity = ref _factory.entityPool[i]; + if (entity.id != i || entity.protoId != ItemIds.MiningMachine || entity.minerId <= 0 || + (entity.pos - _center).sqrMagnitude > radius * radius) continue; + ref var miner = ref _factory.factorySystem.minerPool[entity.minerId]; + existing.Add(new MinerPlacementDebug.ExistingMiner + { + entityId = i, minerId = entity.minerId, position = MinerPlacementDebug.Vector(entity.pos), + rotation = MinerPlacementDebug.Rotation(entity.rot), veins = miner.veins?.Take(miner.veinCount).ToArray() ?? [] + }); + } + for (var i = 1; i < _factory.prebuildCursor; i++) + { + ref var prebuild = ref _factory.prebuildPool[i]; + if (prebuild.id != i || prebuild.protoId != ItemIds.MiningMachine || + (prebuild.pos - _center).sqrMagnitude > radius * radius) continue; + existing.Add(new MinerPlacementDebug.ExistingMiner + { + entityId = i, prebuild = true, position = MinerPlacementDebug.Vector(prebuild.pos), + rotation = MinerPlacementDebug.Rotation(prebuild.rot), veins = prebuild.parameters?.Take(prebuild.paramCount).ToArray() ?? [] + }); + } + _debug.existingMiners = existing.ToArray(); + return _nodes.Count > 0; + } + + private HashSet ReservedNodes() + { + var reserved = new HashSet(); + for (var i = 1; i < _factory.prebuildCursor; i++) + { + ref var prebuild = ref _factory.prebuildPool[i]; + if (prebuild.id != i || prebuild.parameters == null) continue; + var desc = LDB.models.Select(prebuild.modelIndex)?.prefabDesc; + if (desc == null || !desc.veinMiner) continue; + for (var j = desc.isVeinCollector ? 2048 : 0; j < prebuild.paramCount; j++) reserved.Add(prebuild.parameters[j]); + } + return reserved; + } + + private void RestoreTargetVeins() + { + var changed = false; + foreach (var node in _nodes) + { + if (!node.Target || node.Visible) continue; + var surface = node.Position.normalized * (_planet.data.QueryModifiedHeight(node.Position) - 0.13f); + var collider = node.Collider; + collider.pos = surface + surface.normalized * 0.4f; + var obstructed = false; + foreach (var obstacle in _obstacles) + { + // Building triggers are normally boxes. For unusual spherical/capsule + // triggers, conservatively keep the node buried inside their bounds. + var bound = obstacle; + if (bound.shape != EColliderShape.Box) + { + bound.idType = (int)EColliderShape.Box << 24; + bound.q = Quaternion.identity; + bound.ext = new Vector3(Mathf.Abs(obstacle.ext.x), Mathf.Abs(obstacle.ext.y), Mathf.Abs(obstacle.ext.z)) + Vector3.one * obstacle.radius; + } + if (MinerPlacementGeometry.Intersects(new Box(bound), collider)) + { + obstructed = true; + break; + } + } + if (obstructed) continue; + SetVeinPosition(node.Id, surface); + node.Position = surface; + node.Collider = _physics.GetColliderData(_factory.veinPool[node.Id].colliderId); + node.Visible = true; + changed = true; + } + if (changed) RefreshVeins(2); + } + + private IEnumerator Refine(List seeds, float distance, float angle) + { + foreach (var seed in seeds) + for (var x = -2; x <= 2; x++) + for (var z = -2; z <= 2; z++) + for (var yaw = -2; yaw <= 2; yaw++) + { + TryCandidate(seed.X + x * distance, seed.Z + z * distance, seed.Yaw + yaw * angle); + yield return null; + } + } + + 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 void TryCandidate(float x, float z, float yaw) + { + _debug.rejections.attempted++; + var pos = (_center + _right * x + _forward * z).normalized * (_planet.realRadius + 0.2f); + if (!FactoryPatch.RemoveBuildRangeLimitEnabled.Value && + (pos - _player.position).sqrMagnitude > _player.mecha.buildArea * _player.mecha.buildArea) + { _debug.rejections.range++; return; } + var rotation = Maths.SphericalRotation(pos, yaw); + var pose = new Pose(pos, rotation); + _covered.Clear(); + for (var i = 0; i < _nodes.Count; i++) + { + var node = _nodes[i]; + if (!node.Visible || node.Type == EVeinType.Oil || !MinerComponent.IsTargetVeinInRange(node.Position, pose, _item.prefabDesc)) continue; + if (node.Type != _type) { _debug.rejections.mixedType++; return; } + _covered.Add(i); + } + if (_covered.Count < MinerPlacementSolver.MinimumCoverage) { _debug.rejections.noCoverage++; return; } + 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++) + { + var node = _nodes[i]; + if (!node.Visible || !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) + if (Hits(obstacle)) { _debug.rejections.buildingCollision++; return; } + if (!HasGround(pos, rotation)) { _debug.rejections.ground++; return; } + for (var i = 0; i < _nativeObstacles.Length; i++) + _obstacleBoxes[i] = new Box(_nativeObstacles[i].BindToObject(0, 0, EObjectType.None, pos, rotation)); + _candidates.Add(new Candidate + { + X = x, Z = z, Yaw = yaw, Position = pos, Rotation = rotation, Radius = _footprintRadius, + Covered = _covered.ToArray(), Buried = _buried.ToArray(), + BuildBoxes = (Box[])_buildBoxes.Clone(), ObstacleBoxes = (Box[])_obstacleBoxes.Clone() + }); + } + + private bool Hits(ColliderData collider) + { + foreach (var box in _buildBoxes) + { + var radius = box.Extents.magnitude + collider.ext.magnitude + collider.radius; + if ((box.Center - collider.pos).sqrMagnitude <= radius * radius && MinerPlacementGeometry.Intersects(box, collider)) return true; + } + return false; + } + + private bool HasGround(Vector3 position, Quaternion rotation) + { + // Match the ordinary miner's native land-point tests, including water clearance. + var desc = _item.prefabDesc; + foreach (var point in desc.landPoints) + { + var origin = position + rotation * new Vector3(point.x, 0f, point.z); + var up = origin.normalized; + origin += up * 3f; + if (!Physics.Raycast(origin, -up, out var ground, 18f, + (1 << (int)Layer.Terrain) | (1 << (int)Layer.Platform), QueryTriggerInteraction.Collide) || + ground.point.magnitude - _planet.realRadius < -0.3f - desc.landOffset) return false; + var waterDistance = Physics.Raycast(origin, -up, out var water, 20f, 1 << (int)Layer.Water, QueryTriggerInteraction.Collide) + ? water.distance : 1000f; + if (ground.distance - waterDistance > 0.27f + desc.landOffset) return false; + } + return true; + } + + private void Commit(List layout) + { + if (!NodesUnchanged(layout)) + { + _debug.outcome = "veins-changed"; + _result = I18NKeys.QuickMinerVeinsChanged.Translate(); + return; + } + 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(); + try + { + validator._Init(GameMain.data); + validator.planet = _planet; + validator.factory = _factory; + validator.handItem = _item; + validator.handPrefabDesc = _item.prefabDesc; + validator.tmpPackage = new StorageComponent(1); + var preview = new BuildPreview(); + validator.buildPreviews.Add(preview); + for (var i = 0; i < layout.Count; i++) + { + var candidate = layout[i]; + var debug = new MinerPlacementDebug.Placement + { + candidate = _candidates.IndexOf(candidate), outcome = "pending", nativeCondition = "not-checked", nativeVeins = [], plannedVeins = [], finalVeins = [] + }; + _placements.Add(debug); + // No yield between burial, native validation, item consumption, and creation. + foreach (var index in candidate.Buried) + { + var node = _nodes[index]; + ref var vein = ref _factory.veinPool[node.Id]; + if (vein.id != node.Id || hidden.ContainsKey(node.Id)) continue; + hidden.Add(node.Id, vein.pos); + SetVeinPosition(node.Id, vein.pos.normalized * (_planet.realRadius - 50f)); + } + RefreshVeins(0); + if (!Validate(validator, preview, candidate, plannedBurial, debug)) continue; + var itemId = ItemIds.MiningMachine; + var count = 1; + if (_player.inhandItemId == itemId && _player.inhandItemCount > 0) _player.UseHandItems(1, out _); + else _player.package.TakeTailItems(ref itemId, ref count, out _); + // Match native blueprint placement: missing items leave unfunded prebuilds. + var prebuild = new PrebuildData + { + protoId = (short)_item.ID, modelIndex = (short)_item.prefabDesc.modelIndex, + pos = candidate.Position, pos2 = candidate.Position, rot = candidate.Rotation, rot2 = candidate.Rotation, + itemRequired = count == 1 ? 0 : 1, + filterId = _factory.veinPool[_nodes[candidate.Covered[0]].Id].productId + }; + prebuild.InitParametersArray(debug.plannedVeins.Length); + Array.Copy(debug.plannedVeins, prebuild.parameters, debug.plannedVeins.Length); + var id = _factory.AddPrebuildDataWithComponents(prebuild); + debug.prebuildId = id; + debug.itemRequired = prebuild.itemRequired; + debug.outcome = id > 0 ? "placed" : "prebuild-failed"; + if (id == 0 && count == 1) _player.TryAddItemToPackage(ItemIds.MiningMachine, 1, 0, true); + if (id > 0) placed.Add((candidate, id, debug)); + } + } + finally + { + validator._Free(); + // A failed/shortened layout must not leave nodes buried for unplaced miners. + var needed = new HashSet(); + foreach (var entry in placed) + foreach (var index in entry.Candidate.Buried) needed.Add(_nodes[index].Id); + foreach (var entry in hidden) + if (!needed.Contains(entry.Key)) SetVeinPosition(entry.Key, entry.Value); + foreach (var entry in placed) + { + var ids = new List(); + var pose = new Pose(entry.Candidate.Position, entry.Candidate.Rotation); + foreach (var node in _nodes) + { + ref var vein = ref _factory.veinPool[node.Id]; + if (vein.id == node.Id && vein.amount > 0 && vein.type == _type && vein.pos.magnitude >= _planet.realRadius - 40f && + MinerComponent.IsTargetVeinInRange(vein.pos, pose, _item.prefabDesc)) ids.Add(node.Id); + } + ref var prebuild = ref _factory.prebuildPool[entry.Prebuild]; + prebuild.InitParametersArray(ids.Count); + if (ids.Count > 0) ids.CopyTo(prebuild.parameters); + entry.Debug.finalVeins = ids.ToArray(); + coverage += ids.Count; + } + buriedCount = needed.Count; + RefreshVeins(buriedCount > 0 ? 1 : 0); + } + _debug.placedCount = placed.Count; + _debug.totalCoverage = coverage; + _debug.buriedCount = buriedCount; + if (placed.Count == 0) _debug.outcome = "no-placement"; + _result = placed.Count == 0 ? I18NKeys.QuickMinerNoPlacement.Translate() : + string.Format(I18NKeys.QuickMinerResult.Translate(), placed.Count, coverage, buriedCount); + } + + private bool NodesUnchanged(List layout) + { + foreach (var node in _nodes) + { + if (node.Id >= _factory.veinPool.Length) return false; + ref var vein = ref _factory.veinPool[node.Id]; + if (vein.id != node.Id || vein.type != node.Type || vein.amount <= 0 || vein.colliderId <= 0 || + (vein.pos - node.Position).sqrMagnitude > 0.0001f) return false; + } + var reserved = ReservedNodes(); + foreach (var candidate in layout) + foreach (var index in candidate.Buried) + { + var id = _nodes[index].Id; + if (_factory.veinPool[id].minerCount > 0 || reserved.Contains(id)) return false; + } + return true; + } + + 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; + preview.lpos = preview.lpos2 = candidate.Position; + preview.lrot = preview.lrot2 = candidate.Rotation; + preview.condition = EBuildCondition.Ok; + validator.tmpInhandId = _item.ID; + validator.tmpInhandCount = 1; + var action = _player.controller.actionBuild; + var oldTest = _player.controller.cmd.test; + var oldCursorState = action.model.cursorState; + var oldCursorText = action.model.cursorText; + var oldCursor = UICursor.cursorIndex; + try + { + // CommandState is a struct; update the controller's field, not a local copy. + _player.controller.cmd.test = candidate.Position; + _physics.nearColliderLogic.ActiveCollidersInArea(candidate.Position, _footprintRadius + 16f); + // UpdateCursorNear does nothing outside build mode. Activate the native vein + // colliders explicitly so CheckBuildConditions still sees them from this button. + foreach (var node in _nodes) + { + var id = _factory.veinPool[node.Id].colliderId; + while (id > 0) + { + var collider = _physics.GetColliderData(id); + var objects = _physics.nearColliderLogic.colliderObjs; + if (objects.TryGetValue(id, out var existing)) existing.live = true; + else objects[id] = new ColliderObject(id, collider); + id = collider.link; + } + } + Physics.SyncTransforms(); + var valid = validator.CheckBuildConditions(); + debug.nativeCondition = preview.condition.ToString(); + debug.coverObjectId = preview.coverObjId; + debug.nativeVeins = preview.parameters?.Take(preview.paramCount).ToArray() ?? []; + if (!valid || preview.condition != EBuildCondition.Ok || preview.coverObjId != 0) return false; + // Include every planned burial now, so a later miner cannot reduce this one + // below the minimum after its item has already been consumed. + debug.plannedVeins = debug.nativeVeins.Where(id => !plannedBurial.Contains(id)).ToArray(); + if (debug.plannedVeins.Length < MinerPlacementSolver.MinimumCoverage) + { debug.outcome = "below-minimum-coverage"; return false; } + for (var i = 0; i < preview.paramCount; i++) + { + ref var vein = ref _factory.veinPool[preview.parameters[i]]; + if (vein.id != preview.parameters[i] || vein.amount <= 0 || vein.type != _type) return false; + } + return true; + } + finally + { + _player.controller.cmd.test = oldTest; + action.model.cursorState = oldCursorState; + action.model.cursorText = oldCursorText; + UICursor.cursorIndex = oldCursor; + } + } + + private void SetVeinPosition(int id, Vector3 position) + { + ref var vein = ref _factory.veinPool[id]; + vein.pos = position; + ref var collider = ref _physics.GetColliderDataRef(vein.colliderId); + collider.pos = position + position.normalized * 0.4f; + _physics.SetPlanetPhysicsColliderDirty(); + GameMain.gpuiManager.AlterModel(vein.modelIndex, vein.modelId, id, position, setBuffer: false); + var proto = LDB.veins.Select((int)vein.type); + if (proto == null) return; + var up = position.normalized; + if (vein.minerId0 > 0) + { + GameMain.gpuiManager.AlterModel(proto.MinerBaseModelIndex, vein.minerBaseModelId, vein.minerId0, position + up * 0.1f, setBuffer: false); + GameMain.gpuiManager.AlterModel(proto.MinerCircleModelIndex, vein.minerCircleModelId0, vein.minerId0, position + up * 0.4f, setBuffer: false); + } + if (vein.minerId1 > 0) GameMain.gpuiManager.AlterModel(proto.MinerCircleModelIndex, vein.minerCircleModelId1, vein.minerId1, position + up * 0.6f, setBuffer: false); + if (vein.minerId2 > 0) GameMain.gpuiManager.AlterModel(proto.MinerCircleModelIndex, vein.minerCircleModelId2, vein.minerId2, position + up * 0.8f, setBuffer: false); + if (vein.minerId3 > 0) GameMain.gpuiManager.AlterModel(proto.MinerCircleModelIndex, vein.minerCircleModelId3, vein.minerId3, position + up, setBuffer: false); + } + + private void RefreshVeins(int operation) + { + _physics.RefreshColliders(); + GameMain.gpuiManager.SyncAllGPUBuffer(); + if (operation != 0) GameMain.gameScenario?.NotifyOnVeinReformed(operation); + } + } +} diff --git a/UXAssist/README.md b/UXAssist/README.md index eac7915..ae84aee 100644 --- a/UXAssist/README.md +++ b/UXAssist/README.md @@ -81,6 +81,14 @@ * Quick dismantle all buildings (without drops) * Quick build Orbital Collectors * 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. + * 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. + * 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. * 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. @@ -273,6 +281,14 @@ * 快速拆除所有建筑(不掉落) * 快速建造轨道采集器 * 可设置单次建造数量上限;设为 0 时尽可能多地建造 + * 快速铺设采矿机 + * 点击「工厂」页中轨道采集器按钮附近的按钮,在最近的固体矿脉生成完整的普通采矿机布局,数量不受库存限制。有采矿机时正常消耗背包和手持物品,不足的位置保留待建造虚影,等待补充材料。所有计划掩埋完成后,每台矿机仍须覆盖至少 3 个矿点;少于 3 个的视为无效,不予铺设。 + * 先还原未被建筑阻挡的掩埋矿点,再按原版独立碰撞体搜索布局,保留游戏允许的矿机脚部交叉空间。 + * 比较多种铺设顺序,细调位置和朝向,按机身宽度补充紧邻候选,并允许邻近的两三台矿机一起重新布局,尽量提高各台矿机覆盖矿点数之和;同一矿点被多台矿机覆盖时重复计数。计算有界,不保证全局最优。 + * 复用碰撞检查结果,使用最多 4 个后台线程并行搜索独立布局,线程数不超过可用逻辑线程数的一半。单逻辑线程系统继续在主线程按每帧预算计算。原生地形检查和实际铺设保留在主线程;并行调度与顺序搜索生成相同布局。 + * 允许掩埋未被使用的矿点来提高总覆盖数;保护已有矿机及待建造矿机使用的矿点。仍需满足地面、水面、现有建筑和建造范围要求。 + * 计算期间再次点击可取消,切换行星或退出游戏自动取消。待建造对象由建设机器人完成,不自动铺设传送带和电力设施。 + * 功能调试期间,每次计算都会在当前游戏配置目录的 `BepInEx/debug/UXAssist/QuickMiner/` 下写入带时间戳的 JSON 文件,记录矿点、原生碰撞体、有效候选、搜索阶段及其搜索耗时、逻辑线程数和工作线程数、现有矿机和原生铺设校验结果。完成提示保留约 8 秒,日志也会记录结果摘要和文件的完整路径。在仓库根目录运行 `powershell -File tools/tests/Test-QuickMinerPlacement.ps1 -Snapshot `,即可离线重放并比较顺序与并行搜索结果,无需读取存档。 * 用于自动购买黑雾物品的传送带信号 * 在信号面板上添加了6个传送带信号,可以用于自动购买黑雾道具。 * 生成的物品堆叠数为4。 diff --git a/UXAssist/UIConfigWindow.cs b/UXAssist/UIConfigWindow.cs index d890516..6e45b0b 100644 --- a/UXAssist/UIConfigWindow.cs +++ b/UXAssist/UIConfigWindow.cs @@ -4,6 +4,7 @@ using UnityEngine; using UnityEngine.Events; using UXAssist.Common; using UXAssist.Functions; +using UXAssist.Functions.Factory; using UXAssist.ModsCompat; using UXAssist.Patches; using UXAssist.Patches.Logistics; @@ -17,6 +18,7 @@ public static class UIConfigWindow private static RectTransform _windowTrans; private static RectTransform _dysonTab; private static UIButton _dysonInitBtn; + private static UnityEngine.UI.Text _quickMinerText; private static readonly UIButton[] DysonLayerBtn = new UIButton[10]; public static void Init() @@ -365,7 +367,13 @@ public static class UIConfigWindow UIMessageBox.Show(I18NKeys.DismantleAllBuildings.Translate(), I18NKeys.DismantleAllBuildingsConfirm.Translate(), I18NKeys.Cancel.Translate(), I18NKeys.OK.Translate(), UIMessageBox.QUESTION, null, () => { PlanetFunctions.DismantleAll(false); }) ); - y += 72f; + y += 36f; + var quickMiner = wnd.AddButton(x, y, 240, tab2, I18NKeys.QuickBuildMiningMachines, 16, "button-quick-miners", QuickMinerBuild.Toggle); + _quickMinerText = quickMiner.transform.Find("button-text").GetComponent(); + var quickMinerLocalizer = _quickMinerText.GetComponent(); + if (quickMinerLocalizer != null) UnityEngine.Object.DestroyImmediate(quickMinerLocalizer); + wnd.AddTipsButton2(x + 250f, y + 6f, tab2, I18NKeys.QuickBuildMiningMachines, I18NKeys.QuickBuildMiningMachinesTips, "quick-miners-tips"); + y += 36f; wnd.AddButton(x, y, 200, tab2, I18NKeys.QuickBuildOrbitalCollectors, 16, "button-init-planet", PlanetFunctions.BuildOrbitalCollectors); y += 30f; txt = wnd.AddText2(x + 10f, y, tab2, I18NKeys.MaximumCountToBuild, 15, "text-oc-build-count"); @@ -826,6 +834,8 @@ public static class UIConfigWindow private static void UpdateUI() { + if (_quickMinerText != null) _quickMinerText.text = (QuickMinerBuild.IsRunning + ? I18NKeys.QuickMinerCancelSearch : I18NKeys.QuickBuildMiningMachines).Translate(); UpdateDysonShells(); } diff --git a/UXAssist/UXAssist.csproj b/UXAssist/UXAssist.csproj index 4ea3173..1a9d36b 100644 --- a/UXAssist/UXAssist.csproj +++ b/UXAssist/UXAssist.csproj @@ -3,13 +3,14 @@ org.soardev.uxassist DSP MOD - UXAssist - 1.6.2 + 1.6.3 UXAssist UXAssist true + diff --git a/UXAssist/package/manifest.json b/UXAssist/package/manifest.json index ad65f3e..9eb19e7 100644 --- a/UXAssist/package/manifest.json +++ b/UXAssist/package/manifest.json @@ -1,6 +1,6 @@ { "name": "UXAssist", - "version_number": "1.6.2", + "version_number": "1.6.3", "website_url": "https://github.com/soarqin/DSP_Mods/tree/master/UXAssist", "description": "Some functions and patches for better user experience / 一些提升用户体验的功能和补丁", "dependencies": [ diff --git a/tools/tests/QuickMinerPlacementTests.cs b/tools/tests/QuickMinerPlacementTests.cs new file mode 100644 index 0000000..8b88723 --- /dev/null +++ b/tools/tests/QuickMinerPlacementTests.cs @@ -0,0 +1,390 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Threading; +using UnityEngine; +using UXAssist.Functions.Factory; +using Candidate = UXAssist.Functions.Factory.MinerPlacementSolver.Candidate; +using Box = UXAssist.Functions.Factory.MinerPlacementGeometry.Box; + +internal static class QuickMinerPlacementTests +{ + private static int _checks; + + private static void Check(bool condition, string message) + { + if (!condition) throw new InvalidOperationException(message); + _checks++; + } + + private static Quaternion Yaw(float degrees) + { + var radians = degrees * Math.PI / 360; + return new Quaternion(0, (float)Math.Sin(radians), 0, (float)Math.Cos(radians)); + } + + private static ColliderData Collider(Vector3 center, Vector3 halfSize, Quaternion rotation) => new() + { + idType = 3 << 24 | 1 << 29, pos = center, ext = halfSize, q = rotation + }; + + private static Candidate Placement(float x, int[] covered, int[] buried = null, float halfWidth = 0.4f) => new() + { + X = x, Z = 0, Yaw = 0, Rotation = Quaternion.identity, + Position = new Vector3(x, 0, 0), Radius = halfWidth * 2, + Covered = covered, Buried = buried ?? [], + BuildBoxes = [new Box(Collider(new Vector3(x, 0, 0), new Vector3(halfWidth, 0.4f, 0.4f), Quaternion.identity))], + 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) + { + var solver = new MinerPlacementSolver(candidates, nodes); + var search = limit.HasValue ? solver.Search(limit.Value, 12) : solver.Search(12); + 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(); + 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++) + { + Check(solver.Best[i].Covered.Count(n => !buried.Contains(n)) >= MinerPlacementSolver.MinimumCoverage, + "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."); + } + return solver; + } + + private static void SolverChecks() + { + for (var processors = 1; processors <= 64; processors++) + Check(MinerPlacementSolver.GetWorkerCount(processors) <= processors / 2 && MinerPlacementSolver.GetWorkerCount(processors) <= 4, + "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."); + if (MinerPlacementSolver.WorkerCount > 0) + { + var oneWorker = new MinerPlacementSolver(shared, 3); + oneWorker.SearchAsync(int.MaxValue, 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."); + + 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."); + 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."); + 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."); + 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."); + 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, + "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]), + "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, + "Reject cyclic burials that would repeatedly invalidate an earlier miner."); + + // Three columns all block three alternative rows. Duplicated high-scoring column + // alternatives prevent randomized greedy orders from accidentally solving this trap. + // Replacing any single column still leaves the other two blocking every better row. + Candidate Bar(float x, float z, float width, float depth, int count) + { + var candidate = Placement(x, Enumerable.Range(0, count).ToArray(), halfWidth: width); + candidate.Z = z; + candidate.Position = new Vector3(x, 0, z); + candidate.Radius = 10; + candidate.Yaw = width > depth ? 90 : 0; + candidate.Rotation = Yaw(candidate.Yaw); + candidate.BuildBoxes = [new Box(Collider(candidate.Position, new Vector3(Math.Min(width, depth), 0.4f, Math.Max(width, depth)), candidate.Rotation))]; + candidate.ObstacleBoxes = candidate.BuildBoxes; + return candidate; + } + 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."); + + // 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]), + 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."); + } + + private static bool CornerOracle(ColliderData a, ColliderData b) + { + var axesA = new[] { a.q * Vector3.right, a.q * Vector3.up, a.q * Vector3.forward }; + var axesB = new[] { b.q * Vector3.right, b.q * Vector3.up, b.q * Vector3.forward }; + var axes = axesA.Concat(axesB).Concat(axesA.SelectMany(x => axesB.Select(y => Vector3.Cross(x, y)))); + var cornersA = Corners(a); + var cornersB = Corners(b); + foreach (var axis in axes) + { + if (axis.sqrMagnitude < 1e-10f) continue; + var first = cornersA.Select(p => Vector3.Dot(p, axis)).ToArray(); + var second = cornersB.Select(p => Vector3.Dot(p, axis)).ToArray(); + if (first.Max() < second.Min() || second.Max() < first.Min()) return false; + } + return true; + } + + private static Vector3[] Corners(ColliderData collider) + { + var points = new List(); + for (var x = -1; x <= 1; x += 2) + for (var y = -1; y <= 1; y += 2) + for (var z = -1; z <= 1; z += 2) + points.Add(collider.pos + collider.q * new Vector3(x * collider.ext.x, y * collider.ext.y, z * collider.ext.z)); + return points.ToArray(); + } + + private static void GeometryChecks() + { + var unit = new Box(Collider(Vector3.zero, Vector3.one, Quaternion.identity)); + Check(MinerPlacementGeometry.Intersects(unit, new Box(Collider(new Vector3(1.9f, 0, 0), Vector3.one, Yaw(0)))), "Overlapping boxes missed."); + Check(!MinerPlacementGeometry.Intersects(unit, new Box(Collider(new Vector3(2.01f, 0, 0), Vector3.one, Yaw(0)))), "Separated boxes collide."); + Check(!MinerPlacementGeometry.Intersects(unit, new Box(Collider(new Vector3(0, 3, 0), Vector3.one, Yaw(60)))), "Height separation must be respected."); + var capsule = new ColliderData { idType = 2 << 24, pos = new Vector3(1.4f, 0, 0), ext = new Vector3(0, 3, 0), radius = 0.5f }; + Check(MinerPlacementGeometry.Intersects(unit, capsule), "Capsule side intersection missed."); + capsule.pos.x = 1.6f; + Check(!MinerPlacementGeometry.Intersects(unit, capsule), "Separated capsule intersects."); + Check(Math.Abs(MinerPlacementGeometry.SegmentDistanceSquared(new Vector3(2, 2, 2), new Vector3(2, 2, 2), Vector3.one) - 3) < 1e-5, "Zero-length segment distance."); + Check(MinerPlacementGeometry.SegmentDistanceSquared(new Vector3(-3, 0, 0), new Vector3(3, 0, 0), Vector3.one) == 0, "Segment through box distance."); + + // Native ordinary miner prefab: body and two foot-end triggers. PrefabDesc reduces + // the final encompassing trigger to a small marker, excluding it from buildColliders. + var native = NativeMiner(0); + Check(MinerPlacementSolver.Fits(NativeMiner(3.1f), [native]), "Native miner feet must be allowed to interleave."); + Check(MinerPlacementSolver.Fits(NativeMiner(3.05f), [native]), "Body-width neighbor sampling must reach the narrow interleaving interval."); + Check(!MinerPlacementSolver.Fits(NativeMiner(3.2f), [native]), "The 0.8m coarse lattice lands on a foot-end collision."); + Check(MinerPlacementSolver.Fits(NativeMiner(6.2f), [native, NativeMiner(3.1f)]), "Three native miners must fit in an interleaving row."); + Check(MinerPlacementSolver.Fits(NativeMiner(3.65f, -0.6f, 15), [native]), "Angled crossing must also fit the independent native colliders."); + Check(!MinerPlacementSolver.Fits(NativeMiner(4), [native]), "Actual foot-end collisions must still be rejected."); + var envelope = new Box(Collider(new Vector3(0, 1.2f, -0.175f), new Vector3(2.4f, 2.25f, 3.725f), Quaternion.identity)); + var shiftedEnvelope = new Box(Collider(new Vector3(3.1f, 1.2f, -0.175f), new Vector3(2.4f, 2.25f, 3.725f), Quaternion.identity)); + Check(MinerPlacementGeometry.Intersects(envelope, shiftedEnvelope), "Interleaving fixture must expose an enclosing-box false positive."); + + var random = new System.Random(2301); + float Next(float scale) => (float)(random.NextDouble() * 2 - 1) * scale; + for (var i = 0; i < 2000; i++) + { + Quaternion Rotation() + { + var x = Next(1); var y = Next(1); var z = Next(1); var w = Next(1); + var length = (float)Math.Sqrt(x * x + y * y + z * z + w * w); + return new Quaternion(x / length, y / length, z / length, w / length); + } + var a = Collider(new Vector3(Next(3), Next(3), Next(3)), new Vector3(Math.Abs(Next(2)) + 0.1f, 0.4f, 1.3f), Rotation()); + var b = Collider(new Vector3(Next(3), Next(3), Next(3)), new Vector3(1.1f, 0.6f, Math.Abs(Next(2)) + 0.1f), Rotation()); + Check(MinerPlacementGeometry.Intersects(new Box(a), new Box(b)) == CornerOracle(a, b), "Oriented-box result disagrees with corner projections."); + Check(MinerPlacementGeometry.Intersects(new Box(a), new Box(b)) == MinerPlacementGeometry.Intersects(new Box(b), new Box(a)), "Box intersection must be symmetric."); + + var start = new Vector3(Next(5), Next(5), Next(5)); + var end = new Vector3(Next(5), Next(5), Next(5)); + double Distance(double t) + { + var p = start + (end - start) * (float)t; + var x = Math.Max(0, Math.Abs(p.x) - 1); + var y = Math.Max(0, Math.Abs(p.y) - 1); + var z = Math.Max(0, Math.Abs(p.z) - 1); + return x * x + y * y + z * z; + } + double low = 0, high = 1; + for (var n = 0; n < 60; n++) + { + var left = (low * 2 + high) / 3; + var right = (low + high * 2) / 3; + if (Distance(left) < Distance(right)) high = right; else low = left; + } + var expected = Distance((low + high) / 2); + Check(Math.Abs(MinerPlacementGeometry.SegmentDistanceSquared(start, end, Vector3.one) - expected) < 0.0001, "Capsule distance disagrees with independent convex minimization."); + } + } + + private static ColliderData[] NativeColliders() => + [ + Collider(new Vector3(0, 1.2f, 0.5f), new Vector3(1.51f, 2.25f, 3.05f), Quaternion.identity), + Collider(new Vector3(-2, 0.5f, -3.5f), new Vector3(0.4f, 1.5f, 0.4f), Quaternion.identity), + Collider(new Vector3(2, 0.5f, -3.5f), new Vector3(0.4f, 1.5f, 0.4f), Quaternion.identity), + Collider(new Vector3(0, 1.2f, -0.4f), Vector3.one * 0.1f, Quaternion.identity) + ]; + + private static Candidate NativeMiner(float x, float z = 0, float yaw = 0) + { + var colliders = NativeColliders(); + var position = new Vector3(x, 0, z); + var rotation = Yaw(yaw); + return new Candidate + { + X = x, Z = z, Yaw = yaw, Position = position, Rotation = rotation, Radius = 8, Covered = [0], Buried = [], + BuildBoxes = colliders.Take(3).Select(c => new Box(c.BindToObject(0, 0, EObjectType.None, position, rotation))).ToArray(), + ObstacleBoxes = colliders.Select(c => new Box(c.BindToObject(0, 0, EObjectType.None, position, rotation))).ToArray() + }; + } + + private static readonly JsonSerializerOptions ReplayJson = new() { IncludeFields = true }; + + private static void CancellationChecks() + { + if (MinerPlacementSolver.WorkerCount == 0) return; + var candidates = Enumerable.Repeat(Placement(0, [0, 1, 2]), 50000).ToList(); + foreach (var beforeStart in new[] { true, false }) + { + using var cancellation = new CancellationTokenSource(); + if (beforeStart) cancellation.Cancel(); + else cancellation.CancelAfter(10); + var solver = new MinerPlacementSolver(candidates, 3); + var work = solver.SearchAsync(int.MaxValue, 64, cancellation.Token); + try + { + work.GetAwaiter().GetResult(); + throw new InvalidOperationException("Cancelled worker search completed normally."); + } + catch (OperationCanceledException) { Check(work.IsCanceled, "Cancellation must join all parallel work before completing the task."); } + } + candidates.Clear(); + candidates.Add(Placement(0, [0, 1, 2])); + Check(Solve(candidates, 3).BestScore == 3, "A cancelled search must not interfere with the next calculation."); + } + + private static void ReplayChecks() + { + var original = NativeMiner(3.65f, -0.6f, 15); + original.Covered = [0, 1, 2]; + var record = MinerPlacementDebug.CandidateData.Capture(original); + var json = JsonSerializer.Serialize(record, ReplayJson); + record = JsonSerializer.Deserialize(json, ReplayJson); + var colliders = NativeColliders().Select(MinerPlacementDebug.Collider.Capture).ToArray(); + var restored = record.Restore(colliders.Take(3).ToArray(), colliders); + Check(restored.Position == original.Position && restored.Rotation == original.Rotation, "Replay must preserve the actual spherical pose."); + Check(restored.BuildBoxes.Zip(original.BuildBoxes).All(pair => pair.First.Center == pair.Second.Center && pair.First.Extents == pair.Second.Extents && pair.First.X == pair.Second.X && pair.First.Bounds == pair.Second.Bounds), "Replay must reconstruct each native collider exactly."); + Check(MinerPlacementSolver.Fits(restored, [NativeMiner(0)]), "Replay must preserve legal angled crossings."); + var snapshot = new MinerPlacementDebug.Snapshot + { + version = "test", gameVersion = "test", startedUtc = "2026-10-19T00:00:00Z", outcome = "completed", error = "", + planetId = 101, veinType = 1, veinGroup = 3, initialStock = 0, placedCount = 1, totalCoverage = 3, buriedCount = 0, + planetRadius = 200, buildRange = 80, unlimitedRange = true, elapsedMilliseconds = 1, + logicalProcessors = Environment.ProcessorCount, workerCount = MinerPlacementSolver.WorkerCount, + playerPosition = [0, 200, 0], center = [0, 200, 0], right = [1, 0, 0], forward = [0, 0, 1], + nodes = Enumerable.Range(1, 3).Select(id => new MinerPlacementDebug.Node + { + id = id, type = 1, target = true, visible = true, canBury = true, + originalPosition = [0, 200, 0], position = [0, 200, 0], collider = colliders[0] + }).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] }], + 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 } + }; + var path = Path.Combine(AppContext.BaseDirectory, "replay-smoke.json"); + MinerPlacementDebug.Write(path, snapshot); + var snapshotJson = File.ReadAllText(path); + using var document = JsonDocument.Parse(snapshotJson); + Check(document.RootElement.GetProperty("nodes").GetArrayLength() == 3 && + document.RootElement.GetProperty("candidates").GetArrayLength() == 4000 && + 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 && + 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.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); + } + + private static void Replay(string path) + { + var snapshot = JsonSerializer.Deserialize(File.ReadAllText(path), ReplayJson); + Check(snapshot.schema is 1 or 2, "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}"); + foreach (var failure in (snapshot.placements ?? []).Where(p => p.outcome != "placed").GroupBy(p => (p.outcome, p.nativeCondition))) + Console.WriteLine($"Placement {failure.Key.outcome}: native={failure.Key.nativeCondition}, count={failure.Count()}"); + var candidates = new List(); + var solver = new MinerPlacementSolver(candidates, snapshot.nodes.Length); + var parallel = new MinerPlacementSolver(candidates, snapshot.nodes.Length); + foreach (var phase in snapshot.phases) + { + 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); + 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(); + 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++) + { + Check(solver.Best[i].Covered.Count(n => !buried.Contains(n)) >= MinerPlacementSolver.MinimumCoverage, + "Replay selected a miner below the minimum coverage."); + Check(MinerPlacementSolver.Fits(solver.Best[i], solver.Best.Take(i).ToList()), "Replay selected colliding miners."); + } + 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"); + } + } + + public static void Main(string[] args) + { + if (args.Length > 0) { Replay(args[0]); return; } + GeometryChecks(); + SolverChecks(); + CancellationChecks(); + ReplayChecks(); + var desc = new PrefabDesc { veinMiner = true, minerType = EMinerType.Vein }; + var pose = new Pose(new Vector3(0, 200, 0), Quaternion.identity); + Check(MinerComponent.IsTargetVeinInRange(new Vector3(0, 200, -5), pose, desc), "Native rear mining sector must be covered."); + Check(!MinerComponent.IsTargetVeinInRange(new Vector3(0, 200, 5), pose, desc), "Front-facing resource must not be counted."); + Check(!MinerComponent.IsTargetVeinInRange(new Vector3(0, 200, -12), pose, desc), "Distant resource must not be counted."); + Check(!MinerComponent.IsTargetVeinInRange(new Vector3(5, 200, -4), pose, desc), "Resources outside the native sector angle must not be counted."); + var half = (float)Math.Sqrt(0.5); + pose = new Pose(new Vector3(200, 0, 0), new Quaternion(0, 0, -half, half)); + Check(MinerComponent.IsTargetVeinInRange(new Vector3(200, 0, -5), pose, desc), "Native range checks must work away from the north pole."); + Console.WriteLine($"Quick miner placement: {_checks} checks passed."); + } +} diff --git a/tools/tests/Test-QuickMinerPlacement.ps1 b/tools/tests/Test-QuickMinerPlacement.ps1 new file mode 100644 index 0000000..e7f9ea2 --- /dev/null +++ b/tools/tests/Test-QuickMinerPlacement.ps1 @@ -0,0 +1,63 @@ +#requires -Version 5.1 +# Runs the production geometry and solver against the original game assemblies, without Unity. +[CmdletBinding()] +param([string]$GameRoot, [string]$Snapshot) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' +$repoRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..\..')) +if (-not $GameRoot) { + $steamRoot = (Get-ItemProperty -LiteralPath 'HKCU:\Software\Valve\Steam' -Name SteamPath).SteamPath + $vdf = Get-Content -LiteralPath (Join-Path $steamRoot 'steamapps\libraryfolders.vdf') -Raw + foreach ($entry in [regex]::Matches($vdf, '"path"\s+"([^"]+)"')) { + $library = $entry.Groups[1].Value.Replace('\\', '\') + $candidate = Join-Path $library 'steamapps\common\Dyson Sphere Program' + if (Test-Path -LiteralPath (Join-Path $candidate 'DSPGAME_Data\Managed\Assembly-CSharp.dll')) { + $GameRoot = $candidate + break + } + } +} +if (-not $GameRoot) { throw 'DSP installation not found. Pass -GameRoot with the installed game directory.' } +$managed = Join-Path ([IO.Path]::GetFullPath($GameRoot)) 'DSPGAME_Data\Managed' +foreach ($name in @('Assembly-CSharp.dll', 'UnityEngine.CoreModule.dll')) { + if (-not (Test-Path -LiteralPath (Join-Path $managed $name))) { throw "Missing original game assembly: $name" } +} +$testRoot = Join-Path $repoRoot 'UXAssist\obj\quick-miner-tests' +$null = [IO.Directory]::CreateDirectory($testRoot) +# Isolate the temporary console project from the mod's SDK props, packages, and packaging targets. +Set-Content -LiteralPath (Join-Path $testRoot 'Directory.Build.props') -Value '' -Encoding UTF8 +Set-Content -LiteralPath (Join-Path $testRoot 'Directory.Build.targets') -Value '' -Encoding UTF8 +$geometry = [Security.SecurityElement]::Escape((Join-Path $repoRoot 'UXAssist\Functions\Factory\MinerPlacementGeometry.cs')) +$solver = [Security.SecurityElement]::Escape((Join-Path $repoRoot 'UXAssist\Functions\Factory\MinerPlacementSolver.cs')) +$debugData = [Security.SecurityElement]::Escape((Join-Path $repoRoot 'UXAssist\Functions\Factory\MinerPlacementDebug.cs')) +$tests = [Security.SecurityElement]::Escape((Join-Path $PSScriptRoot 'QuickMinerPlacementTests.cs')) +$originalDll = [Security.SecurityElement]::Escape((Join-Path $managed 'Assembly-CSharp.dll')) +$unityDll = [Security.SecurityElement]::Escape((Join-Path $managed 'UnityEngine.CoreModule.dll')) +$project = Join-Path $testRoot 'QuickMinerTests.csproj' +Set-Content -LiteralPath $project -Encoding UTF8 -Value @" + + + Exe + net8.0 + latest + false + true + + + + + + + + + + +"@ +if ($Snapshot) { + $snapshotPath = (Resolve-Path -LiteralPath $Snapshot).Path + & dotnet run --project $project -c Release -- $snapshotPath +} else { + & dotnet run --project $project -c Release +} +if ($LASTEXITCODE -ne 0) { throw "Quick miner placement checks failed (exit $LASTEXITCODE)." }