diff --git a/docs/tools-changelog.md b/docs/tools-changelog.md index 4b41f0c..d457ab2 100644 --- a/docs/tools-changelog.md +++ b/docs/tools-changelog.md @@ -3,7 +3,7 @@ ## [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, grid queries, revision comparison and BCF 2.1 export. +- `IOCoord` provides measurements, triangle surface intersections and clearance, 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 65e61ab..fa5ecd5 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -46,8 +46,11 @@ to a scene. `SceneClash.FindSurfaceIntersections` tests the placed triangle surfaces of two element selections. Its bounding box hierarchy narrows the triangle pairs, and a surface check finds a contact point for each intersecting element -pair. It returns a `SceneClashTest` for export or review, with a contact tolerance of one nanometre. Solid -containment, penetration depth and clearance require different queries. +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. `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 new file mode 100644 index 0000000..bffbf05 --- /dev/null +++ b/src/IOCoord/SceneClash.Clearance.cs @@ -0,0 +1,72 @@ +using IOScene; + +namespace IOCoord; + +public static partial class SceneClash +{ + /// Finds the minimum surface gap for each element pair within the specified clearance. + /// The scene whose placed triangles are tested. + /// Ids of elements in the first selection. + /// Ids of elements in the second selection. + /// Inclusive maximum distance in metres, finite and nonnegative. + /// Cancellation token for the query. + /// One result per pair. Its point is the midpoint of the measured gap. + /// Intersecting surfaces report a distance of zero, using the same rounding tolerance as + /// . The query measures triangle surfaces. + 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); + } + + private static (Vector3d Point, double Distance) ClosestBetween(Triangle a, Triangle b) + { + ReadOnlySpan first = [a.A, a.B, a.C]; + ReadOnlySpan second = [b.A, b.B, b.C]; + Vector3d midpoint = default; + double shortest = double.PositiveInfinity; + + // For disjoint triangles a minimum occurs at a vertex and a face, or between two edges. + for (int i = 0; i < 3; i++) + { + Consider(first[i], SceneMeasure.ClosestOnTriangle(first[i], b.A, b.B, b.C)); + Consider(SceneMeasure.ClosestOnTriangle(second[i], a.A, a.B, a.C), second[i]); + for (int j = 0; j < 3; j++) + { + var (one, two) = ClosestBetweenEdges(first[i], first[(i + 1) % 3], second[j], second[(j + 1) % 3]); + Consider(one, two); + } + } + return (midpoint, shortest); + + 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; + } + } + + private static (Vector3d First, Vector3d Second) ClosestBetweenEdges( + Vector3d aStart, Vector3d aEnd, Vector3d bStart, Vector3d bEnd) + { + var a = aEnd - aStart; + var b = bEnd - bStart; + double aLength = SceneMeasure.Length(a); + double bLength = SceneMeasure.Length(b); + a /= aLength; + b /= bLength; + var cross = Vector3d.Cross(a, b); + double denominator = Vector3d.Dot(cross, cross); + var offset = bStart - aStart; + double alongA = denominator == 0 ? 0 + : Math.Clamp(Vector3d.Dot(Vector3d.Cross(offset, b), cross) / denominator, 0, aLength); + double alongB = Math.Clamp(Vector3d.Dot(a * alongA - offset, b), 0, bLength); + alongA = Math.Clamp(Vector3d.Dot(offset + b * alongB, a), 0, aLength); + return (aStart + a * alongA, bStart + b * alongB); + } +} diff --git a/src/IOCoord/SceneClash.cs b/src/IOCoord/SceneClash.cs index c1aef88..783df97 100644 --- a/src/IOCoord/SceneClash.cs +++ b/src/IOCoord/SceneClash.cs @@ -3,7 +3,7 @@ namespace IOCoord; /// Finds surface intersections between the triangle meshes of scene elements. -public static class SceneClash +public static partial class SceneClash { // The same rounding tolerance is used for the bounds, plane distances and edge distances. private const double Tolerance = 1e-9; @@ -18,7 +18,11 @@ public static class SceneClash /// Tests triangle surfaces in metres. A contact tolerance of one nanometre covers rounding. /// 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) + CancellationToken cancellationToken = default) => + Find(scene, first, second, null, cancellationToken); + + private static SceneClashTest Find(SceneDocument scene, IEnumerable first, IEnumerable second, + double? maxClearance, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(scene); ArgumentNullException.ThrowIfNull(first); @@ -72,19 +76,20 @@ Vector3d WorldVertex(int index) } } - var test = new SceneClashTest { Name = "Surface intersections" }; + 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); - var contacts = new Dictionary<(long First, long Second), Vector3d>(); + double margin = Math.Max(Tolerance, maxClearance ?? 0); + var contacts = new Dictionary<(long First, long Second), (Vector3d Point, double? Distance)>(); var pending = new Stack<(Node First, Node Second)>(); pending.Push((aRoot, bRoot)); while (pending.TryPop(out var pair)) { cancellationToken.ThrowIfCancellationRequested(); var (a, b) = pair; - if (!Overlaps(a.Bounds, b.Bounds)) continue; + if (!Overlaps(a.Bounds, b.Bounds, margin)) continue; if (a.First is not null && (b.First is null || a.Count >= b.Count)) { pending.Push((a.First, b)); @@ -103,16 +108,29 @@ Vector3d WorldVertex(int index) for (int j = b.Start; j < b.Start + b.Count; j++) { var two = bTriangles[j]; - if (one.ElementId == two.ElementId || !Overlaps(one.Bounds, two.Bounds)) continue; + 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)); - if (!contacts.ContainsKey(key) && Contact(one, two) is { } point) - contacts.Add(key, point); + 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) + { + var clearance = ClosestBetween(one, two); + if (clearance.Distance <= limit && (!found || clearance.Distance < best.Distance)) + contacts[key] = clearance; + } } } } } - foreach (var (key, point) in contacts.OrderBy(pair => pair.Key)) + foreach (var (key, contact) in contacts.OrderBy(pair => pair.Key)) { string firstName = elements[key.First].Name; string secondName = elements[key.Second].Name; @@ -124,7 +142,8 @@ Vector3d WorldVertex(int index) Element2Id = key.Second, Element1Name = firstName, Element2Name = secondName, - Point = point, + Point = contact.Point, + Distance = contact.Distance, Status = SceneClashStatus.New, }); } @@ -146,10 +165,10 @@ private static Node Build(Triangle[] triangles, int start, int count, Cancellati return new(bounds, start, count, left, right); } - private static bool Overlaps(BoundingBox3d a, BoundingBox3d b) => - a.Min.X <= b.Max.X + Tolerance && b.Min.X <= a.Max.X + Tolerance - && a.Min.Y <= b.Max.Y + Tolerance && b.Min.Y <= a.Max.Y + Tolerance - && a.Min.Z <= b.Max.Z + Tolerance && b.Min.Z <= a.Max.Z + Tolerance; + private static bool Overlaps(BoundingBox3d a, BoundingBox3d b, double margin) => + a.Min.X <= b.Max.X + margin && b.Min.X <= a.Max.X + 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) => EdgeContact(a.A, a.B, b) ?? EdgeContact(a.B, a.C, b) ?? EdgeContact(a.C, a.A, b) diff --git a/src/IOCoord/SceneMeasure.cs b/src/IOCoord/SceneMeasure.cs index 414fefb..4826a6b 100644 --- a/src/IOCoord/SceneMeasure.cs +++ b/src/IOCoord/SceneMeasure.cs @@ -125,7 +125,7 @@ private static Vector3d ClosestOnSegment(Vector3d point, Vector3d a, Vector3d b) return a + unit * along; } - private static Vector3d ClosestOnTriangle(Vector3d point, Vector3d a, Vector3d b, Vector3d c) + internal static Vector3d ClosestOnTriangle(Vector3d point, Vector3d a, Vector3d b, Vector3d c) { var ab = b - a; var ac = c - a; @@ -151,7 +151,7 @@ bool OnInside(Vector3d start, Vector3d end) => return Length(next - point) < Length(closest - point) ? next : closest; } - private static double Length(Vector3d vector) + internal static double Length(Vector3d vector) { double scale = Math.Max(Math.Abs(vector.X), Math.Max(Math.Abs(vector.Y), Math.Abs(vector.Z))); if (scale == 0) return 0; diff --git a/tests/IOScene.Tools.Tests/SceneClashTests.cs b/tests/IOScene.Tools.Tests/SceneClashTests.cs index 72819ff..76533c1 100644 --- a/tests/IOScene.Tools.Tests/SceneClashTests.cs +++ b/tests/IOScene.Tools.Tests/SceneClashTests.cs @@ -27,6 +27,7 @@ public void Intersections_UsePlacedTrianglesAndReportOneResultPerPair() Assert.Equal(horizontal.Id, contact.Element1Id); Assert.Equal(vertical.Id, contact.Element2Id); Assert.Equal(new Vector3d(0.5, 0.5, 0), contact.Point); + Assert.Null(contact.Distance); Assert.Empty(scene.ClashTests); } @@ -44,4 +45,53 @@ public void Intersections_CheckCoplanarCrossingsAndRejectOverlappingBoundsAlone( Assert.Equal(crossing.Id, contact.Element2Id); Assert.Equal(0, contact.Point.Z); } + + [Fact] + public void Clearances_KeepTheShortestGapAcrossPlacementsAndIncludeTheLimit() + { + var scene = new SceneDocument(); + var first = scene.AddMesh("Slab", [new(0, 0, 0), new(4, 0, 0), new(0, 4, 0)], [0, 1, 2]); + var second = scene.AddMesh("Duct", [new(1, 1, 0), new(2, 1, 0), new(1, 2, 0)], [0, 1, 2]); + scene.Instances[1].Transform = Transform3d.Translate(new(0, 0, 0.75)); + scene.Instances.Add(new SceneInstance + { + ElementId = second.Id, + GeometryId = scene.Geometries[1].Id, + Transform = Transform3d.Translate(new(0, 0, 0.25)), + }); + + var result = Assert.Single(SceneClash.FindSurfaceClearances(scene, [first.Id], [second.Id], 1).Clashes); + Assert.Equal(0.25, result.Distance); + Assert.Equal(new Vector3d(1, 1, 0.125), result.Point); + Assert.Single(SceneClash.FindSurfaceClearances(scene, [second.Id], [first.Id], 0.25).Clashes); + Assert.Empty(SceneClash.FindSurfaceClearances(scene, [first.Id], [second.Id], 0.24).Clashes); + Assert.Empty(scene.ClashTests); + } + + [Fact] + public void Clearances_MeasureAnInteriorEdgePairAndKeepIntersectingPairsAtZero() + { + var scene = new SceneDocument(); + var slab = scene.AddMesh("Slab", [new(0, 0, 0), new(4, 0, 0), new(2, 4, 0)], [0, 1, 2]); + var crossing = scene.AddMesh("Crossing", [new(0, 3, 0), new(4, 3, 0), new(2, -1, 0)], [0, 1, 2]); + scene.Instances[1].Transform = Transform3d.Translate(new(0, 0, 1.25)); + + var result = Assert.Single(SceneClash.FindSurfaceClearances(scene, [slab.Id], [crossing.Id], 1.25).Clashes); + Assert.Equal(1.25, result.Distance!.Value, 12); + Assert.Equal(0.625, result.Point.Z, 12); + + scene.Instances[1].Transform = Transform3d.Identity; + result = Assert.Single(SceneClash.FindSurfaceClearances(scene, [slab.Id], [crossing.Id], 0).Clashes); + Assert.Equal(0, result.Distance); + } + + [Theory] + [InlineData(-1)] + [InlineData(double.NaN)] + [InlineData(double.PositiveInfinity)] + public void Clearances_RejectInvalidLimits(double limit) + { + Assert.Throws(() => + SceneClash.FindSurfaceClearances(new SceneDocument(), [], [], limit)); + } }