diff --git a/docs/public-api.md b/docs/public-api.md index e922bb6..19ccca1 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -91,6 +91,10 @@ and during triangle comparisons, including clearance tests. If cancelled, the ru `OperationCanceledException` and discards the results it added, preserving prior results and groups. The convenience methods register a test only after it completes. +Clash tests and matrix cells use a spatial index to find candidate pairs in selection order. +Each run reuses transformed vertices, and hard clash tests cull triangles outside the shared +region before testing for intersection. Proximity grouping finds nearby clashes with a spatial grid. + ## 4D TimeLiner, Selection Sets & Appearance (`NwcIO.Model.TimeLiner`, `.Sets`, `.Appearance`) | Type | Description | diff --git a/src/NwcIO/Compatibility/Clash/ClashGeometry.cs b/src/NwcIO/Compatibility/Clash/ClashGeometry.cs new file mode 100644 index 0000000..8daf9c2 --- /dev/null +++ b/src/NwcIO/Compatibility/Clash/ClashGeometry.cs @@ -0,0 +1,41 @@ +namespace NwcIO.Model.Clash; + +internal sealed class ClashGeometry(CancellationToken cancellationToken = default) +{ + private readonly Dictionary> _worldVertices = new(ReferenceEqualityComparer.Instance); + private readonly Dictionary _vertexBounds = new(ReferenceEqualityComparer.Instance); + + public IReadOnlyList GetVertices(NwcMesh mesh) + { + if (mesh.Transform is null) return mesh.Vertices; + if (!_worldVertices.TryGetValue(mesh, out var vertices)) + { + vertices = mesh.TransformVertices(cancellationToken); + _worldVertices.Add(mesh, vertices); + } + return vertices; + } + + public BoundingBox3d GetBounds(NwcMesh mesh) => mesh.GetWorldBoundingBox(GetVertices, cancellationToken); + + public BoundingBox3d GetVertexBounds(NwcMesh mesh, IReadOnlyList vertices) + { + if (!_vertexBounds.TryGetValue(mesh, out var bounds)) + { + bounds = BoundingBox3d.Empty; + for (int i = 0; i < vertices.Count; i++) + { + if ((i & 255) == 0) cancellationToken.ThrowIfCancellationRequested(); + bounds = bounds.Union(vertices[i]); + } + _vertexBounds.Add(mesh, bounds); + } + return bounds; + } + + public static BoundingBox3d Expand(BoundingBox3d bounds, double tolerance) + { + var offset = new Vector3d(tolerance, tolerance, tolerance); + return tolerance > 0 ? new BoundingBox3d(bounds.Min - offset, bounds.Max + offset) : bounds; + } +} diff --git a/src/NwcIO/Compatibility/Clash/NwcClashDetector.cs b/src/NwcIO/Compatibility/Clash/NwcClashDetector.cs index 2cee25a..b9928dd 100644 --- a/src/NwcIO/Compatibility/Clash/NwcClashDetector.cs +++ b/src/NwcIO/Compatibility/Clash/NwcClashDetector.cs @@ -1,5 +1,6 @@ using NwcIO.Internal.Export; using NwcIO.Model.Sets; +using NwcIO.Model.Spatial; namespace NwcIO.Model.Clash; @@ -133,18 +134,25 @@ private static void RunCore( meshesInB = new HashSet(meshesB, ReferenceEqualityComparer.Instance); } + var geometry = new ClashGeometry(cancellationToken); + NwcSpatialIndex? index = null; + var candidates = new List(); + double tol = Math.Max(0.0, test.Tolerance); for (int i = 0; i < meshesA.Count; i++) { ReportProgress(progress, i, meshesA.Count, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); var meshA = meshesA[i]; - var boxA = meshA.GetWorldBoundingBox(); + var boxA = geometry.GetBounds(meshA); if (boxA.IsEmpty) continue; bool canVisitReverse = !sameSelection && meshesInB!.Contains(meshA); - for (var j = sameSelection ? i + 1 : 0; j < meshesB.Count; j++) + index ??= new NwcSpatialIndex(meshesB, geometry.GetBounds, cancellationToken); + index.QueryBoxIndices(ClashGeometry.Expand(boxA, tol), candidates, cancellationToken); + foreach (int j in candidates) { cancellationToken.ThrowIfCancellationRequested(); + if (sameSelection && j <= i) continue; var meshB = meshesB[j]; if (ReferenceEquals(meshA, meshB) || meshA.Id == meshB.Id || IsSameElement(meshA, meshB)) continue; // The reverse pair was already visited from the earlier mesh in A. @@ -153,19 +161,10 @@ private static void RunCore( continue; } - var boxB = meshB.GetWorldBoundingBox(); - if (boxB.IsEmpty) continue; - - // Broad phase AABB - double tol = Math.Max(0.0, test.Tolerance); - var expandedA = tol > 0 - ? new BoundingBox3d(boxA.Min - new Vector3d(tol, tol, tol), boxA.Max + new Vector3d(tol, tol, tol)) - : boxA; - - if (!expandedA.Intersects(boxB)) continue; + var boxB = geometry.GetBounds(meshB); // Narrow phase: triangle intersection (Hard) or mesh distance (Clearance) - if (TryGetClash(test, meshA, meshB, cancellationToken, out var clashPoint, out double distance)) + if (TryGetClash(test, meshA, meshB, boxA, boxB, geometry, cancellationToken, out var clashPoint, out double distance)) { int clashIndex = test.Results.Count + 1; string clashName = $"Clash{clashIndex}"; @@ -239,18 +238,25 @@ private static void RunCoreMultiModel( } meshesInB = new HashSet(itemsB.Select(item => item.Mesh), ReferenceEqualityComparer.Instance); } + var geometry = new ClashGeometry(cancellationToken); + NwcSpatialIndex? index = null; + var candidates = new List(); + double tol = Math.Max(0.0, test.Tolerance); for (int i = 0; i < itemsA.Count; i++) { ReportProgress(progress, i, itemsA.Count, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); var itemA = itemsA[i]; - var boxA = itemA.Mesh.GetWorldBoundingBox(); + var boxA = geometry.GetBounds(itemA.Mesh); if (boxA.IsEmpty) continue; bool canVisitReverse = !sameSelection && meshesInB!.Contains(itemA.Mesh); - for (var j = sameSelection ? i + 1 : 0; j < itemsB.Count; j++) + index ??= new NwcSpatialIndex(itemsB.Select(item => item.Mesh).ToArray(), geometry.GetBounds, cancellationToken); + index.QueryBoxIndices(ClashGeometry.Expand(boxA, tol), candidates, cancellationToken); + foreach (int j in candidates) { cancellationToken.ThrowIfCancellationRequested(); + if (sameSelection && j <= i) continue; var itemB = itemsB[j]; if (ReferenceEquals(itemA.Mesh, itemB.Mesh) || IsSameElement(itemA.Mesh, itemB.Mesh)) continue; // Mesh IDs can repeat across models; only references identify pairs. @@ -259,17 +265,9 @@ private static void RunCoreMultiModel( continue; } - var boxB = itemB.Mesh.GetWorldBoundingBox(); - if (boxB.IsEmpty) continue; - - double tol = Math.Max(0.0, test.Tolerance); - var expandedA = tol > 0 - ? new BoundingBox3d(boxA.Min - new Vector3d(tol, tol, tol), boxA.Max + new Vector3d(tol, tol, tol)) - : boxA; + var boxB = geometry.GetBounds(itemB.Mesh); - if (!expandedA.Intersects(boxB)) continue; - - if (TryGetClash(test, itemA.Mesh, itemB.Mesh, cancellationToken, out var clashPoint, out double distance)) + if (TryGetClash(test, itemA.Mesh, itemB.Mesh, boxA, boxB, geometry, cancellationToken, out var clashPoint, out double distance)) { int clashIndex = test.Results.Count + 1; string clashName = $"Clash{clashIndex}"; @@ -331,6 +329,9 @@ private static bool TryGetClash( NwcClashTest test, NwcMesh meshA, NwcMesh meshB, + BoundingBox3d boxA, + BoundingBox3d boxB, + ClashGeometry geometry, CancellationToken cancellationToken, out Vector3d clashPoint, out double distance) @@ -348,26 +349,27 @@ private static bool TryGetClash( return false; } - var measurement = Measure.NwcMeasureEngine.MeasureMeshToMesh(meshA, meshB, useWorldCoordinates: true, cancellationToken); + var measurement = Measure.NwcMeasureEngine.MeasureMeshToMesh(meshA, meshB, + geometry.GetVertices(meshA), geometry.GetVertices(meshB), cancellationToken); clashPoint = (measurement.PointA + measurement.PointB) * 0.5; distance = measurement.Distance; return measurement.Distance <= tolerance; } case NwcClashTestType.Duplicates: - if (!IsDuplicate(meshA, meshB, tolerance, cancellationToken)) + if (!IsDuplicate(meshA, meshB, tolerance, geometry, cancellationToken)) { distance = 0; return false; } - clashPoint = (meshA.GetWorldBoundingBox().Center + meshB.GetWorldBoundingBox().Center) * 0.5; + clashPoint = (boxA.Center + boxB.Center) * 0.5; distance = 0; return true; case NwcClashTestType.Conservative: { - var overlap = meshA.GetWorldBoundingBox().Intersect(meshB.GetWorldBoundingBox()); + var overlap = boxA.Intersect(boxB); if (overlap.IsEmpty) { distance = 0; @@ -380,7 +382,7 @@ private static bool TryGetClash( } default: - if (CheckMeshIntersection(meshA, meshB, cancellationToken, out clashPoint, out double penetration)) + if (CheckMeshIntersection(meshA, meshB, boxA, boxB, geometry, cancellationToken, out clashPoint, out double penetration)) { // A zero-depth AABB overlap is a coplanar or touching surface; it is kept rather than // classified as a below-tolerance penetration. @@ -404,7 +406,7 @@ private static bool TryGetClash( /// Transform, name, id and material are ignored. /// internal static bool IsDuplicate( - NwcMesh meshA, NwcMesh meshB, double tolerance, CancellationToken cancellationToken = default) + NwcMesh meshA, NwcMesh meshB, double tolerance, ClashGeometry? geometry = null, CancellationToken cancellationToken = default) { if (ReferenceEquals(meshA, meshB)) { @@ -417,8 +419,9 @@ internal static bool IsDuplicate( return false; } - var verticesA = meshA.GetWorldVertices(); - var verticesB = meshB.GetWorldVertices(); + geometry ??= new ClashGeometry(cancellationToken); + var verticesA = geometry.GetVertices(meshA); + var verticesB = geometry.GetVertices(meshB); if (verticesA.Count != verticesB.Count) { return false; @@ -460,6 +463,9 @@ internal static bool IsDuplicate( private static bool CheckMeshIntersection( NwcMesh a, NwcMesh b, + BoundingBox3d boxA, + BoundingBox3d boxB, + ClashGeometry geometry, CancellationToken cancellationToken, out Vector3d clashPoint, out double penetrationDepth) @@ -473,14 +479,12 @@ private static bool CheckMeshIntersection( return false; } - var vertsA = a.GetWorldVertices(); - var vertsB = b.GetWorldVertices(); + var vertsA = geometry.GetVertices(a); + var vertsB = geometry.GetVertices(b); if (vertsA.Count < 3 || vertsB.Count < 3) { // Fallback to bounding box overlap - var boxA = a.GetWorldBoundingBox(); - var boxB = b.GetWorldBoundingBox(); if (boxA.Intersects(boxB)) { var overlap = new BoundingBox3d( @@ -495,29 +499,34 @@ private static bool CheckMeshIntersection( var indicesA = a.Indices.Count >= 3 ? a.Indices : CreateDefaultIndices(vertsA.Count); var indicesB = b.Indices.Count >= 3 ? b.Indices : CreateDefaultIndices(vertsB.Count); + var geometryBoxA = geometry.GetVertexBounds(a, vertsA); + var geometryBoxB = geometry.GetVertexBounds(b, vertsB); + double planeTolerance = NwcTriangleIntersection.Epsilon * Math.Max(geometryBoxA.Size.Length, geometryBoxB.Size.Length); + var trianglesA = FilterTriangles(vertsA, indicesA, geometryBoxB, planeTolerance, cancellationToken); + using var remainingB = FilterTriangles(vertsB, indicesB, geometryBoxA, planeTolerance, cancellationToken).GetEnumerator(); + var trianglesB = new List<(int A, int B, int C)>(); + bool moreB = true; var intersectionPoints = new List(); - for (int i = 0; i + 2 < indicesA.Count; i += 3) + foreach (var (ia0, ia1, ia2) in trianglesA) { cancellationToken.ThrowIfCancellationRequested(); - int ia0 = indicesA[i]; - int ia1 = indicesA[i + 1]; - int ia2 = indicesA[i + 2]; - if (ia0 >= vertsA.Count || ia1 >= vertsA.Count || ia2 >= vertsA.Count) continue; - var v0 = vertsA[ia0]; var v1 = vertsA[ia1]; var v2 = vertsA[ia2]; - for (int j = 0; j + 2 < indicesB.Count; j += 3) + for (int j = 0; j < trianglesB.Count || moreB; j++) { - if (j % (3 * 256) == 0) cancellationToken.ThrowIfCancellationRequested(); - int ib0 = indicesB[j]; - int ib1 = indicesB[j + 1]; - int ib2 = indicesB[j + 2]; - if (ib0 >= vertsB.Count || ib1 >= vertsB.Count || ib2 >= vertsB.Count) continue; - + if ((j & 255) == 0) cancellationToken.ThrowIfCancellationRequested(); + if (j == trianglesB.Count) + { + // Keep candidates already read for the next triangle, while allowing the tenth hit to stop the scan. + moreB = remainingB.MoveNext(); + if (!moreB) break; + trianglesB.Add(remainingB.Current); + } + var (ib0, ib1, ib2) = trianglesB[j]; var u0 = vertsB[ib0]; var u1 = vertsB[ib1]; var u2 = vertsB[ib2]; @@ -528,7 +537,7 @@ private static bool CheckMeshIntersection( if (intersectionPoints.Count >= 10) break; // Limit sampling for performance } } - if (intersectionPoints.Count >= 10) break; + if (intersectionPoints.Count >= 10 || trianglesB.Count == 0) break; } if (intersectionPoints.Count > 0) @@ -537,8 +546,6 @@ private static bool CheckMeshIntersection( for (int p = 0; p < intersectionPoints.Count; p++) sum += intersectionPoints[p]; clashPoint = sum / (double)intersectionPoints.Count; - var boxA = a.GetWorldBoundingBox(); - var boxB = b.GetWorldBoundingBox(); var overlapSize = new Vector3d( Math.Max(0.0, Math.Min(boxA.Max.X, boxB.Max.X) - Math.Max(boxA.Min.X, boxB.Min.X)), Math.Max(0.0, Math.Min(boxA.Max.Y, boxB.Max.Y) - Math.Max(boxA.Min.Y, boxB.Min.Y)), @@ -550,6 +557,44 @@ private static bool CheckMeshIntersection( return false; } + private static IEnumerable<(int A, int B, int C)> FilterTriangles(IReadOnlyList vertices, IReadOnlyList indices, + BoundingBox3d otherBounds, double planeTolerance, CancellationToken cancellationToken) + { + for (int i = 0; i + 2 < indices.Count; i += 3) + { + if (i % (3 * 256) == 0) cancellationToken.ThrowIfCancellationRequested(); + int a = indices[i]; + int b = indices[i + 1]; + int c = indices[i + 2]; + if ((uint)a >= (uint)vertices.Count || (uint)b >= (uint)vertices.Count || (uint)c >= (uint)vertices.Count) + { + continue; + } + + var v0 = vertices[a]; + var v1 = vertices[b]; + var v2 = vertices[c]; + var bounds = new BoundingBox3d(v0, v0).Union(v1).Union(v2); + if (!bounds.Intersects(otherBounds)) + { + var ab = v1 - v0; + var ac = v2 - v0; + double twiceArea = Vector3d.Cross(ab, ac).Length; + if (twiceArea == 0) continue; + double lengthAB = ab.Length, lengthAC = ac.Length, lengthBC = (v2 - v1).Length; + double longestEdge = Math.Max(lengthAB, Math.Max(lengthAC, lengthBC)); + double inradius = twiceArea / (lengthAB + lengthAC + lengthBC); + // The coplanar test allows a gap along each projected edge normal. Expanding the + // triangle about its incenter bounds that gap, including at narrow corners. + // Dominant-axis projection and lifting back to 3D cost at most 8x, plus plane separation. + double padding = planeTolerance * (8 * longestEdge / inradius + 2); + if (double.IsFinite(padding) && otherBounds.Intersects(otherBounds) && + !ClashGeometry.Expand(bounds, padding).Intersects(otherBounds)) continue; + } + yield return (a, b, c); + } + } + // Fragments of one element are separate meshes and never clash with each other. The element key works without // the scene tree; the node rule covers documents built in code. internal static bool IsSameElement(NwcMesh a, NwcMesh b) => diff --git a/src/NwcIO/Compatibility/Clash/NwcClashGrouper.cs b/src/NwcIO/Compatibility/Clash/NwcClashGrouper.cs index 835874a..1764032 100644 --- a/src/NwcIO/Compatibility/Clash/NwcClashGrouper.cs +++ b/src/NwcIO/Compatibility/Clash/NwcClashGrouper.cs @@ -57,23 +57,57 @@ void Union(int i, int j) } } - // Pairwise proximity check + var cells = new Dictionary<(long X, long Y, long Z), List>(); + var unindexed = new List(); + // The extra half-cell leaves room for rounding at an exact radius or a cell boundary. + double cellSize = 2 * clusterDistance; for (int i = 0; i < n; i++) { - var p1 = results[i].ClashPoint; - for (int j = i + 1; j < n; j++) + var p = results[i].ClashPoint; + if (!double.IsNormal(distSqThreshold) || + !TryCell(p.X, out long x) || !TryCell(p.Y, out long y) || !TryCell(p.Z, out long z)) { - var p2 = results[j].ClashPoint; - double dx = p1.X - p2.X; - double dy = p1.Y - p2.Y; - double dz = p1.Z - p2.Z; - double dSq = dx * dx + dy * dy + dz * dz; + // Preserve the distance comparison for extreme quotients or a squared radius + // that overflowed or underflowed. + for (int j = 0; j < i; j++) JoinIfClose(i, j); + unindexed.Add(i); + continue; + } - if (dSq <= distSqThreshold) + foreach (int j in unindexed) JoinIfClose(i, j); + for (long cz = z - 1; cz <= z + 1; cz++) + { + for (long cy = y - 1; cy <= y + 1; cy++) { - Union(i, j); + for (long cx = x - 1; cx <= x + 1; cx++) + { + if (!cells.TryGetValue((cx, cy, cz), out var neighbors)) continue; + foreach (int j in neighbors) JoinIfClose(i, j); + } } } + + if (!cells.TryGetValue((x, y, z), out var bucket)) cells.Add((x, y, z), bucket = []); + bucket.Add(i); + } + + bool TryCell(double coordinate, out long cell) + { + double scaled = coordinate / cellSize; + // At larger quotients the cell division can lose precision even before flooring. + const double maxExactCell = 1L << 50; + cell = 0; + if (!(Math.Abs(scaled) < maxExactCell)) return false; + cell = (long)Math.Floor(scaled); + return true; + } + + void JoinIfClose(int i, int j) + { + if ((results[j].ClashPoint - results[i].ClashPoint).LengthSquared <= distSqThreshold) + { + Union(j, i); + } } // Group indices by root diff --git a/src/NwcIO/Compatibility/Clash/NwcClashMatrix.cs b/src/NwcIO/Compatibility/Clash/NwcClashMatrix.cs index daba404..644fa78 100644 --- a/src/NwcIO/Compatibility/Clash/NwcClashMatrix.cs +++ b/src/NwcIO/Compatibility/Clash/NwcClashMatrix.cs @@ -3,6 +3,7 @@ using System.Text.Json; using NwcIO.Internal.Export; using NwcIO.Model.Sets; +using NwcIO.Model.Spatial; namespace NwcIO.Model.Clash; @@ -203,6 +204,8 @@ public void Run(NwcAssembly assembly) keyByDocument[assembly.Models[i]] = modelKeys[i]; } + var geometry = new ClashGeometry(); + var candidates = new List(); foreach (var cell in Cells) { if (!cell.Enabled) continue; @@ -228,20 +231,42 @@ public void Run(NwcAssembly assembly) var test = new NwcClashTest(testName, cell.TestType, cell.Tolerance); test.Rules.AddRange(GlobalRules); - // Execute pair detection with spatial pruning + var selectionB = meshesB.Select(item => item.mesh).ToArray(); + bool clearance = cell.TestType == NwcClashTestType.Clearance; + bool duplicates = cell.TestType == NwcClashTestType.Duplicates; + double tolerance = Math.Max(0.0, cell.Tolerance); + // BoxGap squares the axis differences. Round outward so underflow or rounding + // at the clearance threshold cannot exclude a pair before that test. + double searchRadius = clearance + ? Math.BitIncrement(Math.Sqrt(Math.BitIncrement(tolerance * tolerance))) + : duplicates ? tolerance : 0; + bool unboundedClearance = clearance && (!double.IsFinite(searchRadius) || + selectionB.Any(mesh => HasNonFiniteBounds(geometry.GetBounds(mesh)))); + var index = unboundedClearance ? null : new NwcSpatialIndex(selectionB, geometry.GetBounds, default); int clashId = 1; for (int i = 0; i < meshesA.Count; i++) { var (mA, docA) = meshesA[i]; - var boxA = mA.GetWorldBoundingBox(); + var boxA = geometry.GetBounds(mA); int startJ = (cell.DisciplineA == cell.DisciplineB) ? i + 1 : 0; - for (int j = startJ; j < meshesB.Count; j++) + if (unboundedClearance || clearance && HasNonFiniteBounds(boxA)) { + candidates.Clear(); + for (int j = startJ; j < meshesB.Count; j++) candidates.Add(j); + } + else + { + index!.QueryBoxIndices(ClashGeometry.Expand(boxA, searchRadius), candidates); + } + + foreach (int j in candidates) + { + if (j < startJ) continue; var (mB, docB) = meshesB[j]; if ((mA.Id == mB.Id && docA == docB) || NwcClashDetector.IsSameElement(mA, mB)) continue; - var boxB = mB.GetWorldBoundingBox(); + var boxB = geometry.GetBounds(mB); var interBox = boxA.Intersect(boxB); double penetration; @@ -265,9 +290,7 @@ public void Run(NwcAssembly assembly) continue; } - double dupTol = Math.Max(0.0, cell.Tolerance); - var expandedA = new BoundingBox3d(boxA.Min - new Vector3d(dupTol, dupTol, dupTol), boxA.Max + new Vector3d(dupTol, dupTol, dupTol)); - if (!expandedA.Intersects(boxB) || !NwcClashDetector.IsDuplicate(mA, mB, dupTol)) + if (double.IsNaN(tolerance) || !NwcClashDetector.IsDuplicate(mA, mB, tolerance, geometry)) { continue; } @@ -451,6 +474,10 @@ public void SaveJson(string filePath, bool indent = true) writer.Flush(); } + private static bool HasNonFiniteBounds(BoundingBox3d box) => !box.IsEmpty && + (!double.IsFinite(box.Min.X) || !double.IsFinite(box.Min.Y) || !double.IsFinite(box.Min.Z) || + !double.IsFinite(box.Max.X) || !double.IsFinite(box.Max.Y) || !double.IsFinite(box.Max.Z)); + /// Shortest distance between two axis-aligned boxes (zero when they intersect). private static double BoxGap(BoundingBox3d a, BoundingBox3d b) { diff --git a/src/NwcIO/Compatibility/Clash/NwcTriangleIntersection.cs b/src/NwcIO/Compatibility/Clash/NwcTriangleIntersection.cs index 21c0711..d86384f 100644 --- a/src/NwcIO/Compatibility/Clash/NwcTriangleIntersection.cs +++ b/src/NwcIO/Compatibility/Clash/NwcTriangleIntersection.cs @@ -6,7 +6,7 @@ namespace NwcIO.Model.Clash; /// internal static class NwcTriangleIntersection { - private const double Epsilon = 1e-7; + internal const double Epsilon = 1e-7; /// /// Tests whether two 3D triangles intersect and returns the approximate intersection point. diff --git a/src/NwcIO/Compatibility/Measure/NwcMeasureEngine.cs b/src/NwcIO/Compatibility/Measure/NwcMeasureEngine.cs index 0e77e39..e83632e 100644 --- a/src/NwcIO/Compatibility/Measure/NwcMeasureEngine.cs +++ b/src/NwcIO/Compatibility/Measure/NwcMeasureEngine.cs @@ -279,7 +279,7 @@ public static NwcMeshToMeshMeasurement MeasureMeshToMesh( NwcMesh meshA, NwcMesh meshB, bool useWorldCoordinates, NwcLengthUnit lengthUnit) => MeasureMeshToMesh(meshA, meshB, useWorldCoordinates, cancellationToken: default) with { LengthUnit = lengthUnit }; - internal static NwcMeshToMeshMeasurement MeasureMeshToMesh( + private static NwcMeshToMeshMeasurement MeasureMeshToMesh( NwcMesh meshA, NwcMesh meshB, bool useWorldCoordinates, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(meshA); @@ -287,7 +287,12 @@ internal static NwcMeshToMeshMeasurement MeasureMeshToMesh( var vertsA = useWorldCoordinates ? meshA.GetWorldVertices() : meshA.Vertices; var vertsB = useWorldCoordinates ? meshB.GetWorldVertices() : meshB.Vertices; + return MeasureMeshToMesh(meshA, meshB, vertsA, vertsB, cancellationToken); + } + internal static NwcMeshToMeshMeasurement MeasureMeshToMesh(NwcMesh meshA, NwcMesh meshB, + IReadOnlyList vertsA, IReadOnlyList vertsB, CancellationToken cancellationToken) + { var indicesA = meshA.Indices; var indicesB = meshB.Indices; diff --git a/src/NwcIO/Compatibility/Spatial/NwcSpatialIndex.cs b/src/NwcIO/Compatibility/Spatial/NwcSpatialIndex.cs index c1f3a54..ce9dabe 100644 --- a/src/NwcIO/Compatibility/Spatial/NwcSpatialIndex.cs +++ b/src/NwcIO/Compatibility/Spatial/NwcSpatialIndex.cs @@ -17,7 +17,10 @@ public sealed class NwcSpatialIndex public int MaxDepth { get; private set; } public BoundingBox3d Bounds => _root?.Bounds ?? BoundingBox3d.Empty; - public NwcSpatialIndex(IReadOnlyList meshes) + public NwcSpatialIndex(IReadOnlyList meshes) : this(meshes, null, default) { } + + internal NwcSpatialIndex(IReadOnlyList meshes, Func? getBounds, + CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(meshes); @@ -25,8 +28,11 @@ public NwcSpatialIndex(IReadOnlyList meshes) for (int i = 0; i < meshes.Count; i++) { var m = meshes[i]; - var b = m.GetWorldBoundingBox(); - _entries[i] = new MeshEntry(m, b, b.Center); + cancellationToken.ThrowIfCancellationRequested(); + var b = getBounds is null ? m.GetWorldBoundingBox() : getBounds(m); + // A NaN box cannot intersect a clash query and would poison its BVH's parent bounds. + if (getBounds is not null && !b.Intersects(b)) b = BoundingBox3d.Empty; + _entries[i] = new MeshEntry(m, b, b.Center, i); } if (_entries.Length > 0) @@ -35,7 +41,7 @@ public NwcSpatialIndex(IReadOnlyList meshes) int leafCount = 0; int maxDepth = 0; - _root = BuildNode(0, _entries.Length, 1, ref nodeCount, ref leafCount, ref maxDepth); + _root = BuildNode(0, _entries.Length, 1, ref nodeCount, ref leafCount, ref maxDepth, cancellationToken); NodeCount = nodeCount; LeafCount = leafCount; @@ -54,12 +60,24 @@ public IReadOnlyList QueryBox(BoundingBox3d box) } var results = new List(); - QueryBoxRecursive(_root, box, results); + QueryBoxRecursive(_root, box, results, static entry => entry.Mesh, default); return results; } - private void QueryBoxRecursive(BvhNode node, BoundingBox3d box, List results) + internal void QueryBoxIndices(BoundingBox3d box, List results, CancellationToken cancellationToken = default) + { + results.Clear(); + if (_root is not null && !box.IsEmpty) + { + QueryBoxRecursive(_root, box, results, static entry => entry.Index, cancellationToken); + results.Sort(); + } + } + + private void QueryBoxRecursive(BvhNode node, BoundingBox3d box, List results, + Func select, CancellationToken cancellationToken) { + cancellationToken.ThrowIfCancellationRequested(); if (!node.Bounds.Intersects(box)) { return; @@ -69,16 +87,16 @@ private void QueryBoxRecursive(BvhNode node, BoundingBox3d box, List re { for (int i = node.StartIndex; i < node.StartIndex + node.Count; i++) { - if (_entries[i].Bounds.Intersects(box)) + if (!_entries[i].Bounds.IsEmpty && _entries[i].Bounds.Intersects(box)) { - results.Add(_entries[i].Mesh); + results.Add(select(_entries[i])); } } return; } - if (node.Left is not null) QueryBoxRecursive(node.Left, box, results); - if (node.Right is not null) QueryBoxRecursive(node.Right, box, results); + if (node.Left is not null) QueryBoxRecursive(node.Left, box, results, select, cancellationToken); + if (node.Right is not null) QueryBoxRecursive(node.Right, box, results, select, cancellationToken); } /// @@ -355,8 +373,10 @@ private BvhNode BuildNode( int depth, ref int totalNodes, ref int totalLeaves, - ref int maxDepth) + ref int maxDepth, + CancellationToken cancellationToken) { + cancellationToken.ThrowIfCancellationRequested(); totalNodes++; if (depth > maxDepth) maxDepth = depth; @@ -389,8 +409,8 @@ private BvhNode BuildNode( int mid = start + count / 2; Array.Sort(_entries, start, count, new CentroidComparer(axis)); - var left = BuildNode(start, mid - start, depth + 1, ref totalNodes, ref totalLeaves, ref maxDepth); - var right = BuildNode(mid, start + count - mid, depth + 1, ref totalNodes, ref totalLeaves, ref maxDepth); + var left = BuildNode(start, mid - start, depth + 1, ref totalNodes, ref totalLeaves, ref maxDepth, cancellationToken); + var right = BuildNode(mid, start + count - mid, depth + 1, ref totalNodes, ref totalLeaves, ref maxDepth, cancellationToken); return new BvhNode { @@ -402,7 +422,7 @@ private BvhNode BuildNode( }; } - private readonly record struct MeshEntry(NwcMesh Mesh, BoundingBox3d Bounds, Vector3d Centroid); + private readonly record struct MeshEntry(NwcMesh Mesh, BoundingBox3d Bounds, Vector3d Centroid, int Index); private sealed class CentroidComparer : IComparer { diff --git a/src/NwcIO/Model/NwcMesh.cs b/src/NwcIO/Model/NwcMesh.cs index 33ae306..9d89a4c 100644 --- a/src/NwcIO/Model/NwcMesh.cs +++ b/src/NwcIO/Model/NwcMesh.cs @@ -77,7 +77,10 @@ public NwcTransform? Transform /// /// Gets the axis-aligned bounding box of the mesh in world space coordinates. /// - public BoundingBox3d GetWorldBoundingBox() + public BoundingBox3d GetWorldBoundingBox() => GetWorldBoundingBox(null); + + internal BoundingBox3d GetWorldBoundingBox(Func>? getVertices, + CancellationToken cancellationToken = default) { if (_cachedWorldBounds.HasValue) { @@ -93,7 +96,7 @@ public BoundingBox3d GetWorldBoundingBox() } } - var worldVerts = GetWorldVertices(); + var worldVerts = getVertices is null ? GetWorldVertices() : getVertices(this); if (worldVerts.Count == 0) { _cachedWorldBounds = BoundingBox3d.Empty; @@ -105,6 +108,7 @@ public BoundingBox3d GetWorldBoundingBox() for (int i = 0; i < worldVerts.Count; i++) { + if ((i & 255) == 0) cancellationToken.ThrowIfCancellationRequested(); var v = worldVerts[i]; if (v.X < minX) minX = v.X; if (v.Y < minY) minY = v.Y; @@ -123,7 +127,9 @@ public BoundingBox3d GetWorldBoundingBox() /// Returns vertices transformed into world space coordinates by . /// If no transform is assigned, returns . /// - public IReadOnlyList GetWorldVertices() + public IReadOnlyList GetWorldVertices() => TransformVertices(default); + + internal IReadOnlyList TransformVertices(CancellationToken cancellationToken) { if (Transform is null) { @@ -134,6 +140,7 @@ public IReadOnlyList GetWorldVertices() var world = new Vector3d[Vertices.Count]; for (int i = 0; i < Vertices.Count; i++) { + if ((i & 255) == 0) cancellationToken.ThrowIfCancellationRequested(); var v = Vertices[i]; double wx = v.X * m[0] + v.Y * m[4] + v.Z * m[8] + m[12]; double wy = v.X * m[1] + v.Y * m[5] + v.Z * m[9] + m[13]; diff --git a/tests/NwcIO.Tests/ClashDetectiveTests.cs b/tests/NwcIO.Tests/ClashDetectiveTests.cs index e018e1c..665a844 100644 --- a/tests/NwcIO.Tests/ClashDetectiveTests.cs +++ b/tests/NwcIO.Tests/ClashDetectiveTests.cs @@ -1311,6 +1311,102 @@ public void ClashDetection_EmptySelection_ReportsCompletionOnce() Assert.Same(test, Assert.Single(assembly.ClashTests)); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ClashDetection_SpatialQueriesPreserveBruteForceOrder(bool federated) + { + double[] offsets = [20, 0, 1, 21, 40, 20.5, 0.5, 19]; + var meshes = offsets.Select((x, i) => new NwcMesh + { + Id = i, + Vertices = [new(0, 0, 0), new(2, 0, 0), new(0, 2, 0)], + Indices = [0, 1, 2], + Transform = new NwcTransform { Id = i, Translation = new Vector3d(x, 0, 0) }, + }).ToArray(); + var expected = (from a in meshes + from b in meshes + where a.Id < b.Id && Math.Abs(offsets[a.Id] - offsets[b.Id]) <= 2 + select (a.Id, b.Id)).ToArray(); + var test = new NwcClashTest("Reference", NwcClashTestType.Hard, tolerance: 0); + if (federated) + { + var assembly = NwcAssembly.Create("Federation", NwcDocument.Create(meshes: meshes[..4]), + NwcDocument.Create(meshes: meshes[4..])); + NwcClashDetector.Run(assembly, test); + } + else + { + NwcClashDetector.Run(NwcDocument.Create(meshes: meshes), test); + } + + Assert.Equal(expected, test.Results.Select(result => (result.Item1.Mesh!.Id, result.Item2.Mesh!.Id))); + for (int i = 0; i < test.Results.Count; i++) + { + var result = test.Results[i]; + var (a, b) = expected[i]; + Assert.Equal($"Clash{i + 1}", result.Name); + Assert.Equal((offsets[a] + offsets[b]) * 0.5 + 2.0 / 3, result.ClashPoint.X, 12); + Assert.Equal(2.0 / 3, result.ClashPoint.Y, 12); + Assert.Equal(0, result.Distance); + } + } + + [Theory] + [InlineData(NwcClashTestType.Hard)] + [InlineData(NwcClashTestType.Clearance)] + [InlineData(NwcClashTestType.Duplicates)] + public void ClashDetection_TransformsEachMeshOnlyOncePerRun(NwcClashTestType type) + { + var vertices = new CountingVertices([new(0, 0, 0), new(2, 0, 0), new(0, 2, 0)]); + var meshes = Enumerable.Range(0, 4).Select(i => new NwcMesh + { + Id = i, + Vertices = vertices, + Indices = [0, 1, 2], + }).ToArray(); + var doc = NwcDocument.Create(meshes: meshes); + foreach (var mesh in meshes) mesh.Transform = new NwcTransform { Id = mesh.Id, Translation = new(5, 0, 0) }; + int before = vertices.Reads; + + var test = NwcClashDetector.Run(doc, new NwcClashTest("Cached", type)); + + Assert.Equal(6, test.Results.Count); + Assert.Equal(meshes.Length * vertices.Count, vertices.Reads - before); + } + + [Fact] + public void ClashDetection_TriangleCullingPreservesNearCoplanarContact() + { + var a = new NwcMesh { Id = 1, Vertices = [new(0, 0, 0), new(2, 0, 0), new(0, 2, 0)], Indices = [0, 1, 2] }; + var b = new NwcMesh + { + Id = 2, + Vertices = [new(0, 0, 1e-7), new(2, 0, 1e-7), new(0, 2, 1e-7), new(0, 0, 0)], + Indices = [0, 1, 2], + }; + + var test = NwcClashDetector.Run(NwcDocument.Create(meshes: [a, b]), new NwcClashTest("Coplanar")); + + Assert.Equal(5e-8, Assert.Single(test.Results).ClashPoint.Z, 15); + } + + private sealed class CountingVertices(Vector3d[] values) : IReadOnlyList + { + public int Count => values.Length; + public int Reads { get; private set; } + public Vector3d this[int index] + { + get + { + Reads++; + return values[index]; + } + } + public IEnumerator GetEnumerator() => ((IEnumerable)values).GetEnumerator(); + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + } + private sealed class ClashProgress(Action report) : IProgress { public void Report(NwcProgress value) => report(value); diff --git a/tests/NwcIO.Tests/ClashGroupingTests.cs b/tests/NwcIO.Tests/ClashGroupingTests.cs index 6b184f8..0cc8049 100644 --- a/tests/NwcIO.Tests/ClashGroupingTests.cs +++ b/tests/NwcIO.Tests/ClashGroupingTests.cs @@ -220,6 +220,21 @@ public void GroupByProximity_ClustersNearbyClashesIntoGroups() Assert.Equal(-0.12, g2.Distance); // Worst penetration } + [Fact] + public void GroupByProximity_KeepsTransitiveClustersAndInputOrderAcrossCells() + { + var test = new NwcClashTest("Grid"); + double[] coordinates = [2, -1, 30, 0, 1, 31, 40, 1e20, 1e20]; + var clashes = coordinates.Select((x, i) => CreateClash($"Clash {i}", new Vector3d(x, 0, 0), 0)).ToArray(); + test.Results.AddRange(clashes); + + Assert.Equal(3, NwcClashGrouper.GroupByProximity(test, clusterDistance: 1)); + Assert.Equal([clashes[0], clashes[1], clashes[3], clashes[4]], test.Groups[0].Clashes); + Assert.Equal([clashes[2], clashes[5]], test.Groups[1].Clashes); + Assert.Equal([clashes[7], clashes[8]], test.Groups[2].Clashes); + Assert.Same(clashes[6], Assert.Single(test.Results)); + } + [Fact] public void GroupByPrimaryElement_BundlesByItem1() { diff --git a/tests/NwcIO.Tests/ClashMatrixTests.cs b/tests/NwcIO.Tests/ClashMatrixTests.cs index 9a7fbf2..bbc673f 100644 --- a/tests/NwcIO.Tests/ClashMatrixTests.cs +++ b/tests/NwcIO.Tests/ClashMatrixTests.cs @@ -88,6 +88,7 @@ public void Matrix_DisciplineTests_DetectsCrossModelConflicts() [InlineData(0.0, 0.001, NwcClashTestType.Hard, 0)] // touching boxes are not a Hard clash with a positive tolerance [InlineData(0.0, 0.0, NwcClashTestType.Hard, 1)] [InlineData(0.0005, 0.001, NwcClashTestType.Clearance, 1)] + [InlineData(0.5, 0.5, NwcClashTestType.Clearance, 1)] [InlineData(0.002, 0.001, NwcClashTestType.Clearance, 0)] public void Matrix_Tolerance_AppliesToTestType(double gap, double tolerance, NwcClashTestType type, int expected) {