diff --git a/docs/tools-changelog.md b/docs/tools-changelog.md index d457ab2..7cd8eaf 100644 --- a/docs/tools-changelog.md +++ b/docs/tools-changelog.md @@ -3,7 +3,8 @@ ## [0.1.0-preview.1] - `IOScene.Formats` reads embedded GLB and OBJ geometry and writes GLB from an IOScene document. -- `IOCoord` provides measurements, triangle surface intersections and clearance, grid queries, revision comparison and BCF 2.1 export. +- `IOCoord` provides measurements, surface clearance, hard clashes with an estimated depth, box overlap checks, + duplicate geometry detection, grid queries, revision comparison and BCF 2.1 export. - Both packages use the public IOScene 0.1 API and can be installed independently. See [Optional IOScene tools](tools.md) for supported inputs and scope. diff --git a/docs/tools.md b/docs/tools.md index fa5ecd5..0b37611 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -49,8 +49,16 @@ box hierarchy narrows the triangle pairs, and a surface check finds a contact po pair. It returns a `SceneClashTest` for export or review, with a contact tolerance of one nanometre. `SceneClash.FindSurfaceClearances` returns the shortest gap between the placed triangle surfaces of each element pair within an inclusive limit in metres. The result includes the distance and the midpoint of the -gap. Surface contacts report zero using the same tolerance. Solid containment and penetration depth require -different queries. +gap. Surface contacts report zero using the same tolerance. + +`SceneClash.FindHardClashes` checks triangle contact and estimates depth from the minimum side of the overlap +of the two contacting mesh bounds, as in NwcIO. It reports negative depth in metres, skips positive depths +below the requested minimum, and keeps zero-depth contacts. `SceneClash.FindBoundingBoxOverlaps` uses the same +overlap metric and reports the centre of overlapping instance boxes without checking their surfaces. A box +overlap can include empty space. Exact depth and closed-solid containment are outside these queries. + +`SceneClash.FindDuplicates` compares placed vertices and effective index order within a tolerance in metres. +It reports a pair when any two of its instances match, independent of material and display name. `SceneDiff.Compare` matches elements by model key and source id. It compares names and types, ordered property sets, and ordered vertices and indices in scene coordinates. It reports elements without an identity separately and refuses diff --git a/src/IOCoord/SceneClash.Clearance.cs b/src/IOCoord/SceneClash.Clearance.cs index bffbf05..cc5eb8d 100644 --- a/src/IOCoord/SceneClash.Clearance.cs +++ b/src/IOCoord/SceneClash.Clearance.cs @@ -16,13 +16,11 @@ public static partial class SceneClash public static SceneClashTest FindSurfaceClearances(SceneDocument scene, IEnumerable first, IEnumerable second, double maxClearanceMetres, CancellationToken cancellationToken = default) { - ArgumentOutOfRangeException.ThrowIfNegative(maxClearanceMetres); - if (!double.IsFinite(maxClearanceMetres)) - throw new ArgumentOutOfRangeException(nameof(maxClearanceMetres), "Clearance must be finite."); - return Find(scene, first, second, maxClearanceMetres, cancellationToken); + ValidateDistance(maxClearanceMetres, nameof(maxClearanceMetres)); + return Find(scene, first, second, Query.Clearance, maxClearanceMetres, cancellationToken); } - private static (Vector3d Point, double Distance) ClosestBetween(Triangle a, Triangle b) + private static (Vector3d Point, double Distance) ClosestBetween(Primitive a, Primitive b) { ReadOnlySpan first = [a.A, a.B, a.C]; ReadOnlySpan second = [b.A, b.B, b.C]; @@ -47,7 +45,7 @@ void Consider(Vector3d one, Vector3d two) double distance = SceneMeasure.Length(one - two); if (distance >= shortest) return; shortest = distance; - midpoint = one * 0.5 + two * 0.5; + midpoint = Midpoint(one, two); } } diff --git a/src/IOCoord/SceneClash.Duplicates.cs b/src/IOCoord/SceneClash.Duplicates.cs new file mode 100644 index 0000000..5636cd6 --- /dev/null +++ b/src/IOCoord/SceneClash.Duplicates.cs @@ -0,0 +1,54 @@ +using IOScene; + +namespace IOCoord; + +public static partial class SceneClash +{ + /// Finds element pairs with matching placed geometry and ordered topology. + /// The scene whose placed geometry is tested. + /// Ids of elements in the first selection. + /// Ids of elements in the second selection. + /// Inclusive maximum distance between corresponding vertices, in metres. + /// Cancellation token for the query. + /// One zero-distance result per element pair with at least one matching instance. + /// Topology, vertex order and effective index order must match. Material and names do not affect the query. + public static SceneClashTest FindDuplicates(SceneDocument scene, IEnumerable first, IEnumerable second, + double toleranceMetres = 0, CancellationToken cancellationToken = default) + { + ValidateDistance(toleranceMetres, nameof(toleranceMetres)); + return Find(scene, first, second, Query.Duplicate, toleranceMetres, cancellationToken); + } + + private static bool AreDuplicates(SceneInstance first, SceneInstance second, + Dictionary geometries, double tolerance, CancellationToken token) + { + var a = geometries[first.GeometryId]; + var b = geometries[second.GeometryId]; + if (a.Topology != b.Topology || a.Vertices.Count != b.Vertices.Count) return false; + + int aCount = a.Indices.Count == 0 ? a.Vertices.Count : a.Indices.Count; + int bCount = b.Indices.Count == 0 ? b.Vertices.Count : b.Indices.Count; + if (aCount != bCount) return false; + if (a.Id != b.Id) + { + for (int i = 0; i < aCount; i++) + { + token.ThrowIfCancellationRequested(); + int ai = a.Indices.Count == 0 ? i : a.Indices[i]; + int bi = b.Indices.Count == 0 ? i : b.Indices[i]; + if (ai != bi) return false; + } + } + + var transformA = first.Transform ?? Transform3d.Identity; + var transformB = second.Transform ?? Transform3d.Identity; + if (a.Id == b.Id && transformA == transformB) return true; + for (int i = 0; i < a.Vertices.Count; i++) + { + token.ThrowIfCancellationRequested(); + var delta = transformA.Apply(a.Vertices[i]) - transformB.Apply(b.Vertices[i]); + if (double.Hypot(double.Hypot(delta.X, delta.Y), delta.Z) > tolerance) return false; + } + return true; + } +} diff --git a/src/IOCoord/SceneClash.Overlap.cs b/src/IOCoord/SceneClash.Overlap.cs new file mode 100644 index 0000000..b2efaca --- /dev/null +++ b/src/IOCoord/SceneClash.Overlap.cs @@ -0,0 +1,54 @@ +using IOScene; + +namespace IOCoord; + +public static partial class SceneClash +{ + /// Finds surface clashes using the overlap of the colliding mesh bounds to estimate depth. + /// The scene whose placed triangles are tested. + /// Ids of elements in the first selection. + /// Ids of elements in the second selection. + /// Inclusive minimum positive depth in metres, finite and nonnegative. + /// Cancellation token for the query. + /// The deepest contact per element pair, with a signed distance of zero or less in metres. + /// Zero-depth contacts are retained. Depth is the minimum side length of the overlap of the two + /// contacting instances' axis-aligned bounds. Enclosed solids whose surfaces do not touch have no result. + public static SceneClashTest FindHardClashes(SceneDocument scene, IEnumerable first, IEnumerable second, + double minDepthMetres = 0, CancellationToken cancellationToken = default) + { + ValidateDistance(minDepthMetres, nameof(minDepthMetres)); + return Find(scene, first, second, Query.Hard, minDepthMetres, cancellationToken); + } + + /// Finds potentially clashing element pairs by comparing the bounds of their placed geometry. + /// The scene whose placed geometry is tested. + /// Ids of elements in the first selection. + /// Ids of elements in the second selection. + /// Cancellation token for the query. + /// The deepest box overlap per pair, with the centre of that overlap and its negative depth in metres. + /// Touching boxes have a distance of zero. The box overlap can include empty space. + public static SceneClashTest FindBoundingBoxOverlaps(SceneDocument scene, IEnumerable first, IEnumerable second, + CancellationToken cancellationToken = default) => + Find(scene, first, second, Query.Overlap, 0, cancellationToken); + + private static BoundingBox3d Overlap(BoundingBox3d a, BoundingBox3d b) => new( + new(Math.Max(a.Min.X, b.Min.X), Math.Max(a.Min.Y, b.Min.Y), Math.Max(a.Min.Z, b.Min.Z)), + new(Math.Min(a.Max.X, b.Max.X), Math.Min(a.Max.Y, b.Max.Y), Math.Min(a.Max.Z, b.Max.Z))); + + private static double OverlapDepth(BoundingBox3d overlap) + { + if (overlap.IsEmpty) return 0; + var size = overlap.Size; + double depth = Math.Min(size.X, Math.Min(size.Y, size.Z)); + if (!double.IsFinite(depth)) throw new InvalidDataException("The overlap depth is outside the finite range."); + return depth; + } + + private static Vector3d Midpoint(Vector3d a, Vector3d b) => a * 0.5 + b * 0.5; + + private static void ValidateDistance(double distance, string parameter) + { + if (distance < 0 || !double.IsFinite(distance)) + throw new ArgumentOutOfRangeException(parameter, "The distance must be finite and nonnegative."); + } +} diff --git a/src/IOCoord/SceneClash.cs b/src/IOCoord/SceneClash.cs index 783df97..8de3106 100644 --- a/src/IOCoord/SceneClash.cs +++ b/src/IOCoord/SceneClash.cs @@ -2,7 +2,7 @@ namespace IOCoord; -/// Finds surface intersections between the triangle meshes of scene elements. +/// Checks placed scene geometry for intersections, clearances and overlap. public static partial class SceneClash { // The same rounding tolerance is used for the bounds, plane distances and edge distances. @@ -19,10 +19,10 @@ public static partial class SceneClash /// Penetration depth, clearance and solids enclosed without surface contact are outside this query. public static SceneClashTest FindSurfaceIntersections(SceneDocument scene, IEnumerable first, IEnumerable second, CancellationToken cancellationToken = default) => - Find(scene, first, second, null, cancellationToken); + Find(scene, first, second, Query.Intersection, 0, cancellationToken); private static SceneClashTest Find(SceneDocument scene, IEnumerable first, IEnumerable second, - double? maxClearance, CancellationToken cancellationToken) + Query query, double limit, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(scene); ArgumentNullException.ThrowIfNull(first); @@ -38,50 +38,92 @@ private static SceneClashTest Find(SceneDocument scene, IEnumerable first, throw new ArgumentException("The selections must contain ids of elements in the scene."); var geometries = scene.Geometries.ToDictionary(geometry => geometry.Id); - var leftTriangles = new List(); - var rightTriangles = new List(); - foreach (var instance in scene.Instances) + var leftPrimitives = new List(); + var rightPrimitives = new List(); + var meshBounds = query == Query.Hard ? new List() : null; + for (int placement = 0; placement < scene.Instances.Count; placement++) { + cancellationToken.ThrowIfCancellationRequested(); + var instance = scene.Instances[placement]; bool inLeft = left.Contains(instance.ElementId), inRight = right.Contains(instance.ElementId); if (!inLeft && !inRight) continue; var geometry = geometries[instance.GeometryId]; - if (geometry.Topology != SceneTopology.Triangles) continue; + if (query is not (Query.Overlap or Query.Duplicate) && geometry.Topology != SceneTopology.Triangles) continue; var transform = instance.Transform ?? Transform3d.Identity; + + int meshIndex = -1; + if (query is Query.Overlap or Query.Hard or Query.Duplicate) + { + var bounds = BoundingBox3d.Empty; + foreach (var vertex in geometry.Vertices) + { + cancellationToken.ThrowIfCancellationRequested(); + bounds = bounds.Encapsulate(WorldVertex(vertex)); + } + if (bounds.IsEmpty) continue; + if (meshBounds is null) + { + Add(new(instance.ElementId, bounds, MeshIndex: placement)); + continue; + } + meshIndex = meshBounds.Count; + meshBounds.Add(bounds); + } + var indices = geometry.Indices; bool indexed = indices.Count > 0; int count = indexed ? indices.Count : geometry.Vertices.Count; for (int offset = 0; offset < count; offset += 3) { cancellationToken.ThrowIfCancellationRequested(); - var a = WorldVertex(offset); - var b = WorldVertex(offset + 1); - var c = WorldVertex(offset + 2); + var a = WorldVertex(geometry.Vertices[indexed ? indices[offset] : offset]); + var b = WorldVertex(geometry.Vertices[indexed ? indices[offset + 1] : offset + 1]); + var c = WorldVertex(geometry.Vertices[indexed ? indices[offset + 2] : offset + 2]); var faceNormal = Vector3d.Cross(b - a, c - a); double length = faceNormal.Length; if (!double.IsFinite(length)) throw new InvalidDataException("A triangle normal is outside the finite range."); if (length == 0) continue; - var normal = faceNormal / length; var bounds = BoundingBox3d.Empty.Encapsulate(a).Encapsulate(b).Encapsulate(c); - var triangle = new Triangle(instance.ElementId, a, b, c, normal, bounds); - if (inLeft) leftTriangles.Add(triangle); - if (inRight) rightTriangles.Add(triangle); + Add(new(instance.ElementId, bounds, a, b, c, faceNormal / length, meshIndex)); } - Vector3d WorldVertex(int index) + void Add(Primitive primitive) { - var point = transform.Apply(geometry.Vertices[indexed ? indices[index] : index]); + if (inLeft) leftPrimitives.Add(primitive); + if (inRight) rightPrimitives.Add(primitive); + } + + Vector3d WorldVertex(Vector3d vertex) + { + var point = transform.Apply(vertex); if (!double.IsFinite(point.X) || !double.IsFinite(point.Y) || !double.IsFinite(point.Z)) throw new InvalidDataException("The transformed coordinates are outside the finite range."); return point; } } - var test = new SceneClashTest { Name = maxClearance is null ? "Surface intersections" : "Surface clearances" }; - if (leftTriangles.Count == 0 || rightTriangles.Count == 0) return test; - Triangle[] aTriangles = leftTriangles.ToArray(), bTriangles = rightTriangles.ToArray(); - var aRoot = Build(aTriangles, 0, aTriangles.Length, cancellationToken); - var bRoot = Build(bTriangles, 0, bTriangles.Length, cancellationToken); - double margin = Math.Max(Tolerance, maxClearance ?? 0); + var test = new SceneClashTest + { + Name = query switch + { + Query.Clearance => "Surface clearances", + Query.Hard => "Hard clashes", + Query.Overlap => "Bounding box overlaps", + Query.Duplicate => "Duplicate geometry", + _ => "Surface intersections", + }, + }; + if (leftPrimitives.Count == 0 || rightPrimitives.Count == 0) return test; + Primitive[] aPrimitives = leftPrimitives.ToArray(), bPrimitives = rightPrimitives.ToArray(); + var aRoot = Build(aPrimitives, 0, aPrimitives.Length, cancellationToken); + var bRoot = Build(bPrimitives, 0, bPrimitives.Length, cancellationToken); + double margin = query switch + { + Query.Overlap => 0, + Query.Clearance => Math.Max(Tolerance, limit), + Query.Duplicate => limit, + _ => Tolerance, + }; var contacts = new Dictionary<(long First, long Second), (Vector3d Point, double? Distance)>(); var pending = new Stack<(Node First, Node Second)>(); pending.Push((aRoot, bRoot)); @@ -104,26 +146,53 @@ Vector3d WorldVertex(int index) { for (int i = a.Start; i < a.Start + a.Count; i++) { - var one = aTriangles[i]; + var one = aPrimitives[i]; for (int j = b.Start; j < b.Start + b.Count; j++) { - var two = bTriangles[j]; + var two = bPrimitives[j]; if (one.ElementId == two.ElementId || !Overlaps(one.Bounds, two.Bounds, margin)) continue; var key = (Math.Min(one.ElementId, two.ElementId), Math.Max(one.ElementId, two.ElementId)); bool found = contacts.TryGetValue(key, out var best); - if (found && (maxClearance is null || best.Distance == 0)) continue; - if (best.Distance is double distance && !Overlaps(one.Bounds, two.Bounds, Math.Max(Tolerance, distance))) continue; - - if ((maxClearance is null || Overlaps(one.Bounds, two.Bounds, Tolerance)) - && Contact(one, two) is { } point) - { - contacts[key] = (point, maxClearance is null ? null : 0); - } - else if (maxClearance is double limit) + switch (query) { - var clearance = ClosestBetween(one, two); - if (clearance.Distance <= limit && (!found || clearance.Distance < best.Distance)) - contacts[key] = clearance; + case Query.Hard: + double depth = OverlapDepth(Overlap(meshBounds![one.MeshIndex], meshBounds[two.MeshIndex])); + if ((depth == 0 || depth >= limit) && (!found || -depth < best.Distance) + && Contact(one, two) is { } hardPoint) + contacts[key] = (hardPoint, -depth); + break; + case Query.Overlap: + var overlap = Overlap(one.Bounds, two.Bounds); + double overlapDepth = OverlapDepth(overlap); + if (!found || -overlapDepth < best.Distance) + contacts[key] = (Midpoint(overlap.Min, overlap.Max), -overlapDepth); + break; + case Query.Duplicate: + if (!found && AreDuplicates(scene.Instances[one.MeshIndex], scene.Instances[two.MeshIndex], + geometries, limit, cancellationToken)) + { + var centreA = Midpoint(one.Bounds.Min, one.Bounds.Max); + var centreB = Midpoint(two.Bounds.Min, two.Bounds.Max); + contacts[key] = (Midpoint(centreA, centreB), 0); + } + break; + case Query.Clearance: + if (best.Distance == 0) break; + if (best.Distance is double distance + && !Overlaps(one.Bounds, two.Bounds, Math.Max(Tolerance, distance))) break; + if (Overlaps(one.Bounds, two.Bounds, Tolerance) && Contact(one, two) is { } contact) + { + contacts[key] = (contact, 0); + break; + } + var clearance = ClosestBetween(one, two); + if (clearance.Distance <= limit && (!found || clearance.Distance < best.Distance)) + contacts[key] = clearance; + break; + case Query.Intersection: + if (!found && Contact(one, two) is { } point) + contacts[key] = (point, null); + break; } } } @@ -150,18 +219,18 @@ Vector3d WorldVertex(int index) return test; } - private static Node Build(Triangle[] triangles, int start, int count, CancellationToken token) + private static Node Build(Primitive[] primitives, int start, int count, CancellationToken token) { token.ThrowIfCancellationRequested(); var bounds = BoundingBox3d.Empty; - for (int i = start; i < start + count; i++) bounds = bounds.Encapsulate(triangles[i].Bounds); + for (int i = start; i < start + count; i++) bounds = bounds.Encapsulate(primitives[i].Bounds); if (count <= LeafSize) return new(bounds, start, count); Vector3d extent = bounds.Size; var comparer = extent.X >= extent.Y && extent.X >= extent.Z ? ByX : extent.Y >= extent.Z ? ByY : ByZ; - Array.Sort(triangles, start, count, comparer); + Array.Sort(primitives, start, count, comparer); int half = count / 2; - var left = Build(triangles, start, half, token); - var right = Build(triangles, start + half, count - half, token); + var left = Build(primitives, start, half, token); + var right = Build(primitives, start + half, count - half, token); return new(bounds, start, count, left, right); } @@ -170,11 +239,11 @@ private static bool Overlaps(BoundingBox3d a, BoundingBox3d b, double margin) => && a.Min.Y <= b.Max.Y + margin && b.Min.Y <= a.Max.Y + margin && a.Min.Z <= b.Max.Z + margin && b.Min.Z <= a.Max.Z + margin; - private static Vector3d? Contact(Triangle a, Triangle b) => + private static Vector3d? Contact(Primitive a, Primitive b) => EdgeContact(a.A, a.B, b) ?? EdgeContact(a.B, a.C, b) ?? EdgeContact(a.C, a.A, b) ?? EdgeContact(b.A, b.B, a) ?? EdgeContact(b.B, b.C, a) ?? EdgeContact(b.C, b.A, a); - private static Vector3d? EdgeContact(Vector3d from, Vector3d to, Triangle triangle) + private static Vector3d? EdgeContact(Vector3d from, Vector3d to, Primitive triangle) { double start = Vector3d.Dot(from - triangle.A, triangle.Normal); double end = Vector3d.Dot(to - triangle.A, triangle.Normal); @@ -192,7 +261,7 @@ private static bool Overlaps(BoundingBox3d a, BoundingBox3d b, double margin) => return Inside(point, triangle) ? point : null; } - private static bool Inside(Vector3d point, Triangle triangle) + private static bool Inside(Vector3d point, Primitive triangle) { return HasLeftSide(triangle.A, triangle.B) && HasLeftSide(triangle.B, triangle.C) && HasLeftSide(triangle.C, triangle.A); @@ -215,10 +284,13 @@ bool HasLeftSide(Vector3d from, Vector3d to) return t is >= 0 and <= 1 && s is >= 0 and <= 1 ? a + u * t : null; } - private static readonly Comparer ByX = Comparer.Create((a, b) => a.Bounds.Center.X.CompareTo(b.Bounds.Center.X)); - private static readonly Comparer ByY = Comparer.Create((a, b) => a.Bounds.Center.Y.CompareTo(b.Bounds.Center.Y)); - private static readonly Comparer ByZ = Comparer.Create((a, b) => a.Bounds.Center.Z.CompareTo(b.Bounds.Center.Z)); + private static readonly Comparer ByX = Comparer.Create((a, b) => a.Bounds.Center.X.CompareTo(b.Bounds.Center.X)); + private static readonly Comparer ByY = Comparer.Create((a, b) => a.Bounds.Center.Y.CompareTo(b.Bounds.Center.Y)); + private static readonly Comparer ByZ = Comparer.Create((a, b) => a.Bounds.Center.Z.CompareTo(b.Bounds.Center.Z)); + + private enum Query { Intersection, Clearance, Hard, Overlap, Duplicate } - private readonly record struct Triangle(long ElementId, Vector3d A, Vector3d B, Vector3d C, Vector3d Normal, BoundingBox3d Bounds); + private readonly record struct Primitive(long ElementId, BoundingBox3d Bounds, + Vector3d A = default, Vector3d B = default, Vector3d C = default, Vector3d Normal = default, int MeshIndex = -1); private sealed record Node(BoundingBox3d Bounds, int Start, int Count, Node? First = null, Node? Second = null); } diff --git a/tests/IOScene.Tools.Tests/SceneClashTests.cs b/tests/IOScene.Tools.Tests/SceneClashTests.cs index 76533c1..9fe8d1d 100644 --- a/tests/IOScene.Tools.Tests/SceneClashTests.cs +++ b/tests/IOScene.Tools.Tests/SceneClashTests.cs @@ -94,4 +94,85 @@ public void Clearances_RejectInvalidLimits(double limit) Assert.Throws(() => SceneClash.FindSurfaceClearances(new SceneDocument(), [], [], limit)); } + + [Fact] + public void HardClashes_UseOnlyBoundsOfContactingInstancesForTheDepth() + { + var scene = new SceneDocument(); + var first = AddBox(scene, "Wall", Vector3d.Zero, 2); + var second = AddBox(scene, "Column", new(1.5, 0.25, 0.25), 2); + scene.Instances.Add(new SceneInstance + { + ElementId = second.Id, + GeometryId = scene.Geometries[1].Id, + Transform = Transform3d.Translate(new(-12, 0, 0)), + }); + + var clash = Assert.Single(SceneClash.FindHardClashes(scene, [first.Id], [second.Id], 0.5).Clashes); + Assert.Equal(-0.5, clash.Distance); + Assert.Empty(SceneClash.FindHardClashes(scene, [first.Id], [second.Id], 0.51).Clashes); + Assert.Equal(-0.5, Assert.Single(SceneClash.FindBoundingBoxOverlaps(scene, [first.Id], [second.Id]).Clashes).Distance); + } + + [Fact] + public void HardClashes_RetainZeroDepthSurfaceContacts() + { + var scene = new SceneDocument(); + var first = AddBox(scene, "Wall", Vector3d.Zero, 2); + var second = AddBox(scene, "Column", new(2, 0, 0), 2); + + var clash = Assert.Single(SceneClash.FindHardClashes(scene, [first.Id], [second.Id], 0.1).Clashes); + Assert.Equal(0, clash.Distance); + Assert.Equal(2, clash.Point.X); + } + + [Fact] + public void BoundingBoxOverlaps_IncludeNestedBoxesWithNoSurfaceContact() + { + var scene = new SceneDocument(); + var first = AddBox(scene, "Outer", Vector3d.Zero, 4); + var second = AddBox(scene, "Inner", new(1, 1, 1), 1); + var disjoint = AddBox(scene, "Outside", new(12, 0, 0), 1); + + Assert.Empty(SceneClash.FindHardClashes(scene, [first.Id], [second.Id, disjoint.Id]).Clashes); + var overlap = Assert.Single(SceneClash.FindBoundingBoxOverlaps(scene, [first.Id], [second.Id, disjoint.Id]).Clashes); + Assert.Equal(second.Id, overlap.Element2Id); + Assert.Equal(new Vector3d(1.5, 1.5, 1.5), overlap.Point); + Assert.Equal(-1, overlap.Distance); + } + + [Fact] + public void Duplicates_ComparePlacedVerticesAndEffectiveIndexOrder() + { + var scene = new SceneDocument(); + Vector3d[] vertices = [Vector3d.Zero, Vector3d.UnitX, Vector3d.UnitY]; + var original = scene.AddMesh("Original", vertices, [0, 1, 2]); + var matching = scene.AddMesh("Matching", vertices, []); + var reordered = scene.AddMesh("Reordered", vertices, [0, 2, 1]); + var points = scene.AddMesh("Points", vertices, [0, 1, 2]); + scene.Geometries[3].Topology = SceneTopology.Points; + scene.Instances[1].Transform = Transform3d.Translate(new(0, 0, 0.125)); + long[] selection = [original.Id, matching.Id, reordered.Id, points.Id]; + + var duplicate = Assert.Single(SceneClash.FindDuplicates(scene, [original.Id], selection, 0.125).Clashes); + Assert.Equal(matching.Id, duplicate.Element2Id); + Assert.Equal(0, duplicate.Distance); + Assert.Empty(SceneClash.FindDuplicates(scene, [original.Id], selection, 0.124).Clashes); + } + + private static SceneElement AddBox(SceneDocument scene, string name, Vector3d position, double side) + { + var element = scene.AddMesh(name, + [ + new(0, 0, 0), new(side, 0, 0), new(side, side, 0), new(0, side, 0), + new(0, 0, side), new(side, 0, side), new(side, side, side), new(0, side, side), + ], + [ + 0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7, + 0, 1, 5, 0, 5, 4, 1, 2, 6, 1, 6, 5, + 2, 3, 7, 2, 7, 6, 3, 0, 4, 3, 4, 7, + ]); + scene.Instances[^1].Transform = Transform3d.Translate(position); + return element; + } }