mirror of
https://github.com/soarqin/DSP_Mods.git
synced 2026-11-19 17:05:20 +08:00
feat(uxassist): add dense mining machine placement
This commit is contained in:
1 parent
94e5c7884b
commit
3ed616ce80
13 files changed
+2083
-3
No files matched your search
@@ -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]);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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<Candidate> _candidates;
|
||||
private readonly int _nodeCount;
|
||||
private int _bestBuriedCount;
|
||||
public List<Candidate> Best { get; private set; } = [];
|
||||
public int BestScore { get; private set; }
|
||||
|
||||
public MinerPlacementSolver(List<Candidate> 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<Candidate>(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<Candidate> seeds, SearchResult[] results, int resultIndex, CancellationToken cancellationToken)
|
||||
{
|
||||
var selected = new List<Candidate>();
|
||||
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<int, IEnumerator> 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<Candidate> selected, int score, int buriedCount)
|
||||
{
|
||||
public List<Candidate> 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<Candidate>(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<int>();
|
||||
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<Candidate> seeds, (int, int, int) region, bool[][] fits,
|
||||
SearchResult result, CancellationToken cancellationToken)
|
||||
{
|
||||
var state = new PartialLayout(_nodeCount);
|
||||
var removed = new List<Candidate>();
|
||||
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<Candidate>(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<Candidate> 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<Candidate>(state.Selected);
|
||||
result.Score = state.Score;
|
||||
result.BuriedCount = state.BuriedCount;
|
||||
}
|
||||
|
||||
private static int CountBuried(List<Candidate> selected)
|
||||
{
|
||||
var buried = new HashSet<int>();
|
||||
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<Candidate> 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<Candidate> 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<Candidate> 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;
|
||||
}
|
||||
}
|
||||
@@ -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<Node> _nodes = [];
|
||||
private readonly List<ColliderData> _obstacles = [];
|
||||
private readonly List<Candidate> _candidates = [];
|
||||
private readonly List<int> _covered = [], _buried = [];
|
||||
private readonly Box[] _buildBoxes, _obstacleBoxes;
|
||||
private readonly ColliderData[] _nativeObstacles;
|
||||
private readonly float _footprintRadius;
|
||||
private readonly MinerPlacementDebug.Snapshot _debug = new();
|
||||
private readonly List<MinerPlacementDebug.Phase> _phases = [];
|
||||
private readonly List<MinerPlacementDebug.Placement> _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<ColliderData>();
|
||||
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<MinerPlacementDebug.ExistingMiner>();
|
||||
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<int> ReservedNodes()
|
||||
{
|
||||
var reserved = new HashSet<int>();
|
||||
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<Candidate> 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<Candidate> 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<Candidate> 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<int, Vector3>();
|
||||
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<int>();
|
||||
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<int>();
|
||||
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<Candidate> 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<int> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user