From dd971d65b3d13ede75f3ff06ce675e06a94c2554 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:10:47 +0300 Subject: [PATCH] Add cancellation and progress to clash detection --- docs/public-api.md | 10 +- .../Compatibility/Clash/NwcClashDetector.cs | 103 +++++++++-- .../Compatibility/Measure/NwcMeasureEngine.cs | 8 +- .../NwcAssembly.Compatibility.cs | 10 +- .../NwcDocument.Compatibility.cs | 10 +- src/NwcIO/Model/NwcProgress.cs | 2 +- tests/NwcIO.Tests/ClashDetectiveTests.cs | 160 ++++++++++++++++++ 7 files changed, 279 insertions(+), 24 deletions(-) diff --git a/docs/public-api.md b/docs/public-api.md index f81e500..ffb7699 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -49,7 +49,7 @@ Stream overloads leave the supplied stream open. | Type | Description | |---|---| -| `NwcClashDetector` | Broad-phase BVH and narrow-phase 3D triangle-to-triangle collision engine (`Run` over a document or federated assembly, driven by an `NwcClashTest`). Frozen: bug fixes only. | +| `NwcClashDetector` | Broad-phase bounding-box checks and narrow-phase 3D triangle-to-triangle collision detection (`Run` over a document or federated assembly, driven by an `NwcClashTest`). Frozen: bug fixes only. | | `NwcClashTest`, `NwcClashSelection`, `NwcClashResult`, `NwcClashObject` | Clash test definition (type, tolerance, per-side selections), results, and the involved elements. Frozen: bug fixes only. | | `NwcClashBatch`, `NwcClashRule`, `NwcClashComment` | Batch test container, filtering rules (ignore thresholds, custom predicates), and review comments. Frozen: bug fixes only. | | `NwcClashGroup` | Grouped clash clusters produced by `NwcClashGrouper`. Frozen: bug fixes only. | @@ -59,6 +59,14 @@ Stream overloads leave the supplied stream open. | `NwcXmlClashSerializer` | Roundtrip Navisworks Clash Report XML (`nw-clashreport-11.0.xsd`) reader and writer. Frozen: bug fixes only. | | `NwcNwfManifest` | Federation manifest used by `NwcAssembly` tooling. | +`NwcClashDetector.Run` and the `RunClashDetection` methods on `NwcDocument` and `NwcAssembly` +offer overloads with `IProgress` and `CancellationToken`. The `clash-detection` phase +reports the number of meshes processed in the first selection, starting at zero and reaching the +total on completion. An empty selection reports `0/0` once. Cancellation is checked between meshes +and during triangle comparisons, including clearance tests. If cancelled, the run throws +`OperationCanceledException` and discards the results it added, preserving prior results and groups. +The convenience methods register a test only after it completes. + ## 4D TimeLiner, Selection Sets & Appearance (`NwcIO.Model.TimeLiner`, `.Sets`, `.Appearance`) | Type | Description | diff --git a/src/NwcIO/Compatibility/Clash/NwcClashDetector.cs b/src/NwcIO/Compatibility/Clash/NwcClashDetector.cs index 703e2ef..b06aae9 100644 --- a/src/NwcIO/Compatibility/Clash/NwcClashDetector.cs +++ b/src/NwcIO/Compatibility/Clash/NwcClashDetector.cs @@ -13,16 +13,26 @@ public static class NwcClashDetector /// Executes clash detection across an individual Navisworks document according to the specified test configuration. /// /// An active set selection names a set that the document doesn't contain. - public static NwcClashTest Run(NwcDocument document, NwcClashTest test) + public static NwcClashTest Run(NwcDocument document, NwcClashTest test) => + Run(document, test, null, default); + + /// Runs clash detection across a document with cancellation and progress. + /// The cancellation token was cancelled. + public static NwcClashTest Run( + NwcDocument document, NwcClashTest test, IProgress? progress = null, + CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(document); ArgumentNullException.ThrowIfNull(test); + cancellationToken.ThrowIfCancellationRequested(); ThrowIfSetIsMissing([document], test); - var meshesA = ResolveSelection(document, test.SelectionA); - var meshesB = ResolveSelection(document, test.SelectionB); + var meshesA = ResolveSelection(document, test.SelectionA, cancellationToken); + var meshesB = ResolveSelection(document, test.SelectionB, cancellationToken); - RunCore(meshesA, meshesB, test, document.FileInfo.SourcePath ?? "Model", document); + RunWithCancellation(test, meshesA.Count, progress, + () => RunCore(meshesA, meshesB, test, document.FileInfo.SourcePath ?? "Model", document, progress, cancellationToken), + cancellationToken); return test; } @@ -30,10 +40,18 @@ public static NwcClashTest Run(NwcDocument document, NwcClashTest test) /// Executes clash detection across all contributing models of a federated Navisworks assembly. /// /// An active set selection names a set that none of the models contains. - public static NwcClashTest Run(NwcAssembly assembly, NwcClashTest test) + public static NwcClashTest Run(NwcAssembly assembly, NwcClashTest test) => + Run(assembly, test, null, default); + + /// Runs clash detection across a federated assembly with cancellation and progress. + /// The cancellation token was cancelled. + public static NwcClashTest Run( + NwcAssembly assembly, NwcClashTest test, IProgress? progress = null, + CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(assembly); ArgumentNullException.ThrowIfNull(test); + cancellationToken.ThrowIfCancellationRequested(); ThrowIfSetIsMissing(assembly.Models, test); var itemsA = new List<(NwcMesh Mesh, string ModelName, string? Layer, string ModelKey)>(); @@ -42,32 +60,64 @@ public static NwcClashTest Run(NwcAssembly assembly, NwcClashTest test) for (int m = 0; m < assembly.Models.Count; m++) { + cancellationToken.ThrowIfCancellationRequested(); var doc = assembly.Models[m]; string docName = Path.GetFileNameWithoutExtension(doc.FileInfo.SourcePath ?? $"Model_{m + 1}"); - var selA = ResolveSelection(doc, test.SelectionA); + var selA = ResolveSelection(doc, test.SelectionA, cancellationToken); for (int i = 0; i < selA.Count; i++) { itemsA.Add((selA[i], docName, selA[i].Node?.Parent?.Name, modelKeys[m])); } - var selB = ResolveSelection(doc, test.SelectionB); + var selB = ResolveSelection(doc, test.SelectionB, cancellationToken); for (int i = 0; i < selB.Count; i++) { itemsB.Add((selB[i], docName, selB[i].Node?.Parent?.Name, modelKeys[m])); } } - RunCoreMultiModel(itemsA, itemsB, test); + RunWithCancellation(test, itemsA.Count, progress, + () => RunCoreMultiModel(itemsA, itemsB, test, progress, cancellationToken), cancellationToken); return test; } + private static void RunWithCancellation( + NwcClashTest test, int total, IProgress? progress, Action run, CancellationToken cancellationToken) + { + int firstNewResult = test.Results.Count; + try + { + cancellationToken.ThrowIfCancellationRequested(); + run(); + ReportProgress(progress, total, total, cancellationToken); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + if (test.Results.Count > firstNewResult) + { + test.Results.RemoveRange(firstNewResult, test.Results.Count - firstNewResult); + } + + throw; + } + } + + private static void ReportProgress( + IProgress? progress, int completed, int total, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + progress?.Report(new NwcProgress("clash-detection", completed, total)); + } + private static void RunCore( IReadOnlyList meshesA, IReadOnlyList meshesB, NwcClashTest test, string modelName, - NwcDocument document) + NwcDocument document, + IProgress? progress, + CancellationToken cancellationToken) { bool sameSelection = ReferenceEquals(meshesA, meshesB) || meshesA.SequenceEqual(meshesB, ReferenceEqualityComparer.Instance); @@ -85,6 +135,8 @@ private static void RunCore( for (int i = 0; i < meshesA.Count; i++) { + ReportProgress(progress, i, meshesA.Count, cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); var meshA = meshesA[i]; var boxA = meshA.GetWorldBoundingBox(); if (boxA.IsEmpty) continue; @@ -92,6 +144,7 @@ private static void RunCore( for (var j = sameSelection ? i + 1 : 0; j < meshesB.Count; j++) { + cancellationToken.ThrowIfCancellationRequested(); 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. @@ -112,7 +165,7 @@ private static void RunCore( if (!expandedA.Intersects(boxB)) continue; // Narrow phase: triangle intersection (Hard) or mesh distance (Clearance) - if (TryGetClash(test, meshA, meshB, out var clashPoint, out double distance)) + if (TryGetClash(test, meshA, meshB, cancellationToken, out var clashPoint, out double distance)) { int clashIndex = test.Results.Count + 1; string clashName = $"Clash{clashIndex}"; @@ -167,7 +220,9 @@ private static void RunCore( private static void RunCoreMultiModel( List<(NwcMesh Mesh, string ModelName, string? Layer, string ModelKey)> itemsA, List<(NwcMesh Mesh, string ModelName, string? Layer, string ModelKey)> itemsB, - NwcClashTest test) + NwcClashTest test, + IProgress? progress, + CancellationToken cancellationToken) { bool sameSelection = itemsA.Select(item => item.Mesh) .SequenceEqual(itemsB.Select(item => item.Mesh), ReferenceEqualityComparer.Instance); @@ -184,6 +239,8 @@ private static void RunCoreMultiModel( } 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(); if (boxA.IsEmpty) continue; @@ -191,6 +248,7 @@ private static void RunCoreMultiModel( for (var j = sameSelection ? i + 1 : 0; j < itemsB.Count; j++) { + cancellationToken.ThrowIfCancellationRequested(); 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. @@ -209,7 +267,7 @@ private static void RunCoreMultiModel( if (!expandedA.Intersects(boxB)) continue; - if (TryGetClash(test, itemA.Mesh, itemB.Mesh, out var clashPoint, out double distance)) + if (TryGetClash(test, itemA.Mesh, itemB.Mesh, cancellationToken, out var clashPoint, out double distance)) { int clashIndex = test.Results.Count + 1; string clashName = $"Clash{clashIndex}"; @@ -270,6 +328,7 @@ private static bool TryGetClash( NwcClashTest test, NwcMesh meshA, NwcMesh meshB, + CancellationToken cancellationToken, out Vector3d clashPoint, out double distance) { @@ -286,14 +345,14 @@ private static bool TryGetClash( return false; } - var measurement = NwcIO.Model.Measure.NwcMeasureEngine.MeasureMeshToMesh(meshA, meshB); + var measurement = Measure.NwcMeasureEngine.MeasureMeshToMesh(meshA, meshB, useWorldCoordinates: true, cancellationToken); clashPoint = (measurement.PointA + measurement.PointB) * 0.5; distance = measurement.Distance; return measurement.Distance <= tolerance; } case NwcClashTestType.Duplicates: - if (!IsDuplicate(meshA, meshB, tolerance)) + if (!IsDuplicate(meshA, meshB, tolerance, cancellationToken)) { distance = 0; return false; @@ -318,7 +377,7 @@ private static bool TryGetClash( } default: - if (CheckMeshIntersection(meshA, meshB, out clashPoint, out double penetration)) + if (CheckMeshIntersection(meshA, meshB, 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. @@ -341,7 +400,8 @@ private static bool TryGetClash( /// Duplicate geometry: same world vertices within the tolerance and the same triangle/line topology. /// Transform, name, id and material are ignored. /// - internal static bool IsDuplicate(NwcMesh meshA, NwcMesh meshB, double tolerance) + internal static bool IsDuplicate( + NwcMesh meshA, NwcMesh meshB, double tolerance, CancellationToken cancellationToken = default) { if (ReferenceEquals(meshA, meshB)) { @@ -364,6 +424,7 @@ internal static bool IsDuplicate(NwcMesh meshA, NwcMesh meshB, double tolerance) double toleranceSquared = tolerance * tolerance; for (int i = 0; i < verticesA.Count; i++) { + if ((i & 255) == 0) cancellationToken.ThrowIfCancellationRequested(); Vector3d delta = verticesA[i] - verticesB[i]; // Negated form so a NaN tolerance fails closed. if (!(Vector3d.Dot(delta, delta) <= toleranceSquared)) @@ -374,6 +435,7 @@ internal static bool IsDuplicate(NwcMesh meshA, NwcMesh meshB, double tolerance) for (int i = 0; i < meshA.Indices.Count; i++) { + if ((i & 255) == 0) cancellationToken.ThrowIfCancellationRequested(); if (meshA.Indices[i] != meshB.Indices[i]) { return false; @@ -382,6 +444,7 @@ internal static bool IsDuplicate(NwcMesh meshA, NwcMesh meshB, double tolerance) for (int i = 0; i < meshA.LineIndices.Count; i++) { + if ((i & 255) == 0) cancellationToken.ThrowIfCancellationRequested(); if (meshA.LineIndices[i] != meshB.LineIndices[i]) { return false; @@ -394,6 +457,7 @@ internal static bool IsDuplicate(NwcMesh meshA, NwcMesh meshB, double tolerance) private static bool CheckMeshIntersection( NwcMesh a, NwcMesh b, + CancellationToken cancellationToken, out Vector3d clashPoint, out double penetrationDepth) { @@ -433,6 +497,7 @@ private static bool CheckMeshIntersection( for (int i = 0; i + 2 < indicesA.Count; i += 3) { + cancellationToken.ThrowIfCancellationRequested(); int ia0 = indicesA[i]; int ia1 = indicesA[i + 1]; int ia2 = indicesA[i + 2]; @@ -444,6 +509,7 @@ private static bool CheckMeshIntersection( for (int j = 0; j + 2 < indicesB.Count; j += 3) { + if (j % (3 * 256) == 0) cancellationToken.ThrowIfCancellationRequested(); int ib0 = indicesB[j]; int ib1 = indicesB[j + 1]; int ib2 = indicesB[j + 2]; @@ -494,8 +560,10 @@ private static List CreateDefaultIndices(int count) return indices; } - private static IReadOnlyList ResolveSelection(NwcDocument document, NwcClashSelection sel) + private static IReadOnlyList ResolveSelection( + NwcDocument document, NwcClashSelection sel, CancellationToken cancellationToken) { + cancellationToken.ThrowIfCancellationRequested(); if (sel.ExplicitNodeIds.Count > 0) { var idSet = new HashSet(sel.ExplicitNodeIds); @@ -515,6 +583,7 @@ private static IReadOnlyList ResolveSelection(NwcDocument document, Nwc var matchedMeshes = new List(); for (int s = 0; s < sel.SetNames.Count; s++) { + cancellationToken.ThrowIfCancellationRequested(); var set = document.FindSet(sel.SetNames[s]); if (set is NwcSelectionSet selSet) { diff --git a/src/NwcIO/Compatibility/Measure/NwcMeasureEngine.cs b/src/NwcIO/Compatibility/Measure/NwcMeasureEngine.cs index ad5906e..cbdf621 100644 --- a/src/NwcIO/Compatibility/Measure/NwcMeasureEngine.cs +++ b/src/NwcIO/Compatibility/Measure/NwcMeasureEngine.cs @@ -253,7 +253,11 @@ public static NwcPointToMeshMeasurement MeasurePointToMesh(Vector3d point, NwcMe /// /// Measures the clearance (minimum distance) between two 3D polygon meshes. /// - public static NwcMeshToMeshMeasurement MeasureMeshToMesh(NwcMesh meshA, NwcMesh meshB, bool useWorldCoordinates = true) + public static NwcMeshToMeshMeasurement MeasureMeshToMesh(NwcMesh meshA, NwcMesh meshB, bool useWorldCoordinates = true) => + MeasureMeshToMesh(meshA, meshB, useWorldCoordinates, default); + + internal static NwcMeshToMeshMeasurement MeasureMeshToMesh( + NwcMesh meshA, NwcMesh meshB, bool useWorldCoordinates, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(meshA); ArgumentNullException.ThrowIfNull(meshB); @@ -277,6 +281,7 @@ public static NwcMeshToMeshMeasurement MeasureMeshToMesh(NwcMesh meshA, NwcMesh for (var i = 0; i + 2 < indicesA.Count; i += 3) { + cancellationToken.ThrowIfCancellationRequested(); if (!ReadTriangle(vertsA, indicesA, i, a)) { continue; @@ -284,6 +289,7 @@ public static NwcMeshToMeshMeasurement MeasureMeshToMesh(NwcMesh meshA, NwcMesh for (var j = 0; j + 2 < indicesB.Count; j += 3) { + if (j % (3 * 256) == 0) cancellationToken.ThrowIfCancellationRequested(); if (!ReadTriangle(vertsB, indicesB, j, b)) { continue; diff --git a/src/NwcIO/Compatibility/NwcAssembly.Compatibility.cs b/src/NwcIO/Compatibility/NwcAssembly.Compatibility.cs index 7576fa2..8805ef0 100644 --- a/src/NwcIO/Compatibility/NwcAssembly.Compatibility.cs +++ b/src/NwcIO/Compatibility/NwcAssembly.Compatibility.cs @@ -243,10 +243,16 @@ public IReadOnlyList FindClashes(double tolerance = 0.0) /// /// Executes full mesh-level triangle collision detection across all contributing models of the assembly. /// - public Clash.NwcClashTest RunClashDetection(string testName = "Federated Clash Test", double tolerance = 0.001) + public Clash.NwcClashTest RunClashDetection(string testName = "Federated Clash Test", double tolerance = 0.001) => + RunClashDetection(testName, tolerance, null, default); + + /// Runs a hard clash test across all models with cancellation and progress. + /// The cancellation token was cancelled. + public Clash.NwcClashTest RunClashDetection( + string testName, double tolerance, IProgress? progress = null, CancellationToken cancellationToken = default) { var test = new Clash.NwcClashTest(testName, Clash.NwcClashTestType.Hard, tolerance); - Clash.NwcClashDetector.Run(this, test); + Clash.NwcClashDetector.Run(this, test, progress, cancellationToken); ClashTests.Add(test); return test; } diff --git a/src/NwcIO/Compatibility/NwcDocument.Compatibility.cs b/src/NwcIO/Compatibility/NwcDocument.Compatibility.cs index 835e688..5c286fb 100644 --- a/src/NwcIO/Compatibility/NwcDocument.Compatibility.cs +++ b/src/NwcIO/Compatibility/NwcDocument.Compatibility.cs @@ -197,10 +197,16 @@ public void ImportTimeLinerPrimavera(string path) /// /// Executes clash detection across the document using the specified or default test configuration. /// - public Model.Clash.NwcClashTest RunClashDetection(Model.Clash.NwcClashTest? test = null) + public Model.Clash.NwcClashTest RunClashDetection(Model.Clash.NwcClashTest? test = null) => + RunClashDetection(test, null, default); + + /// Runs the specified or default clash test with cancellation and progress. + /// The cancellation token was cancelled. + public Model.Clash.NwcClashTest RunClashDetection( + Model.Clash.NwcClashTest? test, IProgress? progress = null, CancellationToken cancellationToken = default) { test ??= new Model.Clash.NwcClashTest("Clash Test"); - Model.Clash.NwcClashDetector.Run(this, test); + Model.Clash.NwcClashDetector.Run(this, test, progress, cancellationToken); if (!ClashTests.Contains(test)) ClashTests.Add(test); return test; } diff --git a/src/NwcIO/Model/NwcProgress.cs b/src/NwcIO/Model/NwcProgress.cs index 6b7c59f..24d3f35 100644 --- a/src/NwcIO/Model/NwcProgress.cs +++ b/src/NwcIO/Model/NwcProgress.cs @@ -1,6 +1,6 @@ namespace NwcIO.Model; -/// Progress reported by long-running reader operations. +/// Progress reported by long-running operations. /// Operation phase, for example "load-models". /// Completed units, such as mesh pairs or model files. /// Total units for the phase, or 0 when unknown. diff --git a/tests/NwcIO.Tests/ClashDetectiveTests.cs b/tests/NwcIO.Tests/ClashDetectiveTests.cs index 5bfc800..e018e1c 100644 --- a/tests/NwcIO.Tests/ClashDetectiveTests.cs +++ b/tests/NwcIO.Tests/ClashDetectiveTests.cs @@ -1180,6 +1180,166 @@ public void IsDuplicate_RejectsDifferentTopologyAndAppliesTransform() Assert.True(NwcClashDetector.IsDuplicate(a, shifted, 0.001)); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ClashDetection_PreCancelled_DoesNotReportOrRegisterTest(bool federated) + { + var doc = NwcDocument.Create(meshes: [CreateBoxMesh(1, new(0, 0, 0), new(1, 1, 1))]); + var assembly = NwcAssembly.Create("Federation", doc); + using var cts = new CancellationTokenSource(); + cts.Cancel(); + var reports = new List(); + var progress = new ClashProgress(reports.Add); + + var error = Assert.Throws(() => federated + ? assembly.RunClashDetection("Cancelled", 0.001, progress, cts.Token) + : doc.RunClashDetection(null, progress, cts.Token)); + + Assert.Equal(cts.Token, error.CancellationToken); + Assert.Empty(reports); + Assert.Empty(doc.ClashTests); + Assert.Empty(assembly.ClashTests); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ClashDetection_CancelledAfterFirstMesh_PreservesPriorResultsAndCanBeRetried(bool federated) + { + var first = NwcDocument.Create(meshes: + [ + CreateBoxMesh(1, new(0, 0, 0), new(2, 2, 2)), + new NwcMesh { Id = 2, Vertices = [], Indices = [] }, + ]); + NwcMesh[] otherMeshes = + [ + CreateBoxMesh(3, new(0, 0, 0), new(2, 2, 2)), + CreateBoxMesh(4, new(0, 0, 0), new(2, 2, 2)), + ]; + var doc = NwcDocument.Create(meshes: [.. first.Meshes, .. otherMeshes]); + var assembly = NwcAssembly.Create("Federation", first, NwcDocument.Create(meshes: otherMeshes)); + var test = new NwcClashTest("Progress", NwcClashTestType.Conservative); + var prior = new NwcClashResult(); + var group = new NwcClashGroup("Previous run"); + test.Results.Add(prior); + test.Groups.Add(group); + using var cts = new CancellationTokenSource(); + var reports = new List(); + var cancelAfterFirstMesh = new ClashProgress(value => + { + reports.Add(value); + if (value.Completed == 1) + { + Assert.Equal(3, test.Results.Count); + cts.Cancel(); + } + }); + + var error = Assert.Throws(() => Run(cancelAfterFirstMesh, cts.Token)); + Assert.Equal(cts.Token, error.CancellationToken); + Assert.Equal([0, 1], reports.Select(value => value.Completed)); + Assert.Same(prior, Assert.Single(test.Results)); + Assert.Same(group, Assert.Single(test.Groups)); + Assert.Empty(doc.ClashTests); + + reports.Clear(); + Assert.Same(test, Run(new ClashProgress(reports.Add), default)); + + Assert.Equal([0, 1, 2, 3, 4], reports.Select(value => value.Completed)); + Assert.All(reports, value => + { + Assert.Equal("clash-detection", value.Phase); + Assert.Equal(4, value.Total); + }); + Assert.Equal(4, test.Results.Count); + Assert.Same(prior, test.Results[0]); + if (!federated) Assert.Same(test, Assert.Single(doc.ClashTests)); + + NwcClashTest Run(IProgress progress, CancellationToken token) => federated + ? NwcClashDetector.Run(assembly, test, progress, token) + : doc.RunClashDetection(test, progress, token); + } + + [Theory] + [InlineData(NwcClashTestType.Hard)] + [InlineData(NwcClashTestType.Clearance)] + [InlineData(NwcClashTestType.Duplicates)] + public void ClashDetection_CancelledDuringGeometryComparison_StopsInsideMeshPair(NwcClashTestType type) + { + using var cts = new CancellationTokenSource(); + var indices = new CancelOnIndexRead(cts); + bool duplicates = type == NwcClashTestType.Duplicates; + var a = new NwcMesh + { + Id = 1, + Vertices = [new(0, 0, 0), new(2, 0, 0), new(0, 2, 0)], + Indices = duplicates ? Enumerable.Range(0, indices.Count).Select(i => i % 3).ToArray() : [0, 1, 2], + }; + var b = new NwcMesh + { + Id = 2, + Vertices = duplicates ? a.Vertices : [new(1.5, 1.5, 0), new(2, 1.5, 0), new(1.5, 2, 0)], + Indices = indices, + }; + var report = new List(); + var doc = NwcDocument.Create(meshes: [a, b]); + var test = new NwcClashTest("One pair", type); + test.SelectionA.ExplicitNodeIds.Add(1); + test.SelectionB.ExplicitNodeIds.Add(2); + + var error = Assert.Throws(() => + NwcClashDetector.Run(doc, test, new ClashProgress(report.Add), cts.Token)); + + Assert.Equal(cts.Token, error.CancellationToken); + Assert.InRange(indices.Reads, 1, 3 * 256); + Assert.Equal(new NwcProgress("clash-detection", 0, 1), Assert.Single(report)); + Assert.Empty(test.Results); + } + + [Fact] + public void ClashDetection_EmptySelection_ReportsCompletionOnce() + { + var reports = new List(); + var doc = NwcDocument.Create(); + var assembly = NwcAssembly.Create("Empty", doc); + + var test = assembly.RunClashDetection("Empty", 0.001, new ClashProgress(reports.Add), default); + + Assert.Equal(new NwcProgress("clash-detection", 0, 0), Assert.Single(reports)); + Assert.Empty(test.Results); + Assert.Same(test, Assert.Single(assembly.ClashTests)); + } + + private sealed class ClashProgress(Action report) : IProgress + { + public void Report(NwcProgress value) => report(value); + } + + private sealed class CancelOnIndexRead(CancellationTokenSource cancellation) : IReadOnlyList + { + public int Count => 2048 * 3; + public int Reads { get; private set; } + public int this[int index] + { + get + { + if (++Reads == 1) cancellation.Cancel(); + return index % 3; + } + } + + public IEnumerator GetEnumerator() + { + for (int i = 0; i < Count; i++) + { + yield return this[i]; + } + } + + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + } + private static NwcMesh CreateBoxMesh(int id, Vector3d min, Vector3d max) { var vertices = new Vector3d[]