Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add safe subtract feature graph validation

Yuechen Lic40cfe0ec67b
diff --git a/Aetheris.Kernel.Core.Tests/Brep/Boolean/BrepBooleanSafeCompositionGraphValidatorTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Boolean/BrepBooleanSafeCompositionGraphValidatorTests.cs
new file mode 100644
index 00000000..89d4e1dc
--- /dev/null
+++ b/Aetheris.Kernel.Core.Tests/Brep/Boolean/BrepBooleanSafeCompositionGraphValidatorTests.cs
@@ -0,0 +1,165 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Boolean;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Geometry.Curves;
+using Aetheris.Kernel.Core.Geometry.Surfaces;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Numerics;
+
+namespace Aetheris.Kernel.Core.Tests.Brep.Boolean;
+
+public sealed class BrepBooleanSafeCompositionGraphValidatorTests
+{
+ [Fact]
+ public void ValidateNextSubtract_CylinderThenCone_PassesAndAppendsHole()
+ {
+ var composition = new SafeBooleanComposition(
+ new AxisAlignedBoxExtents(-20d, 20d, -15d, 15d, 0d, 12d),
+ [
+ new SupportedBooleanHole(
+ new AnalyticSurface(
+ AnalyticSurfaceKind.Cylinder,
+ Cylinder: new RecognizedCylinder(
+ new Point3D(-7d, -2d, -4d),
+ Direction3D.Create(new Vector3D(0d, 0d, 1d)),
+ 0d,
+ 20d,
+ 4d)),
+ -7d,
+ -2d,
+ 4d,
+ 4d)
+ ]);
+ var next = new AnalyticSurface(
+ AnalyticSurfaceKind.Cone,
+ Cone: new RecognizedCone(
+ new Point3D(8d, 0d, -4d),
+ Direction3D.Create(new Vector3D(0d, 0d, 1d)),
+ 0d,
+ 20d,
+ System.Math.Atan(0.25d),
+ 3d,
+ 5d));
+
+ var result = BrepBooleanSafeCompositionGraphValidator.TryValidateNextSubtract(
+ composition,
+ next,
+ ToleranceContext.Default,
+ out var updated,
+ out var diagnostic);
+
+ Assert.True(result);
+ Assert.Null(diagnostic);
+ Assert.Equal(2, updated.Holes.Count);
+ Assert.Equal(AnalyticSurfaceKind.Cone, updated.Holes[1].Surface.Kind);
+ }
+
+ [Fact]
+ public void ValidateNextSubtract_OverlappingHole_FailsDeterministically()
+ {
+ var baseBox = BrepBooleanBoxRecognition.CreateBoxFromExtents(new AxisAlignedBoxExtents(-20d, 20d, -15d, 15d, 0d, 12d)).Value;
+ var firstHole = TransformBody(BrepPrimitives.CreateCylinder(4d, 20d).Value, Transform3D.CreateTranslation(new Vector3D(0d, 0d, 6d)));
+ var firstResult = BrepBoolean.Subtract(baseBox, firstHole);
+ Assert.True(firstResult.IsSuccess);
+
+ var overlap = TransformBody(BrepPrimitives.CreateCylinder(4d, 20d).Value, Transform3D.CreateTranslation(new Vector3D(6d, 0d, 6d)));
+ var recognized = BrepBooleanAnalyticSurfaceRecognition.TryRecognizeCylinder(overlap, ToleranceContext.Default, out var surface, out _);
+ Assert.True(recognized);
+
+ var result = BrepBooleanSafeCompositionGraphValidator.TryValidateNextSubtract(
+ firstResult.Value.SafeBooleanComposition!,
+ surface,
+ ToleranceContext.Default,
+ out _,
+ out var diagnostic);
+
+ Assert.False(result);
+ Assert.NotNull(diagnostic);
+ Assert.Equal(BooleanDiagnosticCode.HoleInterference, diagnostic!.Code);
+ Assert.Equal("BrepBoolean.AnalyticHole.HoleInterference", diagnostic.Source);
+ }
+
+ [Fact]
+ public void ValidateNextSubtract_Sphere_FailsWithUnsupportedSurfaceDiagnostic()
+ {
+ var composition = new SafeBooleanComposition(
+ new AxisAlignedBoxExtents(-20d, 20d, -15d, 15d, 0d, 12d),
+ []);
+ var sphere = new AnalyticSurface(
+ AnalyticSurfaceKind.Sphere,
+ Sphere: new RecognizedSphere(Point3D.Origin, 3d));
+
+ var result = BrepBooleanSafeCompositionGraphValidator.TryValidateNextSubtract(
+ composition,
+ sphere,
+ ToleranceContext.Default,
+ out _,
+ out var diagnostic);
+
+ Assert.False(result);
+ Assert.NotNull(diagnostic);
+ Assert.Equal(BooleanDiagnosticCode.UnsupportedAnalyticSurfaceKind, diagnostic!.Code);
+ Assert.Equal("BrepBoolean.UnsupportedAnalyticSurfaceKind", diagnostic.Source);
+ Assert.Equal("Boolean Subtract: analytic hole surface kind 'Sphere' is recognized but not implemented for M13 reconstruction.", diagnostic.Message);
+ }
+
+ private static BrepBody TransformBody(BrepBody body, Transform3D transform)
+ {
+ var geometry = new BrepGeometryStore();
+ foreach (var curveEntry in body.Geometry.Curves)
+ {
+ geometry.AddCurve(curveEntry.Key, curveEntry.Value.Kind switch
+ {
+ CurveGeometryKind.Line3 => CurveGeometry.FromLine(new Line3Curve(
+ transform.Apply(curveEntry.Value.Line3!.Value.Origin),
+ transform.Apply(curveEntry.Value.Line3.Value.Direction))),
+ CurveGeometryKind.Circle3 => CurveGeometry.FromCircle(new Circle3Curve(
+ transform.Apply(curveEntry.Value.Circle3!.Value.Center),
+ transform.Apply(curveEntry.Value.Circle3.Value.Normal),
+ curveEntry.Value.Circle3.Value.Radius,
+ transform.Apply(curveEntry.Value.Circle3.Value.XAxis))),
+ _ => curveEntry.Value
+ });
+ }
+
+ foreach (var surfaceEntry in body.Geometry.Surfaces)
+ {
+ geometry.AddSurface(surfaceEntry.Key, surfaceEntry.Value.Kind switch
+ {
+ SurfaceGeometryKind.Plane => SurfaceGeometry.FromPlane(new PlaneSurface(
+ transform.Apply(surfaceEntry.Value.Plane!.Value.Origin),
+ transform.Apply(surfaceEntry.Value.Plane.Value.Normal),
+ transform.Apply(surfaceEntry.Value.Plane.Value.UAxis))),
+ SurfaceGeometryKind.Cylinder => SurfaceGeometry.FromCylinder(new CylinderSurface(
+ transform.Apply(surfaceEntry.Value.Cylinder!.Value.Origin),
+ transform.Apply(surfaceEntry.Value.Cylinder.Value.Axis),
+ surfaceEntry.Value.Cylinder.Value.Radius,
+ transform.Apply(surfaceEntry.Value.Cylinder.Value.XAxis))),
+ SurfaceGeometryKind.Cone => SurfaceGeometry.FromCone(new ConeSurface(
+ transform.Apply(surfaceEntry.Value.Cone!.Value.PlacementOrigin),
+ transform.Apply(surfaceEntry.Value.Cone.Value.Axis),
+ surfaceEntry.Value.Cone.Value.PlacementRadius,
+ surfaceEntry.Value.Cone.Value.SemiAngleRadians,
+ transform.Apply(surfaceEntry.Value.Cone.Value.ReferenceAxis))),
+ SurfaceGeometryKind.Torus => SurfaceGeometry.FromTorus(new TorusSurface(
+ transform.Apply(surfaceEntry.Value.Torus!.Value.Center),
+ transform.Apply(surfaceEntry.Value.Torus.Value.Axis),
+ surfaceEntry.Value.Torus.Value.MajorRadius,
+ surfaceEntry.Value.Torus.Value.MinorRadius,
+ transform.Apply(surfaceEntry.Value.Torus.Value.XAxis))),
+ SurfaceGeometryKind.Sphere => SurfaceGeometry.FromSphere(new SphereSurface(
+ transform.Apply(surfaceEntry.Value.Sphere!.Value.Center),
+ transform.Apply(surfaceEntry.Value.Sphere.Value.Axis),
+ surfaceEntry.Value.Sphere.Value.Radius,
+ transform.Apply(surfaceEntry.Value.Sphere.Value.XAxis))),
+ _ => surfaceEntry.Value
+ });
+ }
+
+ var vertexPoints = body.Topology.Vertices.ToDictionary(
+ vertex => vertex.Id,
+ vertex => transform.Apply(body.TryGetVertexPoint(vertex.Id, out var point) ? point : Point3D.Origin));
+
+ return new BrepBody(body.Topology, geometry, body.Bindings, vertexPoints, body.SafeBooleanComposition);
+ }
+}
diff --git a/Aetheris.Kernel.Core/Brep/Boolean/BrepBoolean.cs b/Aetheris.Kernel.Core/Brep/Boolean/BrepBoolean.cs
index 4f724fd5..1a8efdd7 100644
--- a/Aetheris.Kernel.Core/Brep/Boolean/BrepBoolean.cs
+++ b/Aetheris.Kernel.Core/Brep/Boolean/BrepBoolean.cs
@@ -251,7 +251,7 @@ public static class BrepBoolean
return new BooleanClassificationData(intersections, IsComputed: true, FragmentCount: 0, SingleBoxResult: null, SafeCompositionResult: null, UnsupportedReason: $"Boolean {operation}: analytic-hole classification requires a recognized analytic surface.");
}
- if (!BrepBooleanSafeComposition.TryAppend(leftComposition, analyticSurface, tolerance, out var updatedComposition, out var diagnostic))
+ if (!BrepBooleanSafeCompositionGraphValidator.TryValidateNextSubtract(leftComposition, analyticSurface, tolerance, out var updatedComposition, out var diagnostic))
{
return new BooleanClassificationData(
intersections,
diff --git a/Aetheris.Kernel.Core/Brep/Boolean/BrepBooleanSafeComposition.cs b/Aetheris.Kernel.Core/Brep/Boolean/BrepBooleanSafeComposition.cs
index 8601287f..bfd2cf20 100644
--- a/Aetheris.Kernel.Core/Brep/Boolean/BrepBooleanSafeComposition.cs
+++ b/Aetheris.Kernel.Core/Brep/Boolean/BrepBooleanSafeComposition.cs
@@ -68,110 +68,12 @@ public static class BrepBooleanSafeComposition
ToleranceContext tolerance,
out SafeBooleanComposition updatedComposition,
out BooleanDiagnostic? diagnostic)
- {
- updatedComposition = composition;
- diagnostic = null;
-
- if (!TryCreateSupportedHole(composition.OuterBox, surface, tolerance, out var nextHole, out diagnostic))
- {
- return false;
- }
-
- foreach (var existingHole in composition.Holes)
- {
- var deltaX = existingHole.CenterX - nextHole.CenterX;
- var deltaY = existingHole.CenterY - nextHole.CenterY;
- var centerDistance = System.Math.Sqrt((deltaX * deltaX) + (deltaY * deltaY));
- var requiredDistance = existingHole.MaxBoundaryRadius + nextHole.MaxBoundaryRadius;
-
- if (ToleranceMath.AlmostEqual(centerDistance, requiredDistance, tolerance))
- {
- diagnostic = BrepBooleanCylinderRecognition.CreateTangentContactDiagnostic(
- BooleanOperation.Subtract.ToString(),
- "analytic hole footprint is tangent to an existing composed hole.");
- return false;
- }
-
- if (centerDistance < (requiredDistance - tolerance.Linear))
- {
- diagnostic = new BooleanDiagnostic(
- BooleanDiagnosticCode.HoleInterference,
- "Boolean Subtract: analytic hole candidate failed diagnostic HoleInterference (analytic hole footprint overlaps an existing composed hole).",
- "BrepBoolean.AnalyticHole.HoleInterference");
- return false;
- }
- }
-
- updatedComposition = composition with
- {
- Holes = [.. composition.Holes, nextHole],
- };
- return true;
- }
-
- private static bool TryCreateSupportedHole(
- AxisAlignedBoxExtents outerBox,
- AnalyticSurface surface,
- ToleranceContext tolerance,
- out SupportedBooleanHole hole,
- out BooleanDiagnostic? diagnostic)
- {
- switch (surface.Kind)
- {
- case AnalyticSurfaceKind.Cylinder when surface.Cylinder is RecognizedCylinder cylinder:
- if (!BrepBooleanCylinderRecognition.ValidateThroughHole(outerBox, cylinder, tolerance, out diagnostic))
- {
- hole = default;
- return false;
- }
-
- hole = new SupportedBooleanHole(
- surface,
- cylinder.MinCenter.X,
- cylinder.MinCenter.Y,
- cylinder.Radius,
- cylinder.Radius);
- return true;
-
- case AnalyticSurfaceKind.Cone when surface.Cone is RecognizedCone cone:
- if (!BrepBooleanCylinderRecognition.ValidateThroughHole(outerBox, cone, tolerance, out diagnostic))
- {
- hole = default;
- return false;
- }
-
- var bottomAxisParameter = AxisParameterAtZ(cone, outerBox.MinZ, tolerance);
- var topAxisParameter = AxisParameterAtZ(cone, outerBox.MaxZ, tolerance);
- var boundaryBottomCenter = cone.PointAtAxisParameter(bottomAxisParameter);
- hole = new SupportedBooleanHole(
- surface,
- boundaryBottomCenter.X,
- boundaryBottomCenter.Y,
- cone.RadiusAtAxisParameter(bottomAxisParameter),
- cone.RadiusAtAxisParameter(topAxisParameter));
- return true;
-
- case AnalyticSurfaceKind.Sphere:
- case AnalyticSurfaceKind.Torus:
- default:
- diagnostic = BrepBooleanCylinderRecognition.CreateUnsupportedAnalyticSurfaceKindDiagnostic(
- BooleanOperation.Subtract.ToString(),
- surface.Kind);
- hole = default;
- return false;
- }
- }
-
- private static double AxisParameterAtZ(in RecognizedCone cone, double z, ToleranceContext tolerance)
- {
- var axisZ = cone.Axis.ToVector().Z;
- if (ToleranceMath.AlmostEqual(axisZ, 0d, tolerance))
- {
- throw new InvalidOperationException("AxisParameterAtZ requires a cone axis aligned with Z.");
- }
-
- return (z - cone.AxisOrigin.Z) / axisZ;
- }
+ => BrepBooleanSafeCompositionGraphValidator.TryValidateNextSubtract(
+ composition,
+ surface,
+ tolerance,
+ out updatedComposition,
+ out diagnostic);
}
internal static class AnalyticSurfaceCompositionExtensions
diff --git a/Aetheris.Kernel.Core/Brep/Boolean/BrepBooleanSafeCompositionGraphValidator.cs b/Aetheris.Kernel.Core/Brep/Boolean/BrepBooleanSafeCompositionGraphValidator.cs
new file mode 100644
index 00000000..51344136
--- /dev/null
+++ b/Aetheris.Kernel.Core/Brep/Boolean/BrepBooleanSafeCompositionGraphValidator.cs
@@ -0,0 +1,118 @@
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Numerics;
+
+namespace Aetheris.Kernel.Core.Brep.Boolean;
+
+public static class BrepBooleanSafeCompositionGraphValidator
+{
+ public static bool TryValidateNextSubtract(
+ SafeBooleanComposition composition,
+ AnalyticSurface surface,
+ ToleranceContext tolerance,
+ out SafeBooleanComposition updatedComposition,
+ out BooleanDiagnostic? diagnostic)
+ {
+ updatedComposition = composition;
+ diagnostic = null;
+
+ if (!TryCreateSupportedHole(composition.OuterBox, surface, tolerance, out var nextHole, out diagnostic))
+ {
+ return false;
+ }
+
+ foreach (var existingHole in composition.Holes)
+ {
+ var deltaX = existingHole.CenterX - nextHole.CenterX;
+ var deltaY = existingHole.CenterY - nextHole.CenterY;
+ var centerDistance = System.Math.Sqrt((deltaX * deltaX) + (deltaY * deltaY));
+ var requiredDistance = existingHole.MaxBoundaryRadius + nextHole.MaxBoundaryRadius;
+
+ if (ToleranceMath.AlmostEqual(centerDistance, requiredDistance, tolerance))
+ {
+ diagnostic = BrepBooleanCylinderRecognition.CreateTangentContactDiagnostic(
+ BooleanOperation.Subtract.ToString(),
+ "analytic hole footprint is tangent to an existing composed hole.");
+ return false;
+ }
+
+ if (centerDistance < (requiredDistance - tolerance.Linear))
+ {
+ diagnostic = new BooleanDiagnostic(
+ BooleanDiagnosticCode.HoleInterference,
+ "Boolean Subtract: analytic hole candidate failed diagnostic HoleInterference (analytic hole footprint overlaps an existing composed hole).",
+ "BrepBoolean.AnalyticHole.HoleInterference");
+ return false;
+ }
+ }
+
+ updatedComposition = composition with
+ {
+ Holes = [.. composition.Holes, nextHole],
+ };
+ return true;
+ }
+
+ private static bool TryCreateSupportedHole(
+ AxisAlignedBoxExtents outerBox,
+ AnalyticSurface surface,
+ ToleranceContext tolerance,
+ out SupportedBooleanHole hole,
+ out BooleanDiagnostic? diagnostic)
+ {
+ switch (surface.Kind)
+ {
+ case AnalyticSurfaceKind.Cylinder when surface.Cylinder is RecognizedCylinder cylinder:
+ if (!BrepBooleanCylinderRecognition.ValidateThroughHole(outerBox, cylinder, tolerance, out diagnostic))
+ {
+ hole = default;
+ return false;
+ }
+
+ hole = new SupportedBooleanHole(
+ surface,
+ cylinder.MinCenter.X,
+ cylinder.MinCenter.Y,
+ cylinder.Radius,
+ cylinder.Radius);
+ return true;
+
+ case AnalyticSurfaceKind.Cone when surface.Cone is RecognizedCone cone:
+ if (!BrepBooleanCylinderRecognition.ValidateThroughHole(outerBox, cone, tolerance, out diagnostic))
+ {
+ hole = default;
+ return false;
+ }
+
+ var bottomAxisParameter = AxisParameterAtZ(cone, outerBox.MinZ, tolerance);
+ var topAxisParameter = AxisParameterAtZ(cone, outerBox.MaxZ, tolerance);
+ var boundaryBottomCenter = cone.PointAtAxisParameter(bottomAxisParameter);
+ hole = new SupportedBooleanHole(
+ surface,
+ boundaryBottomCenter.X,
+ boundaryBottomCenter.Y,
+ cone.RadiusAtAxisParameter(bottomAxisParameter),
+ cone.RadiusAtAxisParameter(topAxisParameter));
+ return true;
+
+ case AnalyticSurfaceKind.Sphere:
+ case AnalyticSurfaceKind.Torus:
+ default:
+ diagnostic = BrepBooleanCylinderRecognition.CreateUnsupportedAnalyticSurfaceKindDiagnostic(
+ BooleanOperation.Subtract.ToString(),
+ surface.Kind);
+ hole = default;
+ return false;
+ }
+ }
+
+ private static double AxisParameterAtZ(in RecognizedCone cone, double z, ToleranceContext tolerance)
+ {
+ var axisZ = cone.Axis.ToVector().Z;
+ if (ToleranceMath.AlmostEqual(axisZ, 0d, tolerance))
+ {
+ throw new InvalidOperationException("AxisParameterAtZ requires a cone axis aligned with Z.");
+ }
+
+ return (z - cone.AxisOrigin.Z) / axisZ;
+ }
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentBooleanCanonicalSuccessTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentBooleanCanonicalSuccessTests.cs
index 35493c67..4768256c 100644
--- a/Aetheris.Kernel.Firmament.Tests/FirmamentBooleanCanonicalSuccessTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentBooleanCanonicalSuccessTests.cs
@@ -165,9 +165,10 @@ public sealed class FirmamentBooleanCanonicalSuccessTests
[Theory]
[InlineData("testdata/firmament/fixtures/m13a-unsupported-overlapping-composed-holes.firmament", "hole_b", "HoleInterference")]
[InlineData("testdata/firmament/fixtures/m13a-unsupported-tangent-composed-holes.firmament", "hole_b", "TangentContact")]
- [InlineData("testdata/firmament/fixtures/m13a-unsupported-composed-add-ordering.firmament", "joined", "sequential safe composition only supports subtracting supported cylinder/cone through-holes")]
- [InlineData("testdata/firmament/fixtures/m13a-unsupported-composed-subtract-sphere.firmament", "cavity", "analytic hole surface kind 'Sphere'")]
- [InlineData("testdata/firmament/fixtures/m13a-unsupported-composed-subtract-box.firmament", "notch", "sequential safe composition only supports subtracting supported cylinder/cone through-holes")]
+ [InlineData("testdata/firmament/fixtures/m13a-unsupported-composed-add-ordering.firmament", "joined", "violates safe subtract feature-graph ordering")]
+ [InlineData("testdata/firmament/fixtures/m13a-unsupported-composed-subtract-sphere.firmament", "cavity", "unsupported follow-on tool kind 'sphere'")]
+ [InlineData("testdata/firmament/fixtures/m13a-unsupported-composed-subtract-box.firmament", "notch", "unsupported follow-on tool kind 'box'")]
+ [InlineData("testdata/firmament/fixtures/m13b-invalid-composed-reenter-safe-family.firmament", "hole", "outside that supported family")]
public void SequentialCompositionOutsideSafeSubset_RemainsRejectedWithoutFallback(string fixturePath, string expectedFeatureId, string expectedMessageFragment)
{
var result = FirmamentCorpusHarness.Compile(FirmamentCorpusHarness.ReadFixtureText(fixturePath));
@@ -223,6 +224,8 @@ public sealed class FirmamentBooleanCanonicalSuccessTests
private static bool HasExpectedMixedPrimitiveFailure(string message)
=> message.Contains("M13 only supports recognized axis-aligned boxes from BrepPrimitives.CreateBox(...).", StringComparison.Ordinal)
|| message.Contains("sequential safe composition only supports subtracting supported cylinder/cone through-holes", StringComparison.Ordinal)
+ || message.Contains("feature-graph ordering", StringComparison.Ordinal)
+ || message.Contains("unsupported follow-on tool kind", StringComparison.Ordinal)
|| message.Contains("analytic hole candidate failed diagnostic", StringComparison.Ordinal)
|| message.Contains("analytic hole surface kind", StringComparison.Ordinal);
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentBuildAndExportTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentBuildAndExportTests.cs
index fcbf8f7c..6cac275e 100644
--- a/Aetheris.Kernel.Firmament.Tests/FirmamentBuildAndExportTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentBuildAndExportTests.cs
@@ -197,6 +197,7 @@ public sealed class FirmamentBuildAndExportTests
[InlineData("testdata/firmament/fixtures/m13a-unsupported-composed-add-ordering.firmament", "m13a-unsupported-composed-add-ordering.step", "joined", "add")]
[InlineData("testdata/firmament/fixtures/m13a-unsupported-composed-subtract-sphere.firmament", "m13a-unsupported-composed-subtract-sphere.step", "cavity", "subtract")]
[InlineData("testdata/firmament/fixtures/m13a-unsupported-composed-subtract-box.firmament", "m13a-unsupported-composed-subtract-box.step", "notch", "subtract")]
+ [InlineData("testdata/firmament/fixtures/m13b-invalid-composed-reenter-safe-family.firmament", "m13b-invalid-composed-reenter-safe-family.step", "hole", "subtract")]
public void Run_Unsupported_MixedPrimitive_Fixtures_Fail_And_Do_Not_Write_Fallback_Export(
string sourcePath,
string expectedFileName,
@@ -248,6 +249,8 @@ public sealed class FirmamentBuildAndExportTests
private static bool HasExpectedMixedPrimitiveFailure(string message)
=> message.Contains("M13 only supports recognized axis-aligned boxes from BrepPrimitives.CreateBox(...).", StringComparison.Ordinal)
|| message.Contains("sequential safe composition only supports subtracting supported cylinder/cone through-holes", StringComparison.Ordinal)
+ || message.Contains("feature-graph ordering", StringComparison.Ordinal)
+ || message.Contains("unsupported follow-on tool kind", StringComparison.Ordinal)
|| message.Contains("analytic hole candidate failed diagnostic", StringComparison.Ordinal)
|| message.Contains("analytic hole surface kind", StringComparison.Ordinal);
}
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentSafeSubtractFeatureGraphValidationTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentSafeSubtractFeatureGraphValidationTests.cs
new file mode 100644
index 00000000..f2a51c9d
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentSafeSubtractFeatureGraphValidationTests.cs
@@ -0,0 +1,41 @@
+using Aetheris.Kernel.Core.Diagnostics;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class FirmamentSafeSubtractFeatureGraphValidationTests
+{
+ [Fact]
+ public void FeatureGraphValidator_Allows_CurrentCanonicalSafeChains()
+ {
+ var twoCylinder = FirmamentCorpusHarness.Compile(
+ FirmamentCorpusHarness.ReadFixtureText("testdata/firmament/examples/boolean_two_cylinder_holes_basic.firmament"));
+ var cylinderCone = FirmamentCorpusHarness.Compile(
+ FirmamentCorpusHarness.ReadFixtureText("testdata/firmament/examples/boolean_cylinder_cone_holes_basic.firmament"));
+
+ Assert.True(twoCylinder.Compilation.IsSuccess);
+ Assert.True(cylinderCone.Compilation.IsSuccess);
+ }
+
+ [Theory]
+ [InlineData("testdata/firmament/fixtures/m13a-unsupported-composed-add-ordering.firmament", "violates safe subtract feature-graph ordering", "firmament.feature-graph")]
+ [InlineData("testdata/firmament/fixtures/m13a-unsupported-overlapping-composed-holes.firmament", "HoleInterference", "BrepBoolean.AnalyticHole.HoleInterference")]
+ [InlineData("testdata/firmament/fixtures/m13a-unsupported-tangent-composed-holes.firmament", "TangentContact", "BrepBoolean.AnalyticHole.TangentContact")]
+ [InlineData("testdata/firmament/fixtures/m13a-unsupported-composed-subtract-sphere.firmament", "unsupported follow-on tool kind 'sphere'", "firmament.feature-graph")]
+ [InlineData("testdata/firmament/fixtures/m13a-unsupported-composed-subtract-box.firmament", "unsupported follow-on tool kind 'box'", "firmament.feature-graph")]
+ [InlineData("testdata/firmament/fixtures/m13b-invalid-composed-reenter-safe-family.firmament", "outside that supported family", "firmament.feature-graph")]
+ public void FeatureGraphValidator_FailsDeterministically_ForUnsupportedSequentialComposition(
+ string fixturePath,
+ string expectedMessage,
+ string expectedSource)
+ {
+ var result = FirmamentCorpusHarness.Compile(FirmamentCorpusHarness.ReadFixtureText(fixturePath));
+
+ Assert.False(result.Compilation.IsSuccess);
+ Assert.Contains(result.Compilation.Diagnostics, diagnostic =>
+ diagnostic.Code == KernelDiagnosticCode.NotImplemented
+ && diagnostic.Message.Contains(expectedMessage, StringComparison.Ordinal)
+ && diagnostic.Source == expectedSource);
+ Assert.DoesNotContain(result.Compilation.Diagnostics, diagnostic =>
+ diagnostic.Message.Contains("requires at least one executed primitive or boolean body", StringComparison.Ordinal));
+ }
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentStepExporterTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentStepExporterTests.cs
index 9912d9ed..64825e10 100644
--- a/Aetheris.Kernel.Firmament.Tests/FirmamentStepExporterTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentStepExporterTests.cs
@@ -180,6 +180,7 @@ public sealed class FirmamentStepExporterTests
[InlineData("testdata/firmament/fixtures/m13a-unsupported-composed-add-ordering.firmament", "joined")]
[InlineData("testdata/firmament/fixtures/m13a-unsupported-composed-subtract-sphere.firmament", "cavity")]
[InlineData("testdata/firmament/fixtures/m13a-unsupported-composed-subtract-box.firmament", "notch")]
+ [InlineData("testdata/firmament/fixtures/m13b-invalid-composed-reenter-safe-family.firmament", "hole")]
public void Export_UnsupportedMixedPrimitiveBooleanFixtures_Fail_Loudly_Without_Fallback(string fixturePath, string expectedFeatureId)
{
var first = ExportFixture(fixturePath);
@@ -228,6 +229,8 @@ public sealed class FirmamentStepExporterTests
private static bool HasExpectedMixedPrimitiveFailure(string message)
=> message.Contains("M13 only supports recognized axis-aligned boxes from BrepPrimitives.CreateBox(...).", StringComparison.Ordinal)
|| message.Contains("sequential safe composition only supports subtracting supported cylinder/cone through-holes", StringComparison.Ordinal)
+ || message.Contains("feature-graph ordering", StringComparison.Ordinal)
+ || message.Contains("unsupported follow-on tool kind", StringComparison.Ordinal)
|| message.Contains("analytic hole candidate failed diagnostic", StringComparison.Ordinal)
|| message.Contains("analytic hole surface kind", StringComparison.Ordinal);
diff --git a/Aetheris.Kernel.Firmament/Execution/FirmamentBooleanToolBodyFactory.cs b/Aetheris.Kernel.Firmament/Execution/FirmamentBooleanToolBodyFactory.cs
new file mode 100644
index 00000000..83fc5e4b
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Execution/FirmamentBooleanToolBodyFactory.cs
@@ -0,0 +1,74 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Diagnostics;
+using Aetheris.Kernel.Core.Results;
+using Aetheris.Kernel.Firmament.Lowering;
+
+namespace Aetheris.Kernel.Firmament.Execution;
+
+internal static class FirmamentBooleanToolBodyFactory
+{
+ public static KernelResult<BrepBody> CreateBody(FirmamentLoweredToolOp tool)
+ {
+ if (string.Equals(tool.OpName, "box", StringComparison.Ordinal))
+ {
+ if (!tool.RawFields.TryGetValue("size", out var sizeRaw) || string.IsNullOrWhiteSpace(sizeRaw))
+ {
+ return KernelResult<BrepBody>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, "Boolean execution expected validated nested field 'with.size' for tool op 'box'.")]);
+ }
+
+ var parameters = FirmamentPrimitiveToolParsing.ParseBox(sizeRaw);
+ return BrepPrimitives.CreateBox(parameters.SizeX, parameters.SizeY, parameters.SizeZ);
+ }
+
+ if (string.Equals(tool.OpName, "cylinder", StringComparison.Ordinal))
+ {
+ if (!tool.RawFields.TryGetValue("radius", out var radiusRaw) || string.IsNullOrWhiteSpace(radiusRaw)
+ || !tool.RawFields.TryGetValue("height", out var heightRaw) || string.IsNullOrWhiteSpace(heightRaw))
+ {
+ return KernelResult<BrepBody>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, "Boolean execution expected validated nested fields 'with.radius' and 'with.height' for tool op 'cylinder'.")]);
+ }
+
+ return BrepPrimitives.CreateCylinder(FirmamentPrimitiveToolParsing.ParseScalar(radiusRaw), FirmamentPrimitiveToolParsing.ParseScalar(heightRaw));
+ }
+
+ if (string.Equals(tool.OpName, "sphere", StringComparison.Ordinal))
+ {
+ if (!tool.RawFields.TryGetValue("radius", out var radiusRaw) || string.IsNullOrWhiteSpace(radiusRaw))
+ {
+ return KernelResult<BrepBody>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, "Boolean execution expected validated nested field 'with.radius' for tool op 'sphere'.")]);
+ }
+
+ return BrepPrimitives.CreateSphere(FirmamentPrimitiveToolParsing.ParseScalar(radiusRaw));
+ }
+
+ if (string.Equals(tool.OpName, "cone", StringComparison.Ordinal))
+ {
+ if (!tool.RawFields.TryGetValue("bottom_radius", out var bottomRadiusRaw) || string.IsNullOrWhiteSpace(bottomRadiusRaw)
+ || !tool.RawFields.TryGetValue("top_radius", out var topRadiusRaw) || string.IsNullOrWhiteSpace(topRadiusRaw)
+ || !tool.RawFields.TryGetValue("height", out var coneHeightRaw) || string.IsNullOrWhiteSpace(coneHeightRaw))
+ {
+ return KernelResult<BrepBody>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, "Boolean execution expected validated nested fields 'with.bottom_radius', 'with.top_radius', and 'with.height' for tool op 'cone'.")]);
+ }
+
+ return FirmamentPrimitiveExecutor.ExecuteCone(new FirmamentLoweredConeParameters(
+ FirmamentPrimitiveToolParsing.ParseScalar(bottomRadiusRaw),
+ FirmamentPrimitiveToolParsing.ParseScalar(topRadiusRaw),
+ FirmamentPrimitiveToolParsing.ParseScalar(coneHeightRaw)));
+ }
+
+ if (string.Equals(tool.OpName, "torus", StringComparison.Ordinal))
+ {
+ if (!tool.RawFields.TryGetValue("major_radius", out var majorRadiusRaw) || string.IsNullOrWhiteSpace(majorRadiusRaw)
+ || !tool.RawFields.TryGetValue("minor_radius", out var minorRadiusRaw) || string.IsNullOrWhiteSpace(minorRadiusRaw))
+ {
+ return KernelResult<BrepBody>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, "Boolean execution expected validated nested fields 'with.major_radius' and 'with.minor_radius' for tool op 'torus'.")]);
+ }
+
+ return BrepPrimitives.CreateTorus(
+ FirmamentPrimitiveToolParsing.ParseScalar(majorRadiusRaw),
+ FirmamentPrimitiveToolParsing.ParseScalar(minorRadiusRaw));
+ }
+
+ return KernelResult<BrepBody>.Failure([new KernelDiagnostic(KernelDiagnosticCode.NotImplemented, KernelDiagnosticSeverity.Error, $"Boolean execution supports nested tool ops 'box', 'cylinder', 'sphere', 'cone', and 'torus' only. Got '{tool.OpName}'.")]);
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/Execution/FirmamentPrimitiveExecutor.cs b/Aetheris.Kernel.Firmament/Execution/FirmamentPrimitiveExecutor.cs
index b06ca3a6..ff8205e7 100644
--- a/Aetheris.Kernel.Firmament/Execution/FirmamentPrimitiveExecutor.cs
+++ b/Aetheris.Kernel.Firmament/Execution/FirmamentPrimitiveExecutor.cs
@@ -9,6 +9,7 @@ using Aetheris.Kernel.Core.Math;
using Aetheris.Kernel.Core.Results;
using Aetheris.Kernel.Core.Topology;
using Aetheris.Kernel.Firmament.Lowering;
+using Aetheris.Kernel.Firmament.Validation;
namespace Aetheris.Kernel.Firmament.Execution;
@@ -22,6 +23,7 @@ internal static class FirmamentPrimitiveExecutor
var executedBooleans = new List<FirmamentExecutedBoolean>(loweringPlan.Booleans.Count);
var publishedBodiesByFeatureId = new Dictionary<string, BrepBody>(StringComparer.Ordinal);
var booleanExecutionBodiesByFeatureId = new Dictionary<string, BrepBody>(StringComparer.Ordinal);
+ var featureGraphStates = new Dictionary<string, FirmamentSafeSubtractFeatureGraphState>(StringComparer.Ordinal);
foreach (var primitive in loweringPlan.Primitives.OrderBy(p => p.OpIndex))
{
@@ -34,6 +36,9 @@ internal static class FirmamentPrimitiveExecutor
executedPrimitives.Add(new FirmamentExecutedPrimitive(primitive.OpIndex, primitive.FeatureId, primitive.Kind, bodyResult.Value.Published));
publishedBodiesByFeatureId[primitive.FeatureId] = bodyResult.Value.Published;
booleanExecutionBodiesByFeatureId[primitive.FeatureId] = bodyResult.Value.LegacyForBoolean;
+ featureGraphStates[primitive.FeatureId] = primitive.Kind == FirmamentLoweredPrimitiveKind.Box
+ ? FirmamentSafeSubtractFeatureGraphState.BoxRoot
+ : FirmamentSafeSubtractFeatureGraphState.Other;
}
foreach (var boolean in loweringPlan.Booleans.OrderBy(b => b.OpIndex))
@@ -43,7 +48,20 @@ internal static class FirmamentPrimitiveExecutor
continue;
}
- var toolResult = ExecuteTool(boolean.Tool);
+ var featureGraphValidation = FirmamentSafeSubtractFeatureGraphValidator.ValidateNextBoolean(
+ boolean,
+ featureGraphStates,
+ booleanExecutionBodiesByFeatureId);
+ if (!featureGraphValidation.IsSuccess)
+ {
+ return KernelResult<FirmamentPrimitiveExecutionResult>.Failure(
+ [
+ CreateBooleanExecutionFailureDiagnostic(boolean),
+ .. featureGraphValidation.Diagnostics
+ ]);
+ }
+
+ var toolResult = FirmamentBooleanToolBodyFactory.CreateBody(boolean.Tool);
if (!toolResult.IsSuccess)
{
return KernelResult<FirmamentPrimitiveExecutionResult>.Failure(toolResult.Diagnostics);
@@ -71,6 +89,7 @@ internal static class FirmamentPrimitiveExecutor
executedBooleans.Add(new FirmamentExecutedBoolean(boolean.OpIndex, boolean.FeatureId, boolean.Kind, placedBooleanBody));
publishedBodiesByFeatureId[boolean.FeatureId] = placedBooleanBody;
booleanExecutionBodiesByFeatureId[boolean.FeatureId] = placedBooleanBody;
+ featureGraphStates[boolean.FeatureId] = featureGraphValidation.Value.ResultState;
}
return KernelResult<FirmamentPrimitiveExecutionResult>.Success(new FirmamentPrimitiveExecutionResult(executedPrimitives, executedBooleans));
@@ -126,7 +145,7 @@ internal static class FirmamentPrimitiveExecutor
};
}
- private static KernelResult<BrepBody> ExecuteCone(FirmamentLoweredConeParameters parameters)
+ internal static KernelResult<BrepBody> ExecuteCone(FirmamentLoweredConeParameters parameters)
{
var frame = new ExtrudeFrame3D(
origin: Point3D.Origin,
@@ -150,71 +169,6 @@ internal static class FirmamentPrimitiveExecutor
return KernelResult<BrepBody>.Success(TranslateBody(coneResult.Value, new Vector3D(0d, 0d, -parameters.Height * 0.5d)));
}
- private static KernelResult<BrepBody> ExecuteTool(FirmamentLoweredToolOp tool)
- {
- if (string.Equals(tool.OpName, "box", StringComparison.Ordinal))
- {
- if (!tool.RawFields.TryGetValue("size", out var sizeRaw) || string.IsNullOrWhiteSpace(sizeRaw))
- {
- return KernelResult<BrepBody>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, "Boolean execution expected validated nested field 'with.size' for tool op 'box'.")]);
- }
-
- var parameters = FirmamentPrimitiveToolParsing.ParseBox(sizeRaw);
- return BrepPrimitives.CreateBox(parameters.SizeX, parameters.SizeY, parameters.SizeZ);
- }
-
- if (string.Equals(tool.OpName, "cylinder", StringComparison.Ordinal))
- {
- if (!tool.RawFields.TryGetValue("radius", out var radiusRaw) || string.IsNullOrWhiteSpace(radiusRaw)
- || !tool.RawFields.TryGetValue("height", out var heightRaw) || string.IsNullOrWhiteSpace(heightRaw))
- {
- return KernelResult<BrepBody>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, "Boolean execution expected validated nested fields 'with.radius' and 'with.height' for tool op 'cylinder'.")]);
- }
-
- return BrepPrimitives.CreateCylinder(FirmamentPrimitiveToolParsing.ParseScalar(radiusRaw), FirmamentPrimitiveToolParsing.ParseScalar(heightRaw));
- }
-
- if (string.Equals(tool.OpName, "sphere", StringComparison.Ordinal))
- {
- if (!tool.RawFields.TryGetValue("radius", out var radiusRaw) || string.IsNullOrWhiteSpace(radiusRaw))
- {
- return KernelResult<BrepBody>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, "Boolean execution expected validated nested field 'with.radius' for tool op 'sphere'.")]);
- }
-
- return BrepPrimitives.CreateSphere(FirmamentPrimitiveToolParsing.ParseScalar(radiusRaw));
- }
-
- if (string.Equals(tool.OpName, "cone", StringComparison.Ordinal))
- {
- if (!tool.RawFields.TryGetValue("bottom_radius", out var bottomRadiusRaw) || string.IsNullOrWhiteSpace(bottomRadiusRaw)
- || !tool.RawFields.TryGetValue("top_radius", out var topRadiusRaw) || string.IsNullOrWhiteSpace(topRadiusRaw)
- || !tool.RawFields.TryGetValue("height", out var coneHeightRaw) || string.IsNullOrWhiteSpace(coneHeightRaw))
- {
- return KernelResult<BrepBody>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, "Boolean execution expected validated nested fields 'with.bottom_radius', 'with.top_radius', and 'with.height' for tool op 'cone'.")]);
- }
-
- return ExecuteCone(new FirmamentLoweredConeParameters(
- FirmamentPrimitiveToolParsing.ParseScalar(bottomRadiusRaw),
- FirmamentPrimitiveToolParsing.ParseScalar(topRadiusRaw),
- FirmamentPrimitiveToolParsing.ParseScalar(coneHeightRaw)));
- }
-
- if (string.Equals(tool.OpName, "torus", StringComparison.Ordinal))
- {
- if (!tool.RawFields.TryGetValue("major_radius", out var majorRadiusRaw) || string.IsNullOrWhiteSpace(majorRadiusRaw)
- || !tool.RawFields.TryGetValue("minor_radius", out var minorRadiusRaw) || string.IsNullOrWhiteSpace(minorRadiusRaw))
- {
- return KernelResult<BrepBody>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, "Boolean execution expected validated nested fields 'with.major_radius' and 'with.minor_radius' for tool op 'torus'.")]);
- }
-
- return BrepPrimitives.CreateTorus(
- FirmamentPrimitiveToolParsing.ParseScalar(majorRadiusRaw),
- FirmamentPrimitiveToolParsing.ParseScalar(minorRadiusRaw));
- }
-
- return KernelResult<BrepBody>.Failure([new KernelDiagnostic(KernelDiagnosticCode.NotImplemented, KernelDiagnosticSeverity.Error, $"Boolean execution supports nested tool ops 'box', 'cylinder', 'sphere', 'cone', and 'torus' only. Got '{tool.OpName}'.")]);
- }
-
private static KernelResult<BrepBody> ExecuteBoolean(FirmamentLoweredBooleanKind kind, BrepBody left, BrepBody right) =>
kind switch
{
diff --git a/Aetheris.Kernel.Firmament/Validation/FirmamentSafeSubtractFeatureGraphValidator.cs b/Aetheris.Kernel.Firmament/Validation/FirmamentSafeSubtractFeatureGraphValidator.cs
new file mode 100644
index 00000000..3cd33896
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Validation/FirmamentSafeSubtractFeatureGraphValidator.cs
@@ -0,0 +1,140 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Boolean;
+using Aetheris.Kernel.Core.Diagnostics;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Numerics;
+using Aetheris.Kernel.Core.Results;
+using Aetheris.Kernel.Firmament.Execution;
+using Aetheris.Kernel.Firmament.Lowering;
+
+namespace Aetheris.Kernel.Firmament.Validation;
+
+internal static class FirmamentSafeSubtractFeatureGraphValidator
+{
+ public static KernelResult<FirmamentSafeSubtractFeatureGraphValidation> ValidateNextBoolean(
+ FirmamentLoweredBoolean boolean,
+ IReadOnlyDictionary<string, FirmamentSafeSubtractFeatureGraphState> statesByFeatureId,
+ IReadOnlyDictionary<string, BrepBody> executionBodiesByFeatureId,
+ ToleranceContext? tolerance = null)
+ {
+ ArgumentNullException.ThrowIfNull(boolean);
+ ArgumentNullException.ThrowIfNull(statesByFeatureId);
+ ArgumentNullException.ThrowIfNull(executionBodiesByFeatureId);
+
+ var sourceState = statesByFeatureId.TryGetValue(boolean.PrimaryReferenceFeatureId, out var knownState)
+ ? knownState
+ : FirmamentSafeSubtractFeatureGraphState.Other;
+ var usesSupportedSafeHoleTool = IsSupportedSafeHoleTool(boolean.Tool);
+
+ if (sourceState == FirmamentSafeSubtractFeatureGraphState.SafeSubtractComposition)
+ {
+ if (boolean.Kind != FirmamentLoweredBooleanKind.Subtract)
+ {
+ return Failure(
+ $"Boolean op '{boolean.FeatureId}' at index {boolean.OpIndex} violates safe subtract feature-graph ordering: composed hole chains can only continue with 'subtract', but got '{boolean.Kind.ToString().ToLowerInvariant()}'.");
+ }
+
+ if (!usesSupportedSafeHoleTool)
+ {
+ return Failure(
+ $"Boolean op '{boolean.FeatureId}' at index {boolean.OpIndex} uses unsupported follow-on tool kind '{boolean.Tool.OpName}' after safe subtract composition began; only nested 'cylinder' or 'cone' subtract tools are supported.");
+ }
+
+ return ValidateSupportedSafeSubtract(boolean, executionBodiesByFeatureId, tolerance);
+ }
+
+ if (sourceState == FirmamentSafeSubtractFeatureGraphState.BoxRoot)
+ {
+ if (boolean.Kind == FirmamentLoweredBooleanKind.Subtract && usesSupportedSafeHoleTool)
+ {
+ return ValidateSupportedSafeSubtract(boolean, executionBodiesByFeatureId, tolerance);
+ }
+
+ return KernelResult<FirmamentSafeSubtractFeatureGraphValidation>.Success(
+ new FirmamentSafeSubtractFeatureGraphValidation(
+ WasValidated: false,
+ ResultState: FirmamentSafeSubtractFeatureGraphState.Other));
+ }
+
+ if (boolean.Kind == FirmamentLoweredBooleanKind.Subtract && usesSupportedSafeHoleTool)
+ {
+ return Failure(
+ $"Boolean op '{boolean.FeatureId}' at index {boolean.OpIndex} violates safe subtract feature-graph ordering: nested 'cylinder'/'cone' through-hole composition can only start from a box or continue from a previously validated safe subtract result, but '{boolean.PrimaryReferenceFeatureId}' is outside that supported family.");
+ }
+
+ return KernelResult<FirmamentSafeSubtractFeatureGraphValidation>.Success(
+ new FirmamentSafeSubtractFeatureGraphValidation(
+ WasValidated: false,
+ ResultState: FirmamentSafeSubtractFeatureGraphState.Other));
+ }
+
+ private static KernelResult<FirmamentSafeSubtractFeatureGraphValidation> ValidateSupportedSafeSubtract(
+ FirmamentLoweredBoolean boolean,
+ IReadOnlyDictionary<string, BrepBody> executionBodiesByFeatureId,
+ ToleranceContext? tolerance)
+ {
+ if (!executionBodiesByFeatureId.TryGetValue(boolean.PrimaryReferenceFeatureId, out var leftBody))
+ {
+ return Failure($"Boolean op '{boolean.FeatureId}' at index {boolean.OpIndex} could not resolve left feature '{boolean.PrimaryReferenceFeatureId}' for feature-graph validation.");
+ }
+
+ var resolvedTolerance = tolerance ?? ToleranceContext.Default;
+ if (!BrepBooleanSafeComposition.TryRecognize(leftBody, resolvedTolerance, out var composition, out _))
+ {
+ return Failure(
+ $"Boolean op '{boolean.FeatureId}' at index {boolean.OpIndex} violates safe subtract feature-graph ordering: left feature '{boolean.PrimaryReferenceFeatureId}' is not a recognized base box or previously validated safe subtract composition.");
+ }
+
+ var toolBodyResult = FirmamentBooleanToolBodyFactory.CreateBody(boolean.Tool);
+ if (!toolBodyResult.IsSuccess)
+ {
+ return KernelResult<FirmamentSafeSubtractFeatureGraphValidation>.Failure(toolBodyResult.Diagnostics);
+ }
+
+ if (!BrepBooleanAnalyticSurfaceRecognition.TryRecognizeAnalyticSurface(toolBodyResult.Value, resolvedTolerance, out var analyticSurface, out var reason))
+ {
+ return Failure(
+ $"Boolean op '{boolean.FeatureId}' at index {boolean.OpIndex} could not recognize nested tool op '{boolean.Tool.OpName}' as an analytic hole candidate for safe subtract feature-graph validation ({reason}).");
+ }
+
+ if (!BrepBooleanSafeCompositionGraphValidator.TryValidateNextSubtract(
+ composition,
+ analyticSurface,
+ resolvedTolerance,
+ out _,
+ out var diagnostic))
+ {
+ return KernelResult<FirmamentSafeSubtractFeatureGraphValidation>.Failure([diagnostic!.ToKernelDiagnostic()]);
+ }
+
+ return KernelResult<FirmamentSafeSubtractFeatureGraphValidation>.Success(
+ new FirmamentSafeSubtractFeatureGraphValidation(
+ WasValidated: true,
+ ResultState: FirmamentSafeSubtractFeatureGraphState.SafeSubtractComposition));
+ }
+
+ private static bool IsSupportedSafeHoleTool(FirmamentLoweredToolOp tool)
+ => string.Equals(tool.OpName, "cylinder", StringComparison.Ordinal)
+ || string.Equals(tool.OpName, "cone", StringComparison.Ordinal);
+
+ private static KernelResult<FirmamentSafeSubtractFeatureGraphValidation> Failure(string message)
+ => KernelResult<FirmamentSafeSubtractFeatureGraphValidation>.Failure(
+ [
+ new KernelDiagnostic(
+ KernelDiagnosticCode.NotImplemented,
+ KernelDiagnosticSeverity.Error,
+ message,
+ Source: "firmament.feature-graph")
+ ]);
+}
+
+internal sealed record FirmamentSafeSubtractFeatureGraphValidation(
+ bool WasValidated,
+ FirmamentSafeSubtractFeatureGraphState ResultState);
+
+internal enum FirmamentSafeSubtractFeatureGraphState
+{
+ BoxRoot,
+ SafeSubtractComposition,
+ Other
+}
diff --git a/testdata/firmament/fixtures/m13b-invalid-composed-reenter-safe-family.firmament b/testdata/firmament/fixtures/m13b-invalid-composed-reenter-safe-family.firmament
new file mode 100644
index 00000000..ffb4a558
--- /dev/null
+++ b/testdata/firmament/fixtures/m13b-invalid-composed-reenter-safe-family.firmament
@@ -0,0 +1,35 @@
+firmament:
+ version: 1
+
+model:
+ name: m13b_invalid_composed_reenter_safe_family
+ units: mm
+
+ops[4]:
+ -
+ op: box
+ id: base
+ size[3]:
+ 40
+ 30
+ 12
+
+ -
+ op: add
+ id: joined
+ to: base
+ with:
+ op: box
+ size[3]:
+ 6
+ 6
+ 6
+
+ -
+ op: subtract
+ id: hole
+ from: joined
+ with:
+ op: cylinder
+ radius: 2
+ height: 20