Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add hollow, rounded-box, and trihedral fillet export paths
Yuechen Li5261bcdb4981
diff --git a/Aetheris.CLI.Tests/LocalizedTangentBlendFilletPipelineTests.cs b/Aetheris.CLI.Tests/LocalizedTangentBlendFilletPipelineTests.csindex 92d0d310..4826a682 100644--- a/Aetheris.CLI.Tests/LocalizedTangentBlendFilletPipelineTests.cs+++ b/Aetheris.CLI.Tests/LocalizedTangentBlendFilletPipelineTests.cs@@ -101,6 +101,38 @@ public sealed class LocalizedTangentBlendFilletPipelineTestsAssert.Equal(1, closure.GetProperty("sharedEdges").GetInt32());}+ [Theory]+ [InlineData(10d, 8d, 6d, 1d)]+ [InlineData(10d, 8d, 6d, 2d)]+ [InlineData(12d, 5d, 7d, 1d)]+ public void LocalizedTangentBlend_ThreeEdgeTrihedral_ExportsSphericalOctant(double width, double depth, double height, double radius)+ {+ var run = Run($$"""+ Model Trihedral mm+ Box Base { Size: [{{width}}mm, {{depth}}mm, {{height}}mm] }+ Modify Base {+ EdgeFinish XZ { Face: +X Target: SharedEdgePlusZ Kind: Fillet Distance: {{radius}}mm }+ EdgeFinish YZ { Face: +Y Target: SharedEdgePlusZ Kind: Fillet Distance: {{radius}}mm }+ EdgeFinish XY { Face: +X Target: SharedEdgePlusY Kind: Fillet Distance: {{radius}}mm }+ }+ """);+ Assert.Equal(0, run.Exit);+ using var json = JsonDocument.Parse(run.Output);+ var air = json.RootElement.GetProperty("air");+ var junction = air.GetProperty("localizedEdgeJunction");+ Assert.Equal("LocalizedTrihedralFillet", junction.GetProperty("construction").GetString());+ Assert.Equal("SphericalOctant", junction.GetProperty("cornerPatch").GetString());+ Assert.Equal(3, junction.GetProperty("replacementFaces").GetInt32());+ Assert.Equal(1, junction.GetProperty("junctionFaces").GetInt32());+ Assert.Equal(3, junction.GetProperty("closure").GetProperty("sharedEdges").GetInt32());+ Assert.Equal(3, air.GetProperty("materialization").GetProperty("cylindricalFaces").GetInt32());+ Assert.Equal(1, air.GetProperty("materialization").GetProperty("sphericalFaces").GetInt32());+ Assert.True(air.GetProperty("step").GetProperty("reimportSucceeded").GetBoolean());+ var step = File.ReadAllText(json.RootElement.GetProperty("outputPath").GetString()!);+ Assert.Contains("SPHERICAL_SURFACE", step, StringComparison.Ordinal);+ Assert.Contains("CYLINDRICAL_SURFACE", step, StringComparison.Ordinal);+ }+private static (int Exit, string Output) Run(string source){var dir = Path.Combine(Path.GetTempPath(), "aetheris-localized-fillet", Guid.NewGuid().ToString("N"));diff --git a/Aetheris.CLI.Tests/RoundedBoxCliPipelineTests.cs b/Aetheris.CLI.Tests/RoundedBoxCliPipelineTests.csnew file mode 100644index 00000000..6a9ea08b--- /dev/null+++ b/Aetheris.CLI.Tests/RoundedBoxCliPipelineTests.cs@@ -0,0 +1,33 @@+namespace Aetheris.CLI.Tests;++public sealed class RoundedBoxCliPipelineTests+{+ [Fact]+ public void RoundedBoxCliBuild_ExportsAndReportsToroidalTopBoundaryFillet()+ {+ var root = Path.Combine(Path.GetTempPath(), $"aetheris-rounded-box-cli-{Guid.NewGuid():N}");+ Directory.CreateDirectory(root);+ var sourcePath = Path.Combine(root, "enclosure.firmament");+ var stepPath = Path.Combine(root, "enclosure.step");+ File.WriteAllText(sourcePath, """+ Struct Enclosure {+ RoundedBox Body { Size: [80mm, 50mm, 20mm] CornerRadius: 8mm }+ Modify Body { EdgeFinish TopRound { Face: +Z Target: Boundary Kind: Fillet Radius: 1mm } }+ }+ """);+ try+ {+ var stdout = new StringWriter(); var stderr = new StringWriter();+ var exit = CliRunner.Run(["build", sourcePath, "--out", stepPath, "--json"], stdout, stderr);++ Assert.Equal(0, exit);+ Assert.True(File.Exists(stepPath), stderr.ToString());+ Assert.Contains("\"toroidalCornerFaces\": 4", stdout.ToString(), StringComparison.Ordinal);+ Assert.Contains("TOROIDAL_SURFACE", File.ReadAllText(stepPath), StringComparison.Ordinal);+ }+ finally+ {+ if (Directory.Exists(root)) Directory.Delete(root, recursive: true);+ }+ }+}diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex e647d495..c72f1940 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -287,6 +287,8 @@ public static class CliRunneroutputPath = build.Value.OutputPath,conceptIr = build.Value.Export.ConceptIr,air = build.Value.Export.Air,+ roundedBox = build.Value.Export.RoundedBox,+ hollow = build.Value.Export.Hollow,features = build.Value.Export.Features,inlineStepMigration = build.Value.Export.InlineStepMigration,inlineStepReplacementAssist = build.Value.Export.InlineStepReplacementAssist,diff --git a/Aetheris.Kernel.Core.Tests/Air/LocalizedTrihedralFilletTests.cs b/Aetheris.Kernel.Core.Tests/Air/LocalizedTrihedralFilletTests.csnew file mode 100644index 00000000..123c14a2--- /dev/null+++ b/Aetheris.Kernel.Core.Tests/Air/LocalizedTrihedralFilletTests.cs@@ -0,0 +1,92 @@+using Aetheris.Kernel.Core.Air;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Step242;++namespace Aetheris.Kernel.Core.Tests.Air;++public sealed class LocalizedTrihedralFilletTests+{+ [Theory]+ [InlineData(10d, 8d, 6d, 1d)]+ [InlineData(10d, 8d, 6d, 2d)]+ [InlineData(12d, 5d, 7d, 1d)]+ public void EqualRadiusTrihedral_BuildsExactSphericalOctantPlan(double width, double depth, double height, double radius)+ {+ var result = AirLocalizedTrihedralFilletCompiler.Compile(Request(width, depth, height, radius, radius, radius));++ Assert.True(result.Succeeded, result.Error?.Code);+ var construction = Assert.IsType<LocalizedTrihedralFilletConstruction>(result.Construction);+ var body = Assert.IsType<BrepBody>(result.Body);+ Assert.True(result.BRepPlan!.IsAuthoritative);+ Assert.Equal(width / 2d - radius, construction.SphericalCornerPatch.Center.X, 12);+ Assert.Equal(depth / 2d - radius, construction.SphericalCornerPatch.Center.Y, 12);+ Assert.Equal(height / 2d - radius, construction.SphericalCornerPatch.Center.Z, 12);+ Assert.Equal(radius, construction.SphericalCornerPatch.Radius, 12);+ Assert.Equal(0d, construction.SphericalCornerPatch.BoundaryXZ.SphereDeviation, 12);+ Assert.Equal(0d, construction.SphericalCornerPatch.BoundaryXZ.CylinderDeviation, 12);+ Assert.Equal(0d, construction.SphericalCornerPatch.BoundaryXZ.NormalDeviation, 12);+ Assert.Equal(13, body.Topology.Vertices.Count());+ Assert.Equal(21, body.Topology.Edges.Count());+ Assert.Equal(10, body.Topology.Faces.Count());+ Assert.Equal(3, body.Geometry.Surfaces.Count(x => x.Value.Kind == SurfaceGeometryKind.Cylinder));+ Assert.Equal(1, body.Geometry.Surfaces.Count(x => x.Value.Kind == SurfaceGeometryKind.Sphere));+ Assert.Equal(6, body.Geometry.Curves.Count(x => x.Value.Kind == CurveGeometryKind.Circle3));+ Assert.True(BrepExportPreflight.Validate(body).IsValid);++ var step = Step242Exporter.ExportBody(body, new Step242ExportOptions { BrepExportPreflightMode = BrepExportPreflightMode.Enforce });+ Assert.True(step.IsSuccess, string.Join(Environment.NewLine, step.Diagnostics.Select(x => x.Message)));+ Assert.Contains("SPHERICAL_SURFACE", step.Value!, StringComparison.Ordinal);+ Assert.Contains("CYLINDRICAL_SURFACE", step.Value!, StringComparison.Ordinal);+ var imported = Step242Importer.ImportBody(step.Value!);+ Assert.True(imported.IsSuccess, string.Join(Environment.NewLine, imported.Diagnostics.Select(x => x.Message)));+ Assert.Equal(1, imported.Value!.Geometry.Surfaces.Count(x => x.Value.Kind == SurfaceGeometryKind.Sphere));+ }++ [Fact]+ public void UnequalRadii_AreDeferredBeforeBrepEmission()+ {+ var result = AirLocalizedTrihedralFilletCompiler.Compile(Request(10, 8, 6, 1, 1, 2));+ Assert.False(result.Succeeded);+ Assert.Null(result.Body);+ Assert.Equal(TrihedralFilletErrorKind.UnequalRadiusCornerSurfaceRequired, result.Error?.Kind);+ Assert.Equal("localized-trihedral-fillet-unequal-radius-corner-surface-required", result.Error?.Code);+ }++ [Theory]+ [InlineData(0d, "localized-trihedral-fillet-radius-must-be-positive")]+ [InlineData(6d, "localized-trihedral-fillet-radius-too-large")]+ public void InvalidRadius_FailsBeforeBrepEmission(double radius, string code)+ {+ var result = AirLocalizedTrihedralFilletCompiler.Compile(Request(10, 8, 6, radius, radius, radius));+ Assert.False(result.Succeeded);+ Assert.Null(result.Body);+ Assert.Equal(code, result.Error?.Code);+ }++ [Fact]+ public void UnsupportedHistoryAndNonSharingSelection_FailBeforeBrepEmission()+ {+ var unknownHistory = AirLocalizedTrihedralFilletCompiler.Compile(Request(10, 8, 6, 1, 1, 1) with { HistoryKnown = false });+ var nonSharing = AirLocalizedTrihedralFilletCompiler.Compile(Request(10, 8, 6, 1, 1, 1) with { TargetXY = "SharedEdgePlusZ" });+ Assert.Equal("localized-trihedral-fillet-unsupported-history", unknownHistory.Error?.Code);+ Assert.Equal("localized-trihedral-fillet-edges-do-not-share-canonical-vertex", nonSharing.Error?.Code);+ Assert.Null(unknownHistory.Body);+ Assert.Null(nonSharing.Body);+ }++ [Fact]+ public void RemovedVolume_HasIndependentAnalyticDecomposition()+ {+ const double width = 10, depth = 8, height = 6, r = 1;+ // Three non-overlapping remote cylindrical strips plus the local cube less its spherical octant.+ var removed = (1d - System.Math.PI / 4d) * r * r * ((width - r) + (depth - r) + (height - r))+ + (1d - System.Math.PI / 6d) * r * r * r;+ Assert.Equal(4.983039793055287d, removed, 12);+ }++ private static AirLocalizedTrihedralFilletCompileRequest Request(double width, double depth, double height, double xz, double yz, double xy) => new(+ "Base", "Base.XZ.YZ.XY", "XZ+YZ+XY", width, depth, height,+ "+X", "SharedEdgePlusZ", "+Y", "SharedEdgePlusZ", "+X", "SharedEdgePlusY", xz, yz, xy,+ new AirSourceSpan(0, 1, "test"));+}diff --git a/Aetheris.Kernel.Core.Tests/Air/RoundedBoxBRepPlanTests.cs b/Aetheris.Kernel.Core.Tests/Air/RoundedBoxBRepPlanTests.csnew file mode 100644index 00000000..bedb2101--- /dev/null+++ b/Aetheris.Kernel.Core.Tests/Air/RoundedBoxBRepPlanTests.cs@@ -0,0 +1,54 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Geometry;++namespace Aetheris.Kernel.Core.Tests.Air;++public sealed class RoundedBoxBRepPlanTests+{+ [Theory]+ [InlineData(120, 80, 18, 12, 2)]+ [InlineData(80, 50, 20, 8, 1)]+ [InlineData(150, 90, 25, 15, 3)]+ public void TopBoundaryFillet_UsesOneAuthoritativePlanWithExactToroidalCorners(double width, double depth, double height, double corner, double fillet)+ {+ var result = RoundedBoxBRepPlanner.Create(width, depth, height, corner, fillet);++ Assert.True(result.IsSuccess);+ var realization = result.Value;+ Assert.True(realization.Plan.IsAuthoritative);+ Assert.Equal(18, realization.Body.Topology.Faces.Count());+ Assert.Equal(4, realization.Body.Geometry.Surfaces.Count(x => x.Value.Kind == SurfaceGeometryKind.Torus));+ Assert.Equal(8, realization.Body.Geometry.Surfaces.Count(x => x.Value.Kind == SurfaceGeometryKind.Cylinder));+ Assert.Equal(6, realization.Body.Geometry.Surfaces.Count(x => x.Value.Kind == SurfaceGeometryKind.Plane));+ Assert.All(realization.Body.Geometry.Surfaces.Where(x => x.Value.Kind == SurfaceGeometryKind.Torus), x =>+ {+ Assert.Equal(corner - fillet, x.Value.Torus!.Value.MajorRadius, 8);+ Assert.Equal(fillet, x.Value.Torus!.Value.MinorRadius, 8);+ });+ Assert.True(BrepExportPreflight.Validate(realization.Body).IsValid);+ }++ [Fact]+ public void PrimitiveOnly_HasCylindricalSilhouetteCornersButNoEdgeFinishFaces()+ {+ var result = RoundedBoxBRepPlanner.Create(120, 80, 18, 12);++ Assert.True(result.IsSuccess);+ Assert.Equal(10, result.Value.Body.Topology.Faces.Count());+ Assert.Equal(4, result.Value.Body.Geometry.Surfaces.Count(x => x.Value.Kind == SurfaceGeometryKind.Cylinder));+ Assert.DoesNotContain(result.Value.Body.Geometry.Surfaces, x => x.Value.Kind == SurfaceGeometryKind.Torus);+ }++ [Theory]+ [InlineData(120, 80, 18, 0, 2)]+ [InlineData(120, 80, 18, 40, 2)]+ [InlineData(120, 80, 18, 12, 0)]+ [InlineData(120, 80, 18, 12, 12)]+ [InlineData(0, 80, 18, 12, 2)]+ public void InvalidDimensionsAndRadii_AreRejectedBeforeTopologyEmission(double width, double depth, double height, double corner, double fillet)+ {+ var result = RoundedBoxBRepPlanner.Create(width, depth, height, corner, fillet);++ Assert.False(result.IsSuccess);+ }+}diff --git a/Aetheris.Kernel.Core.Tests/ThinWalledBodyBRepPlanTests.cs b/Aetheris.Kernel.Core.Tests/ThinWalledBodyBRepPlanTests.csnew file mode 100644index 00000000..e56172c9--- /dev/null+++ b/Aetheris.Kernel.Core.Tests/ThinWalledBodyBRepPlanTests.cs@@ -0,0 +1,44 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Step242;++namespace Aetheris.Kernel.Core.Tests;++public sealed class ThinWalledBodyBRepPlanTests+{+ [Fact]+ public void RoundedBoxHollow_UsesOneAuthoritativePairedBoundaryPlan()+ {+ var result = ThinWalledBodyBRepPlanner.CreateRoundedBox(120, 80, 24, 12, 2);+ Assert.True(result.IsSuccess, string.Join(", ", result.Diagnostics.Select(x => x.Message)));+ var value = result.Value;+ Assert.True(value.Plan.IsAuthoritative);+ Assert.Equal("ThinWalledBody", value.Plan.Kind);+ Assert.Equal("InsetRoundedProfile", value.Feature.Witness.Kind);+ Assert.Equal(26, value.Body.Topology.Faces.Count());+ Assert.Equal(8, value.Body.Geometry.Surfaces.Count(x => x.Value.Kind == SurfaceGeometryKind.Cylinder));+ Assert.Null(value.Body.SafeBooleanComposition);+ var step = Step242Exporter.ExportBody(value.Body, new Step242ExportOptions { BrepExportPreflightMode = BrepExportPreflightMode.Enforce });+ Assert.True(step.IsSuccess, string.Join(", ", step.Diagnostics.Select(x => x.Message)));+ Assert.True(Step242Importer.ImportBody(step.Value).IsSuccess);+ }++ [Fact]+ public void FrustumHollow_UsesParallelConicalOffsetRatherThanRadialShrink()+ {+ var result = ThinWalledBodyBRepPlanner.CreateFrustum(32, 43, 90, 2);+ Assert.True(result.IsSuccess, string.Join(", ", result.Diagnostics.Select(x => x.Message)));+ var value = result.Value;+ Assert.Equal("ParallelConicalOffset", value.Feature.Witness.Kind);+ Assert.Equal(5, value.Body.Topology.Faces.Count());+ Assert.Equal(2, value.Body.Geometry.Surfaces.Count(x => x.Value.Kind == SurfaceGeometryKind.Cone));+ Assert.Equal(2, value.Construction.ThicknessWitnesses[0].Distance);+ Assert.Null(value.Body.SafeBooleanComposition);+ }++ [Theory]+ [InlineData(120, 80, 24, 12)]+ [InlineData(120, 80, 2, 2)]+ public void RoundedBoxHollow_RejectsCollapsedInnerBoundary(double width, double depth, double height, double thickness)+ => Assert.False(ThinWalledBodyBRepPlanner.CreateRoundedBox(width, depth, height, 12, thickness).IsSuccess);+}diff --git a/Aetheris.Kernel.Core/Air/AirLocalizedTrihedralFilletCompiler.cs b/Aetheris.Kernel.Core/Air/AirLocalizedTrihedralFilletCompiler.csnew file mode 100644index 00000000..bf322d09--- /dev/null+++ b/Aetheris.Kernel.Core/Air/AirLocalizedTrihedralFilletCompiler.cs@@ -0,0 +1,175 @@+using System.Security.Cryptography;+using System.Text;+using Aetheris.Kernel.Core.Air.BRepPlan;+using Aetheris.Kernel.Core.Brep;+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.Topology;++namespace Aetheris.Kernel.Core.Air;++/// <summary>Hard-admitted M5 request: the three positive, mutually incident box edges.</summary>+internal sealed record AirLocalizedTrihedralFilletCompileRequest(+ string BodyId, string FeatureId, string FeatureName, double Width, double Depth, double Height,+ string FaceXZ, string TargetXZ, string FaceYZ, string TargetYZ, string FaceXY, string TargetXY,+ double RadiusXZ, double RadiusYZ, double RadiusXY, AirSourceSpan SourceSpan, bool HistoryKnown = true);++internal enum TrihedralFilletErrorKind+{+ EdgesDoNotShareSingleVertex, UnsupportedJunctionValence, RadiusMismatch, RadiusTooLarge,+ UnsupportedSurfaceCombination, SphericalPatchConstructionFailed, SphereCylinderIntersectionMissing,+ SphereCylinderIntersectionAmbiguous, TangentContinuityFailed, BoundaryOwnershipConflict,+ DegenerateTrihedralPatch, ConstructionWitnessRequired, VerificationFailure,+ UnequalRadiusCornerSurfaceRequired,+}++internal sealed record TrihedralFilletError(TrihedralFilletErrorKind Kind, string Code, string Message, string Stage, IReadOnlyList<string> Evidence);++/// <summary>An exact finite sphere/cylinder intersection branch, owned by one shared topology edge.</summary>+internal sealed record SphereCylinderSeamConstruction(+ string Role, Circle3Curve Curve, ParameterInterval Trim, Point3D Start, Point3D End,+ string CylinderRole, double SphereDeviation, double CylinderDeviation, double NormalDeviation,+ string Orientation, string Provenance);++/// <summary>Explicit Construction AIR witness; the face is a bounded positive spherical octant only.</summary>+internal sealed record SphericalCornerPatchConstruction(+ Point3D Center, double Radius, string OctantSelection,+ SphereCylinderSeamConstruction BoundaryXZ, SphereCylinderSeamConstruction BoundaryYZ, SphereCylinderSeamConstruction BoundaryXY,+ string MaterialSide, string Provenance);++internal sealed record LocalizedTrihedralFilletConstruction(+ string ConstructionId, LocalizedEdgeJunctionReplacement ReplacementXZ,+ LocalizedEdgeJunctionReplacement ReplacementYZ, LocalizedEdgeJunctionReplacement ReplacementXY,+ SphericalCornerPatchConstruction SphericalCornerPatch, IReadOnlyList<IReadOnlyList<Point3D>> RetainedRegions,+ IReadOnlyList<IReadOnlyList<Point3D>> RemoteEndpoints, Point3D SharedOriginalVertex,+ string MaterialSide, string BoundaryOwnership, LocalizedEdgeJunctionTopologyPlan TopologyPlan, string Provenance);++internal sealed record AirLocalizedTrihedralFilletCompileResult(+ bool Succeeded, LocalizedTrihedralFilletConstruction? Construction, AirBRepPlan? BRepPlan,+ BrepBody? Body, TrihedralFilletError? Error, IReadOnlyList<string> Diagnostics)+{+ public const string ProductionRoute = "AirLocalizedTrihedralFilletM5";+}++/// <summary>+/// Exact, deliberately narrow three-edge fillet compiler. Each cylinder is truncated at the+/// plane through the common sphere center; the resulting three quarter circles bound the sole+/// positive spherical octant. No rolling-ball or unequal-radius route is implied by this type.+/// </summary>+internal static class AirLocalizedTrihedralFilletCompiler+{+ private const double Tol = 1e-9;++ public static AirLocalizedTrihedralFilletCompileResult Compile(AirLocalizedTrihedralFilletCompileRequest input)+ {+ var lowered = Lower(input);+ if (lowered.Error is not null) return new(false, null, null, null, lowered.Error, [lowered.Error.Code, .. lowered.Error.Evidence]);+ var construction = lowered.Construction!;+ var plan = BuildPlan(input, construction);+ var emitted = Emit(construction);+ if (!emitted.Succeeded || emitted.Body is null)+ return Failure(construction, plan, new(TrihedralFilletErrorKind.VerificationFailure, "localized-trihedral-fillet-materialization-failed", "The authoritative trihedral plan did not materialize.", "BRep", emitted.Diagnostics));++ var body = emitted.Body;+ var preflight = BrepExportPreflight.Validate(body);+ var sphere = body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Sphere);+ var cylinders = body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Cylinder);+ var circles = body.Geometry.Curves.Count(c => c.Value.Kind == CurveGeometryKind.Circle3);+ if (!preflight.IsValid || sphere != 1 || cylinders != 3 || circles != 6 || body.Topology.Faces.Count() != 10 || !FirmamentManifold(body))+ return Failure(construction, plan, new(TrihedralFilletErrorKind.VerificationFailure, "localized-trihedral-fillet-analytic-verification-failed", "M5 requires three cylinders, one sphere, six circular arcs, ten faces, valid preflight, and a manifold shell.", "Verification", preflight.Diagnostics.Select(d => d.Code).ToArray()));++ return new(true, construction, plan, body, null,+ ["localized-trihedral-fillet-feature-admitted", "localized-trihedral-fillet-spherical-octant", "localized-trihedral-fillet-candidate-plans=1", "localized-trihedral-fillet-hard-valid-plans=1", "localized-trihedral-fillet-g0-exact", "localized-trihedral-fillet-g1-normal-deviation=0", "localized-trihedral-fillet-authoritative-brep-plan-consumed", "localized-trihedral-fillet-no-legacy-fallback"]);+ }++ private static (LocalizedTrihedralFilletConstruction? Construction, TrihedralFilletError? Error) Lower(AirLocalizedTrihedralFilletCompileRequest i)+ {+ TrihedralFilletError Fail(TrihedralFilletErrorKind kind, string code, string message, params string[] evidence) => new(kind, code, message, "FeatureAIR->ConstructionAIR", evidence);+ if (!i.HistoryKnown) return (null, Fail(TrihedralFilletErrorKind.UnsupportedSurfaceCombination, "localized-trihedral-fillet-unsupported-history", "M5 requires a history-known axis-aligned box."));+ if (!FinitePositive(i.Width) || !FinitePositive(i.Depth) || !FinitePositive(i.Height)) return (null, Fail(TrihedralFilletErrorKind.UnsupportedSurfaceCombination, "localized-trihedral-fillet-invalid-box-dimensions", "Box extents must be finite and positive."));+ if (!Matches(i.FaceXZ, i.TargetXZ, "+X", "SharedEdgePlusZ") || !Matches(i.FaceYZ, i.TargetYZ, "+Y", "SharedEdgePlusZ") || !Matches(i.FaceXY, i.TargetXY, "+X", "SharedEdgePlusY"))+ return (null, Fail(TrihedralFilletErrorKind.EdgesDoNotShareSingleVertex, "localized-trihedral-fillet-edges-do-not-share-canonical-vertex", "M5 admits SharedEdge(+X,+Z), SharedEdge(+Y,+Z), and SharedEdge(+X,+Y) only."));+ if (!FinitePositive(i.RadiusXZ) || !FinitePositive(i.RadiusYZ) || !FinitePositive(i.RadiusXY)) return (null, Fail(TrihedralFilletErrorKind.RadiusTooLarge, "localized-trihedral-fillet-radius-must-be-positive", "Every constant radius must be finite and positive."));+ if (double.Abs(i.RadiusXZ - i.RadiusYZ) > Tol || double.Abs(i.RadiusXZ - i.RadiusXY) > Tol)+ return (null, Fail(TrihedralFilletErrorKind.UnequalRadiusCornerSurfaceRequired, "localized-trihedral-fillet-unequal-radius-corner-surface-required", "M5 admits only equal radii; a distinct unproven corner-surface construction is required.", $"rXZ={i.RadiusXZ:R}", $"rYZ={i.RadiusYZ:R}", $"rXY={i.RadiusXY:R}"));+ var r = i.RadiusXZ;+ if (r >= i.Width - Tol || r >= i.Depth - Tol || r >= i.Height - Tol) return (null, Fail(TrihedralFilletErrorKind.RadiusTooLarge, "localized-trihedral-fillet-radius-too-large", "Radius must fit each local support extent."));++ var hx = i.Width / 2d; var hy = i.Depth / 2d; var hz = i.Height / 2d;+ var c = new Point3D(hx - r, hy - r, hz - r);+ var px = new Point3D(hx, c.Y, c.Z); var py = new Point3D(c.X, hy, c.Z); var pz = new Point3D(c.X, c.Y, hz);+ var xz = new CylinderSurface(c, Direction3D.Create(new Vector3D(0, 1, 0)), r, Direction3D.Create(new Vector3D(1, 0, 0)));+ var yz = new CylinderSurface(c, Direction3D.Create(new Vector3D(1, 0, 0)), r, Direction3D.Create(new Vector3D(0, 1, 0)));+ var xy = new CylinderSurface(c, Direction3D.Create(new Vector3D(0, 0, 1)), r, Direction3D.Create(new Vector3D(1, 0, 0)));+ var seamXZ = Seam("SphereCylinderSeamXZ", px, pz, c, xz, "FilletReplacementXZ");+ var seamYZ = Seam("SphereCylinderSeamYZ", pz, py, c, yz, "FilletReplacementYZ");+ var seamXY = Seam("SphereCylinderSeamXY", py, px, c, xy, "FilletReplacementXY");+ if (seamXZ.SphereDeviation > Tol || seamYZ.SphereDeviation > Tol || seamXY.SphereDeviation > Tol || seamXZ.CylinderDeviation > Tol || seamYZ.CylinderDeviation > Tol || seamXY.CylinderDeviation > Tol)+ return (null, Fail(TrihedralFilletErrorKind.SphereCylinderIntersectionMissing, "localized-trihedral-fillet-sphere-cylinder-intersection-missing", "An exact sphere-cylinder seam could not be constructed."));+ var patch = new SphericalCornerPatchConstruction(c, r, "+X,+Y,+Z relative to center", seamXZ, seamYZ, seamXY, "convex exterior removal", "sphere center = original (+X,+Y,+Z) vertex - R*(+X,+Y,+Z); three quarter-circle intersections form one closed octant");+ var v = new[]+ {+ new Point3D(-hx,-hy,-hz), new Point3D(hx,-hy,-hz), new Point3D(-hx,hy,-hz), new Point3D(-hx,-hy,hz),+ new Point3D(hx,-hy,c.Z), new Point3D(c.X,-hy,hz), new Point3D(-hx,hy,c.Z), new Point3D(-hx,c.Y,hz),+ new Point3D(hx,c.Y,-hz), new Point3D(c.X,hy,-hz), px, py, pz,+ };+ IReadOnlyList<int>[] loops =+ [+ [0,2,9,8,1], [0,3,7,6,2], [0,1,4,5,3], [1,8,10,4], [2,6,11,9], [3,5,12,7],+ [4,10,12,5], [6,7,12,11], [8,9,11,10], [12,10,11],+ ];+ var signature = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(FormattableString.Invariant($"localized-trihedral-fillet:+X,+Z:+Y,+Z:+X,+Y:{i.Width:R}:{i.Depth:R}:{i.Height:R}:{r:R}:spherical-octant"))));+ var topology = new LocalizedEdgeJunctionTopologyPlan(v, loops,+ ["UnaffectedFace(-Z)", "UnaffectedFace(-X)", "UnaffectedFace(-Y)", "RetainedSupport(+X)", "RetainedSupport(+Y)", "RetainedSupport(+Z)", "FilletReplacementXZ(Cylinder)", "FilletReplacementYZ(Cylinder)", "FilletReplacementXY(Cylinder)", "SphericalCornerPatch"], signature);+ var fXZ = Feature(i, "XZ", "+X", "SharedEdge(+X,+Z)"); var fYZ = Feature(i, "YZ", "+Y", "SharedEdge(+Y,+Z)"); var fXY = Feature(i, "XY", "+X", "SharedEdge(+X,+Y)");+ return (new($"construction:{i.FeatureId}:trihedral-fillet", new("SharedEdge(+X,+Z)", fXZ, [v[4],v[10],v[12],v[5]], [v[4],v[5]], "CylindricalFillet"), new("SharedEdge(+Y,+Z)", fYZ, [v[6],v[7],v[12],v[11]], [v[6],v[7]], "CylindricalFillet"), new("SharedEdge(+X,+Y)", fXY, [v[8],v[9],v[11],v[10]], [v[8],v[9]], "CylindricalFillet"), patch,+ [[v[1],v[8],v[10],v[4]], [v[2],v[6],v[11],v[9]], [v[3],v[5],v[12],v[7]]], [[v[4],v[5]],[v[6],v[7]],[v[8],v[9]]], new Point3D(hx,hy,hz), "inside:x<=max,y<=max,z<=max; convex exterior removal", "Each seam is one shared opposite-oriented cylinder/sphere coedge; retained planes own tangency boundaries; remote arcs are independently owned.", topology, "history-known-axis-aligned-rectangular-box; equal-constant-radius; exact cylinders plus spherical octant"), null);+ }++ private static SphereCylinderSeamConstruction Seam(string role, Point3D start, Point3D end, Point3D center, CylinderSurface cylinder, string cylinderRole)+ {+ var curve = Arc(start, end, center);+ var mid = curve.Evaluate(double.Pi / 4d);+ var sphereDeviation = double.Abs((mid - center).Length - cylinder.Radius);+ var radial = mid - cylinder.Origin; var axial = radial.Dot(cylinder.Axis.ToVector());+ var cylinderDeviation = double.Abs((radial - cylinder.Axis.ToVector() * axial).Length - cylinder.Radius);+ var sphereNormal = Direction3D.Create(mid - center).ToVector();+ var cylinderAngle = System.Math.Atan2((mid - cylinder.Origin).Dot(cylinder.YAxis.ToVector()), (mid - cylinder.Origin).Dot(cylinder.XAxis.ToVector()));+ var cylinderNormal = cylinder.Normal(cylinderAngle).ToVector();+ return new(role, curve, new(0d, double.Pi / 2d), start, end, cylinderRole, sphereDeviation, cylinderDeviation, (sphereNormal - cylinderNormal).Length, "positive-quarter-circle; directed start->end", "exact plane-through-center sphere/cylinder intersection");+ }++ private static AirBRepPlan BuildPlan(AirLocalizedTrihedralFilletCompileRequest input, LocalizedTrihedralFilletConstruction c)+ {+ var provenance = new AirProvenance("AIR-FILLET-TRIHEDRAL-M5", "Exact equal-radius three-edge trihedral fillet", "SharedEdge(+X,+Z)/SharedEdge(+Y,+Z)/SharedEdge(+X,+Y)", input.FeatureId, nameof(AirLocalizedTrihedralFilletCompiler), AirSelectionClass.None, AirRuleKind.ConstantRadiusFillet, c.Provenance, true, ["One hard-valid spherical-octant construction.", "Three exact shared circle seams.", "No legacy surgery or unequal-radius fallback."]);+ var p = c.TopologyPlan; var e = new List<AirBRepPlanElement>();+ for (var n=0;n<p.ExpectedVertexCount;n++) e.Add(new(new($"vertex:{n}"), AirBRepPlanElementKind.Vertex, n is 10 or 11 or 12 ? AirBRepPlanRole.SharedJunction : AirBRepPlanRole.SectionVertex, input.FeatureId, provenance));+ for (var n=0;n<p.ExpectedFaceCount;n++) { var role = n is 6 or 7 or 8 ? AirBRepPlanRole.FilletFace : n==9 ? AirBRepPlanRole.CornerPatch : n is 3 or 4 or 5 ? AirBRepPlanRole.RetainedSupportFaceA : n is 0 or 1 or 2 ? AirBRepPlanRole.UnaffectedFace : AirBRepPlanRole.Unknown; e.Add(new(new($"surface:{n}"),AirBRepPlanElementKind.Surface,role,input.FeatureId,provenance)); e.Add(new(new($"loop:{n}"),AirBRepPlanElementKind.Loop,role,input.FeatureId,provenance)); for(var k=0;k<p.FaceLoops[n].Count;k++) e.Add(new(new($"coedge:{n}:{k}"),AirBRepPlanElementKind.Coedge,role,input.FeatureId,provenance)); e.Add(new(new($"face:{n}"),AirBRepPlanElementKind.Face,role,input.FeatureId,provenance,FaceRole:p.FaceRoles[n],SemanticRoles:n is 6 or 7 or 8 ? [AirBRepPlanRole.ReplacementFace,AirBRepPlanRole.FilletFace] : [role])); }+ for(var n=0;n<p.ExpectedEdgeCount;n++) e.Add(new(new($"edge:{n}"),AirBRepPlanElementKind.Edge,AirBRepPlanRole.SectionEdge,input.FeatureId,provenance));+ foreach(var role in new[]{"XZ","YZ","XY"}) e.Add(new(new($"curve:sphere-cylinder-seam:{role}"),AirBRepPlanElementKind.Curve,AirBRepPlanRole.SharedJunction,input.FeatureId,provenance,SemanticRoles:[AirBRepPlanRole.SharedJunction,AirBRepPlanRole.CornerPatch]));+ e.Add(new(new("shell:0"),AirBRepPlanElementKind.Shell,AirBRepPlanRole.BodyShell,input.FeatureId,provenance)); e.Add(new(new("body:0"),AirBRepPlanElementKind.Body,AirBRepPlanRole.Body,input.FeatureId,provenance));+ var summary = new AirBRepPlanSummary(AirBRepPlanKind.LocalizedEdgeJunction,input.FeatureId,p.ExpectedVertexCount,p.ExpectedEdgeCount,p.ExpectedEdgeCount,p.ExpectedCoedgeCount,p.ExpectedLoopCount,p.ExpectedFaceCount,p.ExpectedFaceCount,1,1,0,6,4,0,$"localized-trihedral-fillet=Fillet;patch=SphericalOctant;signature={p.DeterministicSignature}",c.BoundaryOwnership,[],["authoritative combined trihedral topology","one hard-valid plan","exact spherical octant","no legacy fallback"],new(AirNodeKind.Unsupported,AirRouteKind.Unsupported,AirSelectionClass.None,AirRuleKind.ConstantRadiusFillet,c.Provenance,"Direct",["SharedEdge(+X,+Z)","SharedEdge(+Y,+Z)","SharedEdge(+X,+Y)"]));+ return new($"brep-plan:localized-trihedral-fillet:{input.FeatureId}",AirBRepPlanKind.LocalizedEdgeJunction,input.FeatureId,provenance,e,summary,[],summary.Guarantees,summary.FeatureContext,LocalizedEdgeJunctionRealizationPlan:p);+ }++ private static AirLocalizedEdgeReplacementEmissionResult Emit(LocalizedTrihedralFilletConstruction c)+ {+ var p=c.TopologyPlan.Vertices; var loops=c.TopologyPlan.FaceLoops; var b=new TopologyBuilder(); var vertices=p.Select(_=>b.AddVertex()).ToArray(); var edges=new Dictionary<(int,int),EdgeId>(); var dirs=new Dictionary<(int,int),(int,int)>(); var faces=new List<FaceId>();+ foreach(var loop in loops) { var uses=new Use[loop.Count]; for(var n=0;n<loop.Count;n++){var a=loop[n];var z=loop[(n+1)%loop.Count];var key=a<z?(a,z):(z,a);if(!edges.TryGetValue(key,out var edge)){edge=b.AddEdge(vertices[a],vertices[z]);edges[key]=edge;dirs[key]=(a,z);}var d=dirs[key];uses[n]=d.Item1==a&&d.Item2==z?Use.F(edge):Use.R(edge);}faces.Add(AddFace(b,uses)); }+ var shell=b.AddShell(faces);b.AddBody([shell]);var geometry=new BrepGeometryStore();var bindings=new BrepBindingModel();var number=1;var arcs=new HashSet<(int,int)>{(4,5),(6,7),(8,9),(10,11),(10,12),(11,12)};+ foreach(var pair in edges.OrderBy(x=>x.Value.Value)){var (a,z)=dirs[pair.Key];var cid=new CurveGeometryId(number++);if(arcs.Contains(pair.Key)){var center=pair.Key is (4,5)?new Point3D(p[5].X,p[4].Y,p[4].Z):pair.Key is (6,7)?new Point3D(p[6].X,p[7].Y,p[6].Z):pair.Key is (8,9)?new Point3D(p[9].X,p[8].Y,p[8].Z):c.SphericalCornerPatch.Center;geometry.AddCurve(cid,CurveGeometry.FromCircle(Arc(p[a],p[z],center)));bindings.AddEdgeBinding(new EdgeGeometryBinding(pair.Value,cid,new(0d,double.Pi/2d)));}else{geometry.AddCurve(cid,CurveGeometry.FromLine(new Line3Curve(p[a],Direction3D.Create(p[z]-p[a]))));bindings.AddEdgeBinding(new EdgeGeometryBinding(pair.Value,cid,new(0d,(p[z]-p[a]).Length)));}}+ for(var n=0;n<faces.Count;n++){var sid=new SurfaceGeometryId(number++);if(n==6)geometry.AddSurface(sid,SurfaceGeometry.FromCylinder(new CylinderSurface(c.SphericalCornerPatch.Center,Direction3D.Create(new Vector3D(0,1,0)),c.SphericalCornerPatch.Radius,Direction3D.Create(new Vector3D(1,0,0)))));else if(n==7)geometry.AddSurface(sid,SurfaceGeometry.FromCylinder(new CylinderSurface(c.SphericalCornerPatch.Center,Direction3D.Create(new Vector3D(1,0,0)),c.SphericalCornerPatch.Radius,Direction3D.Create(new Vector3D(0,1,0)))));else if(n==8)geometry.AddSurface(sid,SurfaceGeometry.FromCylinder(new CylinderSurface(c.SphericalCornerPatch.Center,Direction3D.Create(new Vector3D(0,0,1)),c.SphericalCornerPatch.Radius,Direction3D.Create(new Vector3D(1,0,0)))));else if(n==9)geometry.AddSurface(sid,SurfaceGeometry.FromSphere(new SphereSurface(c.SphericalCornerPatch.Center,Direction3D.Create(new Vector3D(0,0,1)),c.SphericalCornerPatch.Radius,Direction3D.Create(new Vector3D(1,0,0)))));else{var loop=loops[n];var origin=p[loop[0]];var u=p[loop[1]]-origin;Vector3D normal=default;for(var k=2;k<loop.Count;k++){normal=u.Cross(p[loop[k]]-origin);if(normal.Length>Tol)break;}geometry.AddSurface(sid,SurfaceGeometry.FromPlane(new PlaneSurface(origin,Direction3D.Create(normal),Direction3D.Create(u))));}bindings.AddFaceBinding(new FaceGeometryBinding(faces[n],sid));}+ var points=vertices.Select((v,n)=>new KeyValuePair<VertexId,Point3D>(v,p[n])).ToDictionary();var body=new BrepBody(b.Model,geometry,bindings,points);var check=BrepBindingValidator.Validate(body,true);return check.IsSuccess?new(true,body,["localized-trihedral-fillet-plan-emitted"]):new(false,null,check.Diagnostics.Select(x=>x.Message).ToArray());+ }++ private static Circle3Curve Arc(Point3D start, Point3D end, Point3D center) => new(center,Direction3D.Create((start-center).Cross(end-center)),(start-center).Length,Direction3D.Create(start-center));+ private static AirEdgeFinishFeature Feature(AirLocalizedTrihedralFilletCompileRequest i,string suffix,string face,string edge) => new($"{i.FeatureId}.{suffix}",$"{i.FeatureName}.{suffix}",i.BodyId,new AirFaceBoundarySelection(face,edge,false),AirLocalizedEdgeFinishKind.Fillet,new AirConstantRadiusEdgeFinishRule(i.RadiusXZ),i.SourceSpan,"generated/history-known-axis-aligned-rectangular-prism",AirFeatureAdmissionStatus.Admitted,"localized-trihedral-fillet-spherical-octant-candidate");+ private static AirLocalizedTrihedralFilletCompileResult Failure(LocalizedTrihedralFilletConstruction c,AirBRepPlan p,TrihedralFilletError e)=>new(false,c,p,null,e,[e.Code,..e.Evidence]);+ private static FaceId AddFace(TopologyBuilder b,IReadOnlyList<Use> uses){var loop=b.AllocateLoopId();var ids=new CoedgeId[uses.Count];for(var n=0;n<ids.Length;n++)ids[n]=b.AllocateCoedgeId();for(var n=0;n<ids.Length;n++)b.AddCoedge(new Coedge(ids[n],uses[n].Id,loop,ids[(n+1)%ids.Length],ids[(n+ids.Length-1)%ids.Length],uses[n].Reverse));b.AddLoop(new Loop(loop,ids));return b.AddFace([loop]);}+ private readonly record struct Use(EdgeId Id,bool Reverse){public static Use F(EdgeId x)=>new(x,false);public static Use R(EdgeId x)=>new(x,true);}+ private static bool FirmamentManifold(BrepBody body) => body.Topology.Edges.All(e=>body.Topology.Coedges.Count(c=>c.EdgeId==e.Id)==2);+ private static bool FinitePositive(double x)=>double.IsFinite(x)&&x>Tol;+ private static bool Matches(string face,string target,string expectedFace,string expectedTarget)=>string.Equals(face,expectedFace,StringComparison.Ordinal)&&string.Equals(target,expectedTarget,StringComparison.Ordinal);+}diff --git a/Aetheris.Kernel.Core/Air/RoundedBoxFeature.cs b/Aetheris.Kernel.Core/Air/RoundedBoxFeature.csnew file mode 100644index 00000000..6026e1c6--- /dev/null+++ b/Aetheris.Kernel.Core/Air/RoundedBoxFeature.cs@@ -0,0 +1,41 @@+namespace Aetheris.Kernel.Core.Air;++/// <summary>+/// Semantic primitive intent for a history-known rounded rectangular prism. The+/// corner radius belongs to the silhouette; it is deliberately not an edge finish.+/// </summary>+internal sealed record RoundedBoxFeature(+ string BodyId,+ string FeatureId,+ string FeatureName,+ double Width,+ double Depth,+ double Height,+ double CornerRadius,+ string Frame,+ AirSourceSpan Provenance,+ IReadOnlyList<string> SemanticRoles,+ string Admission = "Admitted");++internal sealed record RoundedRectangleProfile(+ double Width,+ double Depth,+ double CornerRadius,+ IReadOnlyList<RoundedRectangleProfileSegment> Segments,+ string Frame,+ AirSourceSpan Provenance);++internal sealed record RoundedRectangleProfileSegment(string StableId, string Kind, string StartRole, string EndRole, double Radius = 0d);++internal sealed record LinearSweep(RoundedRectangleProfile Profile, string Vector, AirSourceSpan Provenance);++/// <summary>Feature AIR for the post-primitive, complete-top-boundary edge finish.</summary>+internal sealed record RoundedBoxTopBoundaryFilletFeature(+ string FeatureId,+ string BodyId,+ double Radius,+ string Face,+ string Target,+ string Kind,+ AirSourceSpan Provenance,+ string Admission = "Admitted");diff --git a/Aetheris.Kernel.Core/Air/ThinWalledBodyAir.cs b/Aetheris.Kernel.Core/Air/ThinWalledBodyAir.csnew file mode 100644index 00000000..35d906bd--- /dev/null+++ b/Aetheris.Kernel.Core/Air/ThinWalledBodyAir.cs@@ -0,0 +1,37 @@+namespace Aetheris.Kernel.Core.Air;++/// <summary>Construction intent, deliberately distinct from a post-construction shell operation.</summary>+public sealed record HollowBodyFeature(+ string PrimitiveKind,+ IReadOnlyDictionary<string, double> PrimitiveParameters,+ double WallThickness,+ IReadOnlyList<string> Openings,+ string ThicknessPolicy,+ HollowConstructionWitness Witness,+ string Provenance);++/// <summary>Primitive-owned proof that its inner boundary can be derived exactly.</summary>+public sealed record HollowConstructionWitness(+ string Kind,+ bool Exact,+ string InnerBoundaryDerivation,+ IReadOnlyList<string> SurfaceCorrespondence,+ IReadOnlyList<string> AdmissibilityEvidence);++/// <summary>Shared paired-boundary construction AIR consumed by the vessel B-rep planner.</summary>+public sealed record ThinWalledBodyConstruction(+ HollowBodyFeature Feature,+ IReadOnlyList<string> OuterBoundaryRoles,+ IReadOnlyList<string> InnerBoundaryRoles,+ IReadOnlyList<string> RimRoles,+ IReadOnlyList<string> ClosedRegionRoles,+ IReadOnlyList<ThinWallThicknessWitness> ThicknessWitnesses,+ string MaterialSide = "between outer and inner boundaries");++public sealed record ThinWallThicknessWitness(+ string Role,+ string OuterSupport,+ string InnerSupport,+ double Distance,+ string OffsetDirection,+ bool Exact = true);diff --git a/Aetheris.Kernel.Core/Brep/RoundedBoxTopologyPlan.cs b/Aetheris.Kernel.Core/Brep/RoundedBoxTopologyPlan.csnew file mode 100644index 00000000..e104ed62--- /dev/null+++ b/Aetheris.Kernel.Core/Brep/RoundedBoxTopologyPlan.cs@@ -0,0 +1,207 @@+using System.Security.Cryptography;+using System.Text;+using Aetheris.Kernel.Core.Diagnostics;+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.Results;+using Aetheris.Kernel.Core.Topology;++namespace Aetheris.Kernel.Core.Brep;++/// <summary>+/// Immutable realization authority for the admitted rounded-box family. It is+/// constructed before the B-rep and its topology roles are consumed directly by+/// the materializer below.+/// </summary>+public sealed record RoundedBoxBRepPlan(+ double Width, double Depth, double Height, double CornerRadius, double? TopFilletRadius,+ IReadOnlyList<string> FaceRoles, IReadOnlyList<string> BoundaryRoles,+ string DeterministicSignature)+{+ public bool IsAuthoritative => true;+ public int ExpectedVertexCount => TopFilletRadius is null ? 16 : 24;+ public int ExpectedEdgeCount => TopFilletRadius is null ? 32 : 48;+ public int ExpectedFaceCount => TopFilletRadius is null ? 10 : 18;+ public int ExpectedLoopCount => ExpectedFaceCount;+ public int ExpectedCoedgeCount => TopFilletRadius is null ? 48 : 96;+}++public sealed record RoundedBoxRealization(RoundedBoxBRepPlan Plan, BrepBody Body);++public static class RoundedBoxBRepPlanner+{+ private const double Tol = 1e-8;+ private static readonly Direction3D PlusX = Direction3D.Create(new Vector3D(1, 0, 0));+ private static readonly Direction3D PlusY = Direction3D.Create(new Vector3D(0, 1, 0));+ private static readonly Direction3D PlusZ = Direction3D.Create(new Vector3D(0, 0, 1));+ private static readonly Direction3D MinusZ = Direction3D.Create(new Vector3D(0, 0, -1));++ public static KernelResult<RoundedBoxRealization> Create(double width, double depth, double height, double cornerRadius, double? topFilletRadius = null)+ {+ var error = Validate(width, depth, height, cornerRadius, topFilletRadius);+ if (error is not null)+ return KernelResult<RoundedBoxRealization>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, error, "RoundedBox.Admission")]);++ var roles = new List<string> { "RoundedBoxBottom", "RoundedBoxTop" };+ roles.AddRange(new[] { "PlanarSide(+X)", "PlanarSide(-Y)", "PlanarSide(-X)", "PlanarSide(+Y)", "RoundedCornerWall(PX_NY)", "RoundedCornerWall(PX_PY)", "RoundedCornerWall(NX_PY)", "RoundedCornerWall(NX_NY)" });+ if (topFilletRadius is double)+ {+ roles.AddRange(Enumerable.Range(0, 4).Select(i => $"TopFilletStraight({i})"));+ roles.AddRange(Enumerable.Range(0, 4).Select(i => $"TopFilletToroidalCorner({i})"));+ }+ var boundaries = Enumerable.Range(0, 8).Select(i => $"TopBoundarySegment({i})").ToArray();+ var signatureSource = FormattableString.Invariant($"RoundedBox|{width:R}|{depth:R}|{height:R}|{cornerRadius:R}|{topFilletRadius?.ToString("R", System.Globalization.CultureInfo.InvariantCulture) ?? "none"}|{string.Join(";", roles)}");+ var plan = new RoundedBoxBRepPlan(width, depth, height, cornerRadius, topFilletRadius, roles, boundaries, Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(signatureSource))).ToLowerInvariant());+ var body = Build(plan);+ var preflight = BrepExportPreflight.Validate(body);+ if (!preflight.IsValid)+ return KernelResult<RoundedBoxRealization>.Failure(preflight.Diagnostics.Where(d => d.Severity == BrepExportPreflightSeverity.Error).Select(d => new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, d.Code, d.Context)).ToArray());+ return KernelResult<RoundedBoxRealization>.Success(new RoundedBoxRealization(plan, body));+ }++ private static string? Validate(double w, double d, double h, double rc, double? rf)+ {+ if (!double.IsFinite(w) || !double.IsFinite(d) || !double.IsFinite(h) || w <= Tol || d <= Tol || h <= Tol) return "RoundedProfileDegenerate";+ if (!double.IsFinite(rc) || rc <= Tol) return "RoundedProfileDegenerate";+ if (rc >= double.Min(w, d) / 2d - Tol) return "RoundedBoxRadiusTooLarge";+ if (rf is null) return null;+ if (!double.IsFinite(rf.Value) || rf.Value <= Tol) return "TopFilletRadiusTooLarge";+ // r < Rc preserves a positive torus major radius; r < h preserves wall.+ if (rf.Value >= double.Min(rc, h) - Tol) return "TopFilletRadiusTooLarge";+ return null;+ }++ private static BrepBody Build(RoundedBoxBRepPlan plan)+ {+ var b = new TopologyBuilder();+ var geometry = new BrepGeometryStore();+ var bindings = new BrepBindingModel();+ var points = new Dictionary<VertexId, Point3D>();+ var a = plan.Width / 2d; var c = plan.Depth / 2d; var z0 = -plan.Height / 2d; var z2 = plan.Height / 2d;+ var r = plan.CornerRadius; var rf = plan.TopFilletRadius ?? 0d; var z1 = z2 - rf;+ var outer = ProfilePoints(a, c, r, 0d);+ var inner = ProfilePoints(a, c, r, rf);+ var rings = plan.TopFilletRadius is null ? 2 : 3;+ var v = new VertexId[rings, 8];+ for (var ring = 0; ring < rings; ring++)+ {+ var z = ring == 0 ? z0 : ring == 1 ? z1 : z2;+ var profile = ring == 2 ? inner : outer;+ for (var i = 0; i < 8; i++) { v[ring, i] = b.AddVertex(); points[v[ring, i]] = new Point3D(profile[i].X, profile[i].Y, z); }+ }++ var bottom = new EdgeId[8]; var outerTop = new EdgeId[8]; var innerTop = plan.TopFilletRadius is null ? outerTop : new EdgeId[8];+ for (var i = 0; i < 8; i++)+ {+ bottom[i] = AddProfileEdge(0, i, v[0, i], v[0, (i + 1) % 8], outer, z0, r, b, geometry, bindings);+ outerTop[i] = AddProfileEdge(10, i, v[1, i], v[1, (i + 1) % 8], outer, z1, r, b, geometry, bindings);+ if (plan.TopFilletRadius is double)+ innerTop[i] = AddProfileEdge(20, i, v[2, i], v[2, (i + 1) % 8], inner, z2, r - rf, b, geometry, bindings);+ }+ var vertical = new EdgeId[8];+ for (var i = 0; i < 8; i++) vertical[i] = AddLine(v[0, i], v[1, i], points, b, geometry, bindings);+ var minor = plan.TopFilletRadius is double ? new EdgeId[8] : [];+ if (plan.TopFilletRadius is double)+ for (var i = 0; i < 8; i++) minor[i] = AddMinorArc(v[1, i], v[2, i], points, b, geometry, bindings);++ var bottomFace = AddLoopFace(b, Reverse(bottom));+ var topFace = AddLoopFace(b, Forward(innerTop));+ var faces = new List<FaceId> { bottomFace, topFace };+ BindSurface(bottomFace, SurfaceGeometry.FromPlane(new PlaneSurface(new Point3D(0, 0, z0), MinusZ, PlusX)), geometry, bindings);+ BindSurface(topFace, SurfaceGeometry.FromPlane(new PlaneSurface(new Point3D(0, 0, z2), PlusZ, PlusX)), geometry, bindings);++ for (var i = 0; i < 8; i++)+ {+ var side = AddLoopFace(b, [new(bottom[i], false), new(vertical[(i + 1) % 8], false), new(outerTop[i], true), new(vertical[i], true)]);+ faces.Add(side);+ BindSurface(side, SideSurface(i, outer[i], outer[(i + 1) % 8], r, a, c, z0), geometry, bindings);+ }+ if (plan.TopFilletRadius is double)+ {+ for (var i = 0; i < 8; i++)+ {+ var finish = AddLoopFace(b, [new(outerTop[i], false), new(minor[(i + 1) % 8], false), new(innerTop[i], true), new(minor[i], true)]);+ faces.Add(finish);+ BindSurface(finish, FinishSurface(i, outer[i], inner[i], r, rf, a, c, z1), geometry, bindings);+ }+ }+ var shell = b.AddShell(faces); b.AddBody([shell]);+ return new BrepBody(b.Model, geometry, bindings, points);+ }++ private static (double X, double Y)[] ProfilePoints(double a, double c, double r, double inset) =>+ [+ (a-r, c-inset), (a-inset, c-r), (a-inset, -c+r), (a-r, -c+inset),+ (-a+r, -c+inset), (-a+inset, -c+r), (-a+inset, c-r), (-a+r, c-inset)+ ];++ private static EdgeId AddProfileEdge(int family, int i, VertexId start, VertexId end, (double X, double Y)[] p, double z, double radius, TopologyBuilder b, BrepGeometryStore g, BrepBindingModel bindings)+ {+ var edge = b.AddEdge(start, end);+ if (i % 2 == 1)+ {+ var a = new Point3D(p[i].X, p[i].Y, z); var endP = new Point3D(p[(i + 1) % 8].X, p[(i + 1) % 8].Y, z);+ AddCurve(edge, CurveGeometry.FromLine(new Line3Curve(a, Direction3D.Create(endP - a))), 0, (endP - a).Length, g, bindings);+ }+ else+ {+ var center = CornerCenter(i, p, radius, z); var startP = new Point3D(p[i].X, p[i].Y, z);+ var circle = new Circle3Curve(center, MinusZ, radius, Direction3D.Create(startP - center));+ AddCurve(edge, CurveGeometry.FromCircle(circle), 0, double.Pi / 2d, g, bindings);+ }+ return edge;+ }++ private static EdgeId AddLine(VertexId start, VertexId end, Dictionary<VertexId, Point3D> points, TopologyBuilder b, BrepGeometryStore g, BrepBindingModel bindings)+ {+ var edge = b.AddEdge(start, end); var a = points[start]; var q = points[end];+ AddCurve(edge, CurveGeometry.FromLine(new Line3Curve(a, Direction3D.Create(q - a))), 0, (q - a).Length, g, bindings); return edge;+ }++ private static EdgeId AddMinorArc(VertexId start, VertexId end, Dictionary<VertexId, Point3D> points, TopologyBuilder b, BrepGeometryStore g, BrepBindingModel bindings)+ {+ var edge = b.AddEdge(start, end); var a = points[start]; var q = points[end];+ var center = new Point3D(q.X, q.Y, a.Z); var radial = Direction3D.Create(a - center);+ var circle = new Circle3Curve(center, Direction3D.Create(radial.ToVector().Cross(PlusZ.ToVector())), (a - center).Length, radial);+ AddCurve(edge, CurveGeometry.FromCircle(circle), 0, double.Pi / 2d, g, bindings); return edge;+ }++ private static SurfaceGeometry SideSurface(int i, (double X, double Y) start, (double X, double Y) end, double r, double a, double c, double z)+ {+ if (i % 2 == 0) return SurfaceGeometry.FromCylinder(new CylinderSurface(CornerCenter(i, ProfilePoints(a, c, r, 0), r, z), PlusZ, r, PlusX));+ var p = new Point3D(start.X, start.Y, z); var tangent = Direction3D.Create(new Vector3D(end.X - start.X, end.Y - start.Y, 0));+ var outward = Direction3D.Create(tangent.ToVector().Cross(PlusZ.ToVector()));+ return SurfaceGeometry.FromPlane(new PlaneSurface(p, outward, PlusZ));+ }++ private static SurfaceGeometry FinishSurface(int i, (double X, double Y) outer, (double X, double Y) inner, double rc, double rf, double a, double c, double z1)+ {+ if (i % 2 == 0)+ return SurfaceGeometry.FromTorus(new TorusSurface(CornerCenter(i, ProfilePoints(a, c, rc, 0), rc, z1), PlusZ, rc - rf, rf, PlusX));+ var tangent = Direction3D.Create(new Vector3D((i == 1 ? 0 : i == 3 ? -1 : i == 5 ? 0 : 1), (i == 1 ? -1 : i == 3 ? 0 : i == 5 ? 1 : 0), 0));+ return SurfaceGeometry.FromCylinder(new CylinderSurface(new Point3D(inner.X, inner.Y, z1), tangent, rf, Direction3D.Create(new Point3D(outer.X, outer.Y, z1) - new Point3D(inner.X, inner.Y, z1))));+ }++ private static Point3D CornerCenter(int i, (double X, double Y)[] p, double radius, double z)+ {+ var s = p[i]; var e = p[(i + 1) % 8];+ // Arc end/start normals identify the unique axis-aligned corner center.+ return i switch+ {+ 0 => new Point3D(s.X, e.Y, z), 2 => new Point3D(e.X, s.Y, z),+ 4 => new Point3D(s.X, e.Y, z), _ => new Point3D(e.X, s.Y, z)+ };+ }++ private static void AddCurve(EdgeId edge, CurveGeometry curve, double start, double end, BrepGeometryStore g, BrepBindingModel bindings)+ { var id = new CurveGeometryId(g.Curves.Count() + 1); g.AddCurve(id, curve); bindings.AddEdgeBinding(new EdgeGeometryBinding(edge, id, new ParameterInterval(start, end))); }+ private static void BindSurface(FaceId face, SurfaceGeometry surface, BrepGeometryStore g, BrepBindingModel bindings)+ { var id = new SurfaceGeometryId(g.Surfaces.Count() + 1); g.AddSurface(id, surface); bindings.AddFaceBinding(new FaceGeometryBinding(face, id)); }+ private static FaceId AddLoopFace(TopologyBuilder b, IReadOnlyList<Use> uses)+ { var loop = b.AllocateLoopId(); var ids = uses.Select(_ => b.AllocateCoedgeId()).ToArray(); for (var i = 0; i < ids.Length; i++) b.AddCoedge(new Coedge(ids[i], uses[i].Edge, loop, ids[(i + 1) % ids.Length], ids[(i + ids.Length - 1) % ids.Length], uses[i].Reverse)); b.AddLoop(new Loop(loop, ids)); return b.AddFace([loop]); }+ private static Use[] Forward(IReadOnlyList<EdgeId> edges) => edges.Select(e => new Use(e, false)).ToArray();+ private static Use[] Reverse(IReadOnlyList<EdgeId> edges) => edges.Reverse().Select(e => new Use(e, true)).ToArray();+ private readonly record struct Use(EdgeId Edge, bool Reverse);+}diff --git a/Aetheris.Kernel.Core/Brep/ThinWalledBodyBRepPlan.cs b/Aetheris.Kernel.Core/Brep/ThinWalledBodyBRepPlan.csnew file mode 100644index 00000000..81ae9577--- /dev/null+++ b/Aetheris.Kernel.Core/Brep/ThinWalledBodyBRepPlan.cs@@ -0,0 +1,179 @@+using System.Security.Cryptography;+using System.Text;+using Aetheris.Kernel.Core.Air;+using Aetheris.Kernel.Core.Diagnostics;+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.Results;+using Aetheris.Kernel.Core.Topology;++namespace Aetheris.Kernel.Core.Brep;++/// <summary>+/// Single topology authority for an admitted open thin-walled vessel. The body is a closed+/// manifold boundary around material; the top is an opening into its cavity, closed by a rim.+/// It is intentionally built from paired supports, never inferred from occupancy subtraction.+/// </summary>+public sealed record ThinWalledBodyBRepPlan(+ string PrimitiveKind,+ IReadOnlyList<string> OuterFaces,+ IReadOnlyList<string> InnerFaces,+ IReadOnlyList<string> RimFaces,+ IReadOnlyList<string> ClosedFaces,+ IReadOnlyList<string> OpeningLoops,+ IReadOnlyList<ThinWallThicknessWitness> ThicknessWitnesses,+ string DeterministicSignature)+{+ public bool IsAuthoritative => true;+ public string Kind => "ThinWalledBody";+}++public sealed record ThinWalledBodyRealization(+ HollowBodyFeature Feature,+ ThinWalledBodyConstruction Construction,+ ThinWalledBodyBRepPlan Plan,+ BrepBody Body);++public static class ThinWalledBodyBRepPlanner+{+ private const double Tol = 1e-8;+ private static readonly Direction3D PlusX = Direction3D.Create(new Vector3D(1, 0, 0));+ private static readonly Direction3D PlusY = Direction3D.Create(new Vector3D(0, 1, 0));+ private static readonly Direction3D PlusZ = Direction3D.Create(new Vector3D(0, 0, 1));+ private static readonly Direction3D MinusZ = Direction3D.Create(new Vector3D(0, 0, -1));++ public static KernelResult<ThinWalledBodyRealization> CreateRoundedBox(double width, double depth, double height, double cornerRadius, double wallThickness)+ {+ if (!FinitePositive(width, depth, height, cornerRadius, wallThickness)) return Failure("RoundedBoxInnerBoundaryDegenerate");+ if (width <= 2d * wallThickness + Tol || depth <= 2d * wallThickness + Tol || height <= wallThickness + Tol) return Failure("WallThicknessTooLarge");+ if (cornerRadius <= wallThickness + Tol) return Failure("RoundedBoxInnerRadiusDegenerate");+ if (cornerRadius >= double.Min(width, depth) / 2d - Tol) return Failure("RoundedBoxRadiusTooLarge");++ var witness = new HollowConstructionWitness("InsetRoundedProfile", true,+ "innerWidth=outerWidth-2T; innerDepth=outerDepth-2T; innerRadius=outerRadius-T; innerBottom=outerBottom+T; innerTop=outerTop",+ ["OuterPlanarWall -> InnerPlanarWall", "OuterCornerCylinder -> InnerCornerCylinder", "OuterBottomPlane -> InnerBottomPlane"],+ ["T>0", "width>2T", "depth>2T", "height>T", "cornerRadius>T"]);+ var feature = new HollowBodyFeature("RoundedBox", new Dictionary<string, double> { ["Width"] = width, ["Depth"] = depth, ["Height"] = height, ["CornerRadius"] = cornerRadius }, wallThickness, ["Top"], "ConstantNormalThickness", witness, "Firmament Primitive<Hollow>");+ var thickness = new List<ThinWallThicknessWitness>();+ thickness.AddRange(Enumerable.Range(0, 4).Select(i => new ThinWallThicknessWitness($"PlanarWall({i})", "Plane", "Plane", wallThickness, "inward normal")));+ thickness.AddRange(Enumerable.Range(0, 4).Select(i => new ThinWallThicknessWitness($"CornerWall({i})", "Cylinder", "Cylinder", wallThickness, "coaxial radial inward")));+ thickness.Add(new ThinWallThicknessWitness("Bottom", "Plane", "Plane", wallThickness, "+Z"));+ var construction = new ThinWalledBodyConstruction(feature,+ ["OuterBottom", .. Enumerable.Range(0, 8).Select(i => $"OuterWall({i})")],+ ["InnerBottom", .. Enumerable.Range(0, 8).Select(i => $"InnerWall({i})")],+ Enumerable.Range(0, 8).Select(i => $"Rim({i})").ToArray(), ["OuterBottom", "InnerBottom"], thickness);+ var plan = MakePlan("RoundedBox", construction, 8, 8, 8, 2, $"{width:R}|{depth:R}|{height:R}|{cornerRadius:R}|{wallThickness:R}");+ var body = BuildRoundedBox(width, depth, height, cornerRadius, wallThickness);+ return Validate(feature, construction, plan, body);+ }++ public static KernelResult<ThinWalledBodyRealization> CreateFrustum(double bottomRadius, double topRadius, double height, double wallThickness)+ {+ if (!FinitePositive(bottomRadius, topRadius, height, wallThickness) || double.Abs(topRadius - bottomRadius) <= Tol) return Failure("FrustumOffsetConeDegenerate");+ var k = (topRadius - bottomRadius) / height;+ var normalScale = double.Sqrt(1d + k * k);+ // Parallel-line form at fixed z. The horizontal decrement is larger than T for a sloped cone,+ // which is precisely why this does not use naive radial shrinking.+ var innerBottom = bottomRadius + k * wallThickness - wallThickness * normalScale;+ var innerTop = topRadius - wallThickness * normalScale;+ if (innerBottom <= Tol) return Failure("FrustumInnerBottomInvalid");+ if (innerTop <= Tol) return Failure("FrustumInnerTopInvalid");+ var witness = new HollowConstructionWitness("ParallelConicalOffset", true,+ "rInner(z)=Rb+kz-T*sqrt(1+k^2), trimmed at z=T and z=H",+ ["OuterConicalWall -> InnerConicalWall", "OuterBottomPlane -> InnerBottomPlane"],+ ["T>0", "frustum is non-cylindrical", "inner bottom radius>0", "inner top radius>0"]);+ var feature = new HollowBodyFeature("Frustum", new Dictionary<string, double> { ["BottomRadius"] = bottomRadius, ["TopRadius"] = topRadius, ["Height"] = height }, wallThickness, ["Top"], "ConstantNormalThickness", witness, "Firmament Primitive<Hollow>");+ var thickness = new[]+ {+ new ThinWallThicknessWitness("ConicalWall", "Cone", "Cone", wallThickness, "inward support normal"),+ new ThinWallThicknessWitness("Bottom", "Plane", "Plane", wallThickness, "+Z")+ };+ var construction = new ThinWalledBodyConstruction(feature, ["OuterConicalWall", "OuterBottom"], ["InnerConicalWall", "InnerBottom"], ["TopAnnularRim"], ["OuterBottom", "InnerBottom"], thickness);+ var plan = MakePlan("Frustum", construction, 2, 2, 1, 2, $"{bottomRadius:R}|{topRadius:R}|{height:R}|{wallThickness:R}|{innerBottom:R}|{innerTop:R}");+ var body = BuildFrustum(bottomRadius, topRadius, height, wallThickness, innerBottom, innerTop, k);+ return Validate(feature, construction, plan, body);+ }++ private static KernelResult<ThinWalledBodyRealization> Validate(HollowBodyFeature feature, ThinWalledBodyConstruction construction, ThinWalledBodyBRepPlan plan, BrepBody body)+ {+ var preflight = BrepExportPreflight.Validate(body);+ if (!preflight.IsValid) return KernelResult<ThinWalledBodyRealization>.Failure(preflight.Diagnostics.Where(d => d.Severity == BrepExportPreflightSeverity.Error).Select(d => new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, d.Code, d.Context)).ToArray());+ return KernelResult<ThinWalledBodyRealization>.Success(new ThinWalledBodyRealization(feature, construction, plan, body));+ }++ private static ThinWalledBodyBRepPlan MakePlan(string primitive, ThinWalledBodyConstruction construction, int outer, int inner, int rim, int closed, string parameters)+ {+ var outerFaces = construction.OuterBoundaryRoles; var innerFaces = construction.InnerBoundaryRoles; var rimFaces = construction.RimRoles; var closedFaces = construction.ClosedRegionRoles;+ var source = $"ThinWalledBody|{primitive}|{parameters}|{string.Join(';', outerFaces)}|{string.Join(';', innerFaces)}|{string.Join(';', rimFaces)}";+ return new(primitive, outerFaces, innerFaces, rimFaces, closedFaces, ["Opening(Top)"], construction.ThicknessWitnesses, Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(source))).ToLowerInvariant());+ }++ private static BrepBody BuildRoundedBox(double width, double depth, double height, double radius, double t)+ {+ var b = new TopologyBuilder(); var g = new BrepGeometryStore(); var bindings = new BrepBindingModel(); var points = new Dictionary<VertexId, Point3D>();+ var outer = ProfilePoints(width / 2d, depth / 2d, radius); var inner = ProfilePoints(width / 2d - t, depth / 2d - t, radius - t);+ var v = new VertexId[4, 8]; var profiles = new[] { outer, outer, inner, inner }; var zs = new[] { 0d, height, t, height };+ for (var ring = 0; ring < 4; ring++) for (var i = 0; i < 8; i++) { v[ring, i] = b.AddVertex(); points[v[ring, i]] = new Point3D(profiles[ring][i].X, profiles[ring][i].Y, zs[ring]); }+ var edges = new EdgeId[4, 8];+ for (var ring = 0; ring < 4; ring++) for (var i = 0; i < 8; i++) edges[ring, i] = AddProfileEdge(v[ring, i], v[ring, (i + 1) % 8], profiles[ring], zs[ring], ring < 2 ? radius : radius - t, i, b, g, bindings);+ var outerVertical = new EdgeId[8]; var innerVertical = new EdgeId[8]; var rim = new EdgeId[8];+ for (var i = 0; i < 8; i++) { outerVertical[i] = AddLine(v[0, i], v[1, i], points, b, g, bindings); innerVertical[i] = AddLine(v[2, i], v[3, i], points, b, g, bindings); rim[i] = AddLine(v[1, i], v[3, i], points, b, g, bindings); }+ var faces = new List<FaceId>();+ var outerBottom = AddFace(b, [Reverse(Row(edges, 0))]); BindPlane(outerBottom, new Point3D(0, 0, 0), MinusZ, g, bindings); faces.Add(outerBottom);+ var innerBottom = AddFace(b, [Forward(Row(edges, 2))]); BindPlane(innerBottom, new Point3D(0, 0, t), PlusZ, g, bindings, false); faces.Add(innerBottom);+ for (var i = 0; i < 8; i++) { var face = AddFace(b, [[new(edges[0, i], false), new(outerVertical[(i + 1) % 8], false), new(edges[1, i], true), new(outerVertical[i], true)]]); BindSurface(face, SideSurface(i, outer, radius, 0d), g, bindings); faces.Add(face); }+ for (var i = 0; i < 8; i++) { var face = AddFace(b, [[new(edges[2, i], false), new(innerVertical[(i + 1) % 8], false), new(edges[3, i], true), new(innerVertical[i], true)]]); BindSurface(face, SideSurface(i, inner, radius - t, t), g, bindings, false); faces.Add(face); }+ for (var i = 0; i < 8; i++) { var face = AddFace(b, [[new(edges[1, i], false), new(rim[(i + 1) % 8], false), new(edges[3, i], true), new(rim[i], true)]]); BindPlane(face, new Point3D(0, 0, height), PlusZ, g, bindings); faces.Add(face); }+ var shell = b.AddShell(faces); b.AddBody([shell]); return new BrepBody(b.Model, g, bindings, points);+ }++ private static BrepBody BuildFrustum(double rb, double rt, double h, double t, double innerBottom, double innerTop, double k)+ {+ var b = new TopologyBuilder(); var g = new BrepGeometryStore(); var bindings = new BrepBindingModel(); var points = new Dictionary<VertexId, Point3D>();+ var radii = new[] { rb, rt, innerBottom, innerTop }; var zs = new[] { 0d, h, t, h }; var vertices = new VertexId[4]; var circles = new EdgeId[4];+ for (var i = 0; i < 4; i++) { vertices[i] = b.AddVertex(); points[vertices[i]] = new Point3D(radii[i], 0, zs[i]); circles[i] = AddCircle(vertices[i], radii[i], zs[i], b, g, bindings); }+ var outerCone = AddFace(b, [Forward([circles[0]]), Reverse([circles[1]])]);+ var innerCone = AddFace(b, [Forward([circles[2]]), Reverse([circles[3]])]);+ var outerBottom = AddFace(b, [Reverse([circles[0]])]);+ var innerBottomFace = AddFace(b, [Forward([circles[2]])]);+ var rim = AddFace(b, [Forward([circles[1]]), Reverse([circles[3]])]);+ var outerSupport = Cone(rb, k); var innerSupport = Cone(rb - t * double.Sqrt(1d + k * k), k);+ BindSurface(outerCone, SurfaceGeometry.FromCone(outerSupport), g, bindings);+ BindSurface(innerCone, SurfaceGeometry.FromCone(innerSupport), g, bindings, false);+ BindPlane(outerBottom, new Point3D(0, 0, 0), MinusZ, g, bindings);+ BindPlane(innerBottomFace, new Point3D(0, 0, t), PlusZ, g, bindings, false);+ BindPlane(rim, new Point3D(0, 0, h), PlusZ, g, bindings);+ var shell = b.AddShell([outerCone, innerCone, outerBottom, innerBottomFace, rim]); b.AddBody([shell]); return new BrepBody(b.Model, g, bindings, points);+ }++ private static ConeSurface Cone(double intercept, double slope)+ {+ var apex = new Point3D(0, 0, -intercept / slope); var axis = slope > 0 ? PlusZ : MinusZ;+ return new ConeSurface(apex, axis, double.Atan(double.Abs(slope)), PlusX);+ }++ private static bool FinitePositive(params double[] values) => values.All(v => double.IsFinite(v) && v > Tol);+ private static KernelResult<ThinWalledBodyRealization> Failure(string code) => KernelResult<ThinWalledBodyRealization>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, code, "ThinWalledBody.Admission")]);+ private static (double X, double Y)[] ProfilePoints(double a, double c, double r) => [(a-r,c), (a,c-r), (a,-c+r), (a-r,-c), (-a+r,-c), (-a,-c+r), (-a,c-r), (-a+r,c)];+ private static EdgeId[] Row(EdgeId[,] edges, int row) => Enumerable.Range(0, 8).Select(i => edges[row, i]).ToArray();+ private static EdgeId AddProfileEdge(VertexId start, VertexId end, (double X, double Y)[] p, double z, double radius, int i, TopologyBuilder b, BrepGeometryStore g, BrepBindingModel bindings)+ {+ var edge = b.AddEdge(start, end);+ if (i % 2 == 1) { var a = new Point3D(p[i].X, p[i].Y, z); var q = new Point3D(p[(i + 1) % 8].X, p[(i + 1) % 8].Y, z); AddCurve(edge, CurveGeometry.FromLine(new Line3Curve(a, Direction3D.Create(q - a))), 0, (q - a).Length, g, bindings); }+ else { var center = CornerCenter(i, p, z); var a = new Point3D(p[i].X, p[i].Y, z); AddCurve(edge, CurveGeometry.FromCircle(new Circle3Curve(center, MinusZ, radius, Direction3D.Create(a - center))), 0, double.Pi / 2d, g, bindings); }+ return edge;+ }+ private static EdgeId AddCircle(VertexId vertex, double radius, double z, TopologyBuilder b, BrepGeometryStore g, BrepBindingModel bindings) { var edge = b.AddEdge(vertex, vertex); AddCurve(edge, CurveGeometry.FromCircle(new Circle3Curve(new Point3D(0, 0, z), PlusZ, radius, PlusX)), 0, 2d * double.Pi, g, bindings); return edge; }+ private static EdgeId AddLine(VertexId start, VertexId end, IReadOnlyDictionary<VertexId, Point3D> points, TopologyBuilder b, BrepGeometryStore g, BrepBindingModel bindings) { var edge=b.AddEdge(start,end); var a=points[start]; var q=points[end]; AddCurve(edge,CurveGeometry.FromLine(new Line3Curve(a,Direction3D.Create(q-a))),0,(q-a).Length,g,bindings); return edge; }+ private static Point3D CornerCenter(int i, (double X, double Y)[] p, double z) => i switch { 0 => new(p[i].X,p[(i+1)%8].Y,z), 2 => new(p[(i+1)%8].X,p[i].Y,z), 4 => new(p[i].X,p[(i+1)%8].Y,z), _ => new(p[(i+1)%8].X,p[i].Y,z) };+ private static SurfaceGeometry SideSurface(int i, (double X, double Y)[] profile, double radius, double z) { if (i % 2 == 0) return SurfaceGeometry.FromCylinder(new CylinderSurface(CornerCenter(i, profile, z), PlusZ, radius, PlusX)); var a=new Point3D(profile[i].X,profile[i].Y,z); var q=new Point3D(profile[(i+1)%8].X,profile[(i+1)%8].Y,z); var tangent=Direction3D.Create(q-a); return SurfaceGeometry.FromPlane(new PlaneSurface(a,Direction3D.Create(tangent.ToVector().Cross(PlusZ.ToVector())),PlusZ)); }+ private static void AddCurve(EdgeId edge, CurveGeometry curve, double start, double end, BrepGeometryStore g, BrepBindingModel bindings) { var id=new CurveGeometryId(g.Curves.Count()+1); g.AddCurve(id,curve); bindings.AddEdgeBinding(new EdgeGeometryBinding(edge,id,new ParameterInterval(start,end))); }+ private static void BindSurface(FaceId face, SurfaceGeometry surface, BrepGeometryStore g, BrepBindingModel bindings, bool sameSense=true) { var id=new SurfaceGeometryId(g.Surfaces.Count()+1); g.AddSurface(id,surface); bindings.AddFaceBinding(new FaceGeometryBinding(face,id,sameSense)); }+ private static void BindPlane(FaceId face, Point3D origin, Direction3D normal, BrepGeometryStore g, BrepBindingModel bindings, bool sameSense=true) => BindSurface(face, SurfaceGeometry.FromPlane(new PlaneSurface(origin,normal,PlusX)),g,bindings,sameSense);+ private static FaceId AddFace(TopologyBuilder b, IReadOnlyList<IReadOnlyList<Use>> loops) { var ids=new List<LoopId>(); foreach(var uses in loops) { var loop=b.AllocateLoopId(); var coedges=uses.Select(_=>b.AllocateCoedgeId()).ToArray(); for(var i=0;i<coedges.Length;i++) b.AddCoedge(new Coedge(coedges[i],uses[i].Edge,loop,coedges[(i+1)%coedges.Length],coedges[(i+coedges.Length-1)%coedges.Length],uses[i].Reverse)); b.AddLoop(new Loop(loop,coedges)); ids.Add(loop); } return b.AddFace(ids); }+ private static Use[] Forward(IReadOnlyList<EdgeId> edges) => edges.Select(e=>new Use(e,false)).ToArray();+ private static Use[] Reverse(IReadOnlyList<EdgeId> edges) => edges.Reverse().Select(e=>new Use(e,true)).ToArray();+ private readonly record struct Use(EdgeId Edge, bool Reverse);+}diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentHollowPolicyTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentHollowPolicyTests.csnew file mode 100644index 00000000..054a5046--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentHollowPolicyTests.cs@@ -0,0 +1,33 @@+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class FirmamentHollowPolicyTests+{+ [Fact]+ public void RoundedBoxHollow_ParsesAsConstrainedConstructionPolicy()+ {+ var result = FirmamentV2Parser.Parse("""+ Struct Enclosure {+ RoundedBox<Hollow> Body {+ Size: [120mm, 80mm, 24mm]+ CornerRadius: 12mm+ WallThickness: 2mm+ Openings: [Top]+ }+ }+ """);+ Assert.True(result.IsSuccess, string.Join(", ", result.Diagnostics));+ Assert.Equal(FirmamentV2ConstructionPolicy.Hollow, result.Document!.Solid.ConstructionPolicy);+ Assert.Equal(2, result.Document.Solid.Hollow!.WallThickness);+ }++ [Fact]+ public void HollowPolicy_RejectsUnsupportedWitnessAndMultipleOpenings()+ {+ var unsupported = FirmamentV2Parser.Parse("Struct X { Box<Hollow> B { Size: [1mm,1mm,1mm] WallThickness: 1mm Openings: [Top] } }");+ Assert.Contains(FirmamentV2Parser.PrimitiveDoesNotSatisfyHollowConstructible, unsupported.Diagnostics);+ var openings = FirmamentV2Parser.Parse("Struct X { Frustum<Hollow> B { BottomRadius: 32mm TopRadius: 43mm Height: 90mm WallThickness: 2mm Openings: [Top, Bottom] } }");+ Assert.Contains(FirmamentV2Parser.MultipleOpeningsNotSupported, openings.Diagnostics);+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/RoundedBoxFirmamentTests.cs b/Aetheris.Kernel.Firmament.Tests/RoundedBoxFirmamentTests.csnew file mode 100644index 00000000..d8eb1a80--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/RoundedBoxFirmamentTests.cs@@ -0,0 +1,37 @@+using Aetheris.Kernel.Firmament;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class RoundedBoxFirmamentTests+{+ [Fact]+ public void DirectRoundedBoxSyntax_PreservesPrimitiveAndTopFilletAsSeparateStages()+ {+ var source = """+ Struct Enclosure {+ RoundedBox Body { Size: [120mm, 80mm, 18mm] CornerRadius: 12mm }+ Modify Body { EdgeFinish TopRound { Face: +Z Target: Boundary Kind: Fillet Radius: 2mm } }+ }+ """;+ var path = Path.Combine(Path.GetTempPath(), $"aetheris-rounded-box-{Guid.NewGuid():N}.firmament");+ try+ {+ File.WriteAllText(path, source);+ var result = FirmamentBuildAndExport.Run(path, Path.ChangeExtension(path, ".step"));+ Assert.True(result.IsSuccess);+ Assert.NotNull(result.Value.Export.RoundedBox);+ Assert.Equal("RoundedBoxFeature", result.Value.Export.RoundedBox!.Primitive.FeatureAir);+ Assert.Equal("RoundedRectangleProfile -> LinearSweep", result.Value.Export.RoundedBox.Primitive.ConstructionAir);+ Assert.Equal(4, result.Value.Export.RoundedBox.Primitive.CylindricalCornerWallFaces);+ Assert.Equal(4, result.Value.Export.RoundedBox.EdgeFinish!.ToroidalCornerFaces);+ Assert.True(result.Value.Export.RoundedBox.Geometry.AnalyticVolume > 0d);+ Assert.Equal("valid", result.Value.Export.RoundedBox.Geometry.Preflight);+ Assert.True(result.Value.Export.RoundedBox.Step.ReimportSucceeded);+ }+ finally+ {+ if (File.Exists(path)) File.Delete(path);+ var step = Path.ChangeExtension(path, ".step"); if (File.Exists(step)) File.Delete(step);+ }+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex 5deb11f8..9b32e7ce 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -57,6 +57,16 @@ public static class FirmamentBuildAndExportreturn KernelResult<FirmamentStepExportResult>.Failure(dfm.Diagnostics);}+ if (TryExportV2HollowBody(v2Parse.Document) is { } hollowExport)+ {+ return hollowExport;+ }++ if (TryExportV2RoundedBoxBody(v2Parse.Document) is { } roundedBoxExport)+ {+ return roundedBoxExport;+ }+if (TryExportV2AirChamferBody(v2Parse.Document) is { } airChamferExport){return airChamferExport;@@ -140,8 +150,10 @@ public static class FirmamentBuildAndExportvar trimmedSource = sourceText.TrimStart();var isV2ModelSource = trimmedSource.StartsWith("model ", StringComparison.Ordinal)|| trimmedSource.StartsWith("Model ", StringComparison.Ordinal)+ || (trimmedSource.StartsWith("Struct ", StringComparison.Ordinal) && sourceText.Contains("<Hollow>", StringComparison.Ordinal))|| sourceText.Contains("\nmodel ", StringComparison.Ordinal)- || sourceText.Contains("\nModel ", StringComparison.Ordinal);+ || sourceText.Contains("\nModel ", StringComparison.Ordinal)+ || (sourceText.Contains("\nStruct ", StringComparison.Ordinal) && sourceText.Contains("<Hollow>", StringComparison.Ordinal));if (isV2ModelSource && fatalV2Diagnostics.Length > 0){return KernelResult<FirmamentStepExportResult>.Failure(fatalV2Diagnostics.Select(code => new Kernel.Core.Diagnostics.KernelDiagnostic(@@ -176,10 +188,21 @@ public static class FirmamentBuildAndExportreturn AirChamferFailure("localized-fillet-junction-unsupported-history:expected-history-known-box");return ExportV2LocalizedEdgeJunctionFillet(document, junctionSolid, finishes[0].Finish, finishes[1].Finish, junctionBox);}+ if (finishes.Length == 3 && finishes.All(x => string.Equals(x.Finish.Kind, "Fillet", StringComparison.Ordinal)))+ {+ if (document.Solids.Count != 1 || document.ModifyBlocks!.Count != 1 || document.ModifyBlocks[0].Regions.Count != 0 || document.ModifyBlocks[0].SemanticHoles.Count != 0)+ return AirChamferFailure("localized-trihedral-fillet-production-route-requires-one-box-and-one-modify-block");+ var junctionSolid = document.Solids.SingleOrDefault(s => s.Name == finishes[0].Modify.TargetSolid);+ if (junctionSolid?.Primitive is not FirmamentV2BoxRecord junctionBox || junctionBox.Size.Count != 3)+ return AirChamferFailure("localized-trihedral-fillet-unsupported-history:expected-history-known-box");+ return ExportV2LocalizedTrihedralFillet(document, junctionSolid, finishes.Select(x => x.Finish).ToArray(), junctionBox);+ }+ if (finishes.Length == 3)+ return AirChamferFailure("localized-trihedral-fillet-unsupported-finish-combination:mixed-families");if (finishes.Length == 2)return AirChamferFailure("localized-junction-unsupported-finish-combination:mixed-families");if (finishes.Length > 2)- return AirChamferFailure("localized-junction-unsupported-valence:two-selected-edges-maximum");+ return AirChamferFailure("localized-trihedral-fillet-unsupported-valence:three-selected-edges-maximum");if (finishes.Length != 1 || document.Solids.Count != 1 || document.ModifyBlocks!.Count != 1|| document.ModifyBlocks[0].Regions.Count != 0 || document.ModifyBlocks[0].SemanticHoles.Count != 0)return AirChamferFailure("air-chamfer-production-route-requires-one-box-and-one-edge-finish");@@ -392,6 +415,211 @@ public static class FirmamentBuildAndExportreturn KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, $"{solid.Name}.{first.Name}.{second.Name}", 0, "air-fillet", "localized-edge-junction-fillet", Air: report, ConceptIr: document.ConceptIr));}+ private static KernelResult<FirmamentStepExportResult>? TryExportV2HollowBody(FirmamentV2Document document)+ {+ if (document.Solids.Count != 1 || document.Solid.ConstructionPolicy != FirmamentV2ConstructionPolicy.Hollow)+ return null;+ var solid = document.Solid;+ if (solid.Hollow is null || solid.Hollow.Openings.Count != 1 || solid.Hollow.Openings[0] != "Top")+ return HollowFailure("UnsupportedOpening");++ KernelResult<ThinWalledBodyRealization> realization = solid.Primitive switch+ {+ FirmamentV2RoundedBoxRecord rounded when rounded.Size.Count == 3 => ThinWalledBodyBRepPlanner.CreateRoundedBox(rounded.Size[0], rounded.Size[1], rounded.Size[2], rounded.CornerRadius, solid.Hollow.WallThickness),+ FirmamentV2FrustumRecord frustum => ThinWalledBodyBRepPlanner.CreateFrustum(frustum.BottomRadius, frustum.TopRadius, frustum.Height, solid.Hollow.WallThickness),+ _ => throw new InvalidOperationException("Parser admitted a Hollow policy without a HollowConstructible witness.")+ };+ if (!realization.IsSuccess || realization.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(realization.Diagnostics);+ var body = realization.Value.Body;+ var preflight = BrepExportPreflight.Validate(body);+ if (!preflight.IsValid) return HollowFailure("VerificationFailure");+ if (!FirmamentManifoldChecker.IsManifold(body)) return HollowFailure("VerificationFailure: vessel boundary is not a closed manifold");+ var step = Step242Exporter.ExportBody(body, new Step242ExportOptions+ {+ ProductName = solid.Name,+ ApplicationName = "Aetheris.Firmament.Primitive<Hollow>",+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce,+ BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,+ });+ if (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);+ var reimport = Step242Importer.ImportBody(step.Value);+ if (!reimport.IsSuccess || reimport.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(reimport.Diagnostics);+ var reimportedManifold = FirmamentManifoldChecker.IsManifold(reimport.Value);+ if (!reimportedManifold) return HollowFailure("VerificationFailure: STEP reimport vessel boundary is not manifold");+ var surfaces = body.Geometry.Surfaces.Select(x => x.Value.Kind).ToArray();+ var r = realization.Value;+ var volume = r.Feature.PrimitiveKind == "RoundedBox"+ ? RoundedHollowVolume((FirmamentV2RoundedBoxRecord)solid.Primitive, r.Feature.WallThickness)+ : FrustumHollowVolume((FirmamentV2FrustumRecord)solid.Primitive, r.Feature.WallThickness);+ var report = new FirmamentHollowBodyReport(r.Feature.PrimitiveKind, "Hollow", r.Feature.WallThickness, r.Feature.Openings, r.Feature.Witness.Kind, r.Feature.Witness.Exact,+ r.Feature.ThicknessPolicy, r.Construction.ThicknessWitnesses.All(w => w.Exact && double.Abs(w.Distance - r.Feature.WallThickness) <= 1e-9), r.Plan.Kind, r.Plan.IsAuthoritative, r.Plan.DeterministicSignature,+ body.Topology.Vertices.Count(), body.Topology.Edges.Count(), body.Topology.Faces.Count(), surfaces.Count(x => x == SurfaceGeometryKind.Plane), surfaces.Count(x => x == SurfaceGeometryKind.Cylinder), surfaces.Count(x => x == SurfaceGeometryKind.Cone), r.Plan.RimFaces.Count,+ volume, Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))), true, reimportedManifold);+ return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, solid.Name, 0, "air-hollow", "thin-walled-body", Hollow: report));+ }++ private static string RoundedHollowVolume(FirmamentV2RoundedBoxRecord rounded, double t)+ {+ var outerArea = RoundedRectangleArea(rounded.Size[0], rounded.Size[1], rounded.CornerRadius);+ var innerArea = RoundedRectangleArea(rounded.Size[0] - 2d * t, rounded.Size[1] - 2d * t, rounded.CornerRadius - t);+ var analytic = outerArea * rounded.Size[2] - innerArea * (rounded.Size[2] - t);+ var numerical = RoundedRectangleAreaNumerical(rounded.Size[0], rounded.Size[1], rounded.CornerRadius) * rounded.Size[2]+ - RoundedRectangleAreaNumerical(rounded.Size[0] - 2d * t, rounded.Size[1] - 2d * t, rounded.CornerRadius - t) * (rounded.Size[2] - t);+ return FormattableString.Invariant($"analytic={analytic:R};numericalSimpson={numerical:R};delta={double.Abs(analytic - numerical):R}");+ }++ private static string FrustumHollowVolume(FirmamentV2FrustumRecord frustum, double t)+ {+ var k = (frustum.TopRadius - frustum.BottomRadius) / frustum.Height;+ var q = t * double.Sqrt(1d + k * k);+ var ib = frustum.BottomRadius + k * t - q; var it = frustum.TopRadius - q;+ var outer = double.Pi * frustum.Height * (frustum.BottomRadius * frustum.BottomRadius + frustum.BottomRadius * frustum.TopRadius + frustum.TopRadius * frustum.TopRadius) / 3d;+ var innerHeight = frustum.Height - t;+ var inner = double.Pi * innerHeight * (ib * ib + ib * it + it * it) / 3d;+ var analytic = outer - inner;+ var numerical = Simpson(0d, frustum.Height, z => double.Pi * double.Pow(frustum.BottomRadius + k * z, 2d))+ - Simpson(t, frustum.Height, z => double.Pi * double.Pow(frustum.BottomRadius + k * z - q, 2d));+ return FormattableString.Invariant($"analytic={analytic:R};numericalSimpson={numerical:R};delta={double.Abs(analytic - numerical):R}");+ }++ private static double RoundedRectangleArea(double width, double depth, double radius) => width * depth - (4d - double.Pi) * radius * radius;++ private static double RoundedRectangleAreaNumerical(double width, double depth, double radius)+ {+ // Parameterizing each quarter-circle by theta avoids the square-root endpoint singularity+ // of direct Cartesian sampling, while still providing an independent numerical integral.+ var straight = (width - 2d * radius) * depth;+ var cornerBands = 4d * radius * (depth / 2d - radius);+ var quarterCircleIntegral = Simpson(0d, double.Pi / 2d, theta => double.Cos(theta) * double.Cos(theta));+ return straight + cornerBands + 4d * radius * radius * quarterCircleIntegral;+ }++ private static double Simpson(double start, double end, Func<double, double> f)+ {+ const int segments = 16384; // even; deterministic numerical evidence, independent of closed-form volume.+ var step = (end - start) / segments; var sum = f(start) + f(end);+ for (var i = 1; i < segments; i++) sum += (i % 2 == 0 ? 2d : 4d) * f(start + i * step);+ return sum * step / 3d;+ }++ private static KernelResult<FirmamentStepExportResult> HollowFailure(string message) =>+ KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, message, "FirmamentV2.Hollow")]);++ private static KernelResult<FirmamentStepExportResult>? TryExportV2RoundedBoxBody(FirmamentV2Document document)+ {+ if (document.Solids.Count != 1 || document.Solids[0].Primitive is not FirmamentV2RoundedBoxRecord rounded || rounded.Size.Count != 3)+ return null;+ var solid = document.Solids[0];+ var finishes = (document.ModifyBlocks ?? []).SelectMany(m => m.EdgeFinishes ?? []).ToArray();+ if (finishes.Length > 1) return RoundedBoxFailure("unsupported top/whole-body or mixed edge-finish request");+ double? fillet = null;+ if (finishes.Length == 1)+ {+ var finish = finishes[0];+ if (!string.Equals(finish.FaceAxis, "+Z", StringComparison.Ordinal) || !string.Equals(finish.Target, "Boundary", StringComparison.Ordinal) || !string.Equals(finish.Kind, "Fillet", StringComparison.Ordinal))+ return RoundedBoxFailure("UnsupportedSupportPair");+ fillet = finish.Distance;+ }+ var realization = RoundedBoxBRepPlanner.Create(rounded.Size[0], rounded.Size[1], rounded.Size[2], rounded.CornerRadius, fillet);+ if (!realization.IsSuccess || realization.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(realization.Diagnostics);+ var body = realization.Value.Body; var plan = realization.Value.Plan;+ if (!FirmamentManifoldChecker.IsManifold(body)) return RoundedBoxFailure("VerificationFailure: rounded-box body is not manifold");+ var step = Step242Exporter.ExportBody(body, new Step242ExportOptions+ {+ ProductName = solid.Name,+ ApplicationName = "AIR-ROUNDED-BOX-M6",+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce,+ BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,+ });+ if (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);+ var imported = Step242Importer.ImportBody(step.Value);+ if (!imported.IsSuccess || imported.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(imported.Diagnostics);+ if (!FirmamentManifoldChecker.IsManifold(imported.Value)) return RoundedBoxFailure("VerificationFailure: STEP reimport is not manifold");+ var surfaces = body.Geometry.Surfaces.Select(x => x.Value.Kind).ToArray();+ var preflight = BrepExportPreflight.Validate(body);+ var report = new FirmamentRoundedBoxReport(+ new("RoundedBoxFeature", "RoundedRectangleProfile -> LinearSweep", rounded.Size[0], rounded.Size[1], rounded.Size[2], rounded.CornerRadius,+ 4, surfaces.Count(x => x == SurfaceGeometryKind.Cylinder) - (fillet is null ? 0 : 4), false),+ fillet is null ? null : new("TopBoundary", "Fillet", fillet.Value, 4, 4, rounded.CornerRadius - fillet.Value, fillet.Value,+ $"torus axis=+Z; center is each corner cylinder axis at z=top-{fillet.Value:R}; major=Rc-Rf={rounded.CornerRadius - fillet.Value:R}; minor=Rf={fillet.Value:R}; v=pi/2 is the top-plane trim and v=0 is the retained corner-cylinder trim."),+ new(plan.IsAuthoritative, plan.DeterministicSignature, plan.ExpectedVertexCount, plan.ExpectedEdgeCount, plan.ExpectedFaceCount, plan.ExpectedLoopCount, plan.ExpectedCoedgeCount, plan.FaceRoles),+ new(Bounds(body), true, surfaces.Count(x => x == SurfaceGeometryKind.Plane), surfaces.Count(x => x == SurfaceGeometryKind.Cylinder), surfaces.Count(x => x == SurfaceGeometryKind.Torus), RoundedBoxAnalyticVolume(rounded.Size[0], rounded.Size[1], rounded.Size[2], rounded.CornerRadius, fillet), preflight.IsValid ? "valid" : "invalid"),+ new(Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))), true, true, imported.Value.Topology.Faces.Count(), Bounds(imported.Value)));+ return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, solid.Name, 0, "air-rounded-box", fillet is null ? "rounded-box-primitive" : "rounded-box-top-boundary-fillet", RoundedBox: report));+ }++ private static KernelResult<FirmamentStepExportResult> RoundedBoxFailure(string message) =>+ KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, message, "FirmamentV2.RoundedBox")]);++ // Exact volume of the admitted family. Each straight finish removes a+ // square-minus-quarter-circle section; each corner is that section swept+ // through a quadrant about the corner-cylinder axis.+ private static double RoundedBoxAnalyticVolume(double width, double depth, double height, double cornerRadius, double? topFilletRadius)+ {+ var primitive = (width * depth - ((4d - double.Pi) * cornerRadius * cornerRadius)) * height;+ if (topFilletRadius is not double r) return primitive;+ var section = r * r * (1d - double.Pi / 4d);+ var straightRemoval = section * (2d * ((width - 2d * cornerRadius) + (depth - 2d * cornerRadius)));+ var cornerFirstMoment = r * r * r * (5d / 6d - double.Pi / 4d);+ var cornerRemoval = 2d * double.Pi * ((cornerRadius * section) - cornerFirstMoment);+ return primitive - straightRemoval - cornerRemoval;+ }++ private static KernelResult<FirmamentStepExportResult> ExportV2LocalizedTrihedralFillet(+ FirmamentV2Document document,+ FirmamentV2SolidBinding solid,+ IReadOnlyList<FirmamentV2EdgeFinishDecl> finishes,+ FirmamentV2BoxRecord box)+ {+ // The compiler owns canonical classification; source order carries no topology meaning.+ var xz = finishes.SingleOrDefault(f => string.Equals(f.FaceAxis, "+X", StringComparison.Ordinal) && string.Equals(f.Target, "SharedEdgePlusZ", StringComparison.Ordinal));+ var yz = finishes.SingleOrDefault(f => string.Equals(f.FaceAxis, "+Y", StringComparison.Ordinal) && string.Equals(f.Target, "SharedEdgePlusZ", StringComparison.Ordinal));+ var xy = finishes.SingleOrDefault(f => string.Equals(f.FaceAxis, "+X", StringComparison.Ordinal) && string.Equals(f.Target, "SharedEdgePlusY", StringComparison.Ordinal));+ if (xz is null || yz is null || xy is null)+ return AirChamferFailure("localized-trihedral-fillet-edges-do-not-share-canonical-vertex");+ var compiled = AirLocalizedTrihedralFilletCompiler.Compile(new(+ solid.Name, $"{solid.Name}.{xz.Name}.{yz.Name}.{xy.Name}", $"{xz.Name}+{yz.Name}+{xy.Name}", box.Size[0], box.Size[1], box.Size[2],+ xz.FaceAxis, xz.Target, yz.FaceAxis, yz.Target, xy.FaceAxis, xy.Target, xz.Distance, yz.Distance, xy.Distance,+ new AirSourceSpan(xz.SourceSpan.Start, xz.SourceSpan.Length + yz.SourceSpan.Length + xy.SourceSpan.Length, document.ModelName)));+ if (!compiled.Succeeded || compiled.Body is null || compiled.Construction is null || compiled.BRepPlan?.LocalizedEdgeJunctionRealizationPlan is null)+ return AirChamferFailure(compiled.Error?.Code ?? "localized-trihedral-fillet-spherical-octant-required", compiled.Diagnostics);++ var body = compiled.Body;+ var preflight = BrepExportPreflight.Validate(body);+ if (!preflight.IsValid) return AirChamferFailure("localized-trihedral-fillet-preflight-verification-failed", preflight.Diagnostics.Select(d => d.Code));+ if (!FirmamentManifoldChecker.IsManifold(body)) return AirChamferFailure("localized-trihedral-fillet-emitted-body-is-not-manifold");+ var step = Step242Exporter.ExportBody(body, new Step242ExportOptions+ {+ ProductName = compiled.Construction.ConstructionId,+ ApplicationName = AirLocalizedTrihedralFilletCompileResult.ProductionRoute,+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce,+ BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,+ });+ if (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);+ var reimport = Step242Importer.ImportBody(step.Value);+ if (!reimport.IsSuccess || reimport.Value is null || !FirmamentManifoldChecker.IsManifold(reimport.Value))+ return AirChamferFailure("localized-trihedral-fillet-step-reimport-verification-failed", reimport.Diagnostics.Select(d => d.Message));++ var topology = compiled.Construction.TopologyPlan;+ var cylinders = body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Cylinder);+ var spheres = body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Sphere);+ var planes = body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Plane);+ var report = new FirmamentAirChamferReport(+ new("Fillet", solid.Name, $"{solid.Name}.{xz.Name}.{yz.Name}.{xy.Name}", $"{xz.Name}+{yz.Name}+{xy.Name}", "SharedEdge(+X,+Z),SharedEdge(+Y,+Z),SharedEdge(+X,+Y)", xz.Distance, "mm",+ $"{xz.SourceSpan.Start}:{xz.SourceSpan.Length}|{yz.SourceSpan.Start}:{yz.SourceSpan.Length}|{xy.SourceSpan.Start}:{xy.SourceSpan.Length}", "Admitted", "localized-trihedral-fillet-spherical-octant-candidate",+ new Dictionary<string, string> { ["Selection"] = "semantic Face(+X),Face(+Z); Face(+Y),Face(+Z); Face(+X),Face(+Y)", ["MaterialSide"] = compiled.Construction.MaterialSide, ["SphereCenter"] = $"({compiled.Construction.SphericalCornerPatch.Center.X:R},{compiled.Construction.SphericalCornerPatch.Center.Y:R},{compiled.Construction.SphericalCornerPatch.Center.Z:R})", ["Continuity"] = "G0=Exact;G1=normal-deviation:0" }),+ new("LocalizedTrihedralFillet", 0, [], "ordered-explicit-loops", "SphereCylinderSharedSeams",+ "replacementFaces=3;junctionFaces=1;sharedEdges=3;patch=SphericalOctant;G0=Exact;G1=WithinTolerance", true),+ new(true, topology.ExpectedVertexCount, topology.ExpectedEdgeCount, topology.ExpectedFaceCount, topology.ExpectedLoopCount, topology.ExpectedCoedgeCount, 0,+ "SphereCylinderSharedSeams", topology.DeterministicSignature, "LocalizedEdgeJunction"),+ new(AirLocalizedTrihedralFilletCompileResult.ProductionRoute, false, true, body.Topology.Vertices.Count(), body.Topology.Edges.Count(), body.Topology.Faces.Count(), Bounds(body), xz.Distance, xz.Distance, cylinders, 0, planes, spheres),+ new("AP242", Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))), true, reimport.Value.Topology.Vertices.Count(), reimport.Value.Topology.Edges.Count(), reimport.Value.Topology.Faces.Count(), Bounds(reimport.Value), true),+ LocalizedEdgeJunction: new(["SharedEdge(+X,+Z)", "SharedEdge(+Y,+Z)", "SharedEdge(+X,+Y)"], "Fillet", "EqualConstantRadius", xz.Distance, "Direct", "LocalizedTrihedralFillet", "SphericalOctant", 3, 1,+ new(true, topology.DeterministicSignature), "valid", false, 1, 1,+ new("SphericalOctant", "Sphere", "Cylinder", "Circle", true, 3, "+X,+Y,+Z octant")));+ return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, $"{solid.Name}.{xz.Name}.{yz.Name}.{xy.Name}", 0, "air-fillet", "localized-trihedral-fillet", Air: report, ConceptIr: document.ConceptIr));+ }+private static KernelResult<FirmamentStepExportResult> ExportV2LocalizedTangentBlendSingleEdgeFillet(FirmamentV2Document document,FirmamentV2SolidBinding solid,diff --git a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.csindex 02c6fc3c..5ea9cb18 100644--- a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs+++ b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs@@ -14,7 +14,47 @@ public sealed record FirmamentStepExportResult(Aetheris.Kernel.Firmament.FirmamentV2.InlineStepReplacementAssistReport? InlineStepReplacementAssist = null,FirmamentAirChamferReport? Air = null,Aetheris.Kernel.Firmament.FirmamentV2.ConceptIrDocument? ConceptIr = null,- IReadOnlyList<FirmamentHoleFeatureReport>? Features = null);+ IReadOnlyList<FirmamentHoleFeatureReport>? Features = null,+ FirmamentRoundedBoxReport? RoundedBox = null,+ FirmamentHollowBodyReport? Hollow = null);++/// <summary>Export evidence for the generic Primitive<Hollow> path.</summary>+public sealed record FirmamentHollowBodyReport(+ string Primitive,+ string ConstructionPolicy,+ double WallThickness,+ IReadOnlyList<string> Openings,+ string WitnessKind,+ bool WitnessExact,+ string ThicknessPolicy,+ bool ThicknessVerified,+ string BRepPlanKind,+ bool AuthoritativePlan,+ string Signature,+ int Vertices,+ int Edges,+ int Faces,+ int Planes,+ int Cylinders,+ int Cones,+ int RimFaces,+ string AnalyticVolume,+ string StepSha256,+ bool ReimportSucceeded,+ bool ReimportedManifold,+ bool LegacyFallback = false);++public sealed record FirmamentRoundedBoxReport(+ FirmamentRoundedBoxPrimitiveReport Primitive,+ FirmamentRoundedBoxEdgeFinishReport? EdgeFinish,+ FirmamentRoundedBoxPlanReport BRepPlan,+ FirmamentRoundedBoxGeometryReport Geometry,+ FirmamentRoundedBoxStepReport Step);+public sealed record FirmamentRoundedBoxPrimitiveReport(string FeatureAir, string ConstructionAir, double Width, double Depth, double Height, double CornerRadius, int PlanarSideFaces, int CylindricalCornerWallFaces, bool LegacyFallback);+public sealed record FirmamentRoundedBoxEdgeFinishReport(string Target, string Kind, double Radius, int CylindricalStraightFaces, int ToroidalCornerFaces, double ToroidalMajorRadius, double ToroidalMinorRadius, string Derivation);+public sealed record FirmamentRoundedBoxPlanReport(bool Authoritative, string Signature, int Vertices, int Edges, int Faces, int Loops, int Coedges, IReadOnlyList<string> Roles);+public sealed record FirmamentRoundedBoxGeometryReport(string Bounds, bool EnclosedManifold, int Planes, int Cylinders, int Tori, double AnalyticVolume, string Preflight);+public sealed record FirmamentRoundedBoxStepReport(string Sha256, bool ReimportSucceeded, bool ReimportedManifold, int ReimportedFaces, string ReimportedBounds);public sealed record FirmamentHoleFeatureReport(string Name,@@ -135,7 +175,7 @@ public sealed record FirmamentAirChamferConstructionReport(IReadOnlyList<IReadOnlyList<double>>? SharpProfile = null,IReadOnlyList<IReadOnlyList<double>>? ReplacementProfile = null);public sealed record FirmamentAirChamferBRepPlanReport(bool Authoritative, int ExpectedVertices, int ExpectedEdges, int ExpectedFaces, int ExpectedLoops, int ExpectedCoedges, int ChamferFaces, string SplitPolicy, string DeterministicSignature, string? PlanKind = null);-public sealed record FirmamentAirChamferMaterializationReport(string Route, bool LegacyFallback, bool EnclosedManifold, int Vertices, int Edges, int Faces, string Bounds, double MeasuredTopInsetX, double MeasuredTopInsetY, int CylindricalFaces = 0, int ConicalFaces = 0, int PlanarFaces = 0);+public sealed record FirmamentAirChamferMaterializationReport(string Route, bool LegacyFallback, bool EnclosedManifold, int Vertices, int Edges, int Faces, string Bounds, double MeasuredTopInsetX, double MeasuredTopInsetY, int CylindricalFaces = 0, int ConicalFaces = 0, int PlanarFaces = 0, int SphericalFaces = 0);public sealed record FirmamentAirChamferStepReport(string Schema, string Sha256, bool ReimportSucceeded, int ReimportedVertices, int ReimportedEdges, int ReimportedFaces, string ReimportedBounds, bool ReimportedManifold);public sealed record FirmamentPmiInspectionDatum(diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.csindex 730f8c55..8c9cffc0 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs@@ -40,7 +40,12 @@ public sealed record FirmamentV2BoundConceptField(string Name, FirmamentV2Conceppublic sealed record FirmamentV2ManufacturingConceptDeclaration(FirmamentV2ConceptApplication Application, IReadOnlyList<FirmamentV2ConceptField> Fields, FirmamentV2SourceSpan SourceSpan, IReadOnlyList<FirmamentV2BoundConceptField>? BoundFields = null);public sealed record FirmamentV2FeatureConceptDeclaration(string Name, FirmamentV2ConceptApplication Application, IReadOnlyList<FirmamentV2ConceptField> Fields, FirmamentV2SourceSpan SourceSpan, IReadOnlyList<FirmamentV2BoundConceptField>? BoundFields = null);-public sealed record FirmamentV2SolidBinding(string Name, string RecordType, FirmamentV2PrimitiveRecord Primitive, string? DerivedFrom = null, IReadOnlyDictionary<string, IReadOnlyList<double>>? Overrides = null, IReadOnlyDictionary<string, string>? Provenance = null)+public enum FirmamentV2ConstructionPolicy { Solid, Hollow }++/// <summary>Source-owned hollow intent. This is deliberately not a Boolean tool description.</summary>+public sealed record FirmamentV2HollowIntent(double WallThickness, IReadOnlyList<string> Openings, FirmamentV2SourceSpan SourceSpan);++public sealed record FirmamentV2SolidBinding(string Name, string RecordType, FirmamentV2PrimitiveRecord Primitive, string? DerivedFrom = null, IReadOnlyDictionary<string, IReadOnlyList<double>>? Overrides = null, IReadOnlyDictionary<string, string>? Provenance = null, FirmamentV2ConstructionPolicy ConstructionPolicy = FirmamentV2ConstructionPolicy.Solid, FirmamentV2HollowIntent? Hollow = null){public bool IsDerived => !string.IsNullOrWhiteSpace(DerivedFrom);public FirmamentV2BoxRecord? Box => Primitive as FirmamentV2BoxRecord;@@ -48,6 +53,7 @@ public sealed record FirmamentV2SolidBinding(string Name, string RecordType, Firpublic FirmamentV2ConeRecord? Cone => Primitive as FirmamentV2ConeRecord;public FirmamentV2SphereRecord? Sphere => Primitive as FirmamentV2SphereRecord;public FirmamentV2TorusRecord? Torus => Primitive as FirmamentV2TorusRecord;+ public FirmamentV2RoundedBoxRecord? RoundedBox => Primitive as FirmamentV2RoundedBoxRecord;public FirmamentV2InlineStepRecord? InlineStep => Primitive as FirmamentV2InlineStepRecord;}@@ -57,6 +63,10 @@ public sealed record FirmamentV2CylinderRecord(double Radius, double Height) : Fpublic sealed record FirmamentV2ConeRecord(double BottomRadius, double TopRadius, double Height) : FirmamentV2PrimitiveRecord;public sealed record FirmamentV2SphereRecord(double Radius) : FirmamentV2PrimitiveRecord;public sealed record FirmamentV2TorusRecord(double MajorRadius, double MinorRadius) : FirmamentV2PrimitiveRecord;+/// <summary>Silhouette-defined rounded rectangle swept along +Z; CornerRadius is not an edge finish.</summary>+public sealed record FirmamentV2RoundedBoxRecord(IReadOnlyList<double> Size, double CornerRadius) : FirmamentV2PrimitiveRecord;+/// <summary>Exact conical-frustum primitive identity; unlike Cone it cannot silently collapse into a generic primitive name.</summary>+public sealed record FirmamentV2FrustumRecord(double BottomRadius, double TopRadius, double Height) : FirmamentV2PrimitiveRecord;public sealed record FirmamentV2InlineStepRecord(string SourcePath, string NormalizedPath, string ContentHash, bool CanonicalInput, string CanonicalEvidence, ImportedStepTopologyMap TopologyMap) : FirmamentV2PrimitiveRecord;public sealed record ImportedStepTopologyMap(IReadOnlyDictionary<string, string> FaceEntityToFaceId, IReadOnlyDictionary<string, string> FaceIdToFaceEntity){diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.csindex c31286c1..4f3451e0 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs@@ -39,6 +39,12 @@ public static class FirmamentV2Parserpublic const string DfmConceptUnitMismatch = "firmament-v2-dfm-concept-unit-mismatch";public const string DfmMinimumToolRadiusViolation = "firmament-v2-dfm-minimum-tool-radius-violation";public const string Phase3EdgeFinishSyntaxInvalid = "firmament-v2-phase3-edge-finish-syntax-invalid";+ public const string UnknownConstructionPolicy = "firmament-v2-unknown-construction-policy";+ public const string PrimitiveDoesNotSatisfyHollowConstructible = "firmament-v2-primitive-does-not-satisfy-hollow-constructible";+ public const string WallThicknessRequired = "firmament-v2-wall-thickness-required";+ public const string WallThicknessMustBePositive = "firmament-v2-wall-thickness-must-be-positive";+ public const string UnsupportedOpening = "firmament-v2-unsupported-opening";+ public const string MultipleOpeningsNotSupported = "firmament-v2-multiple-openings-not-supported";public const string ConceptUnknownFamily = "firmament-v2-concept-unknown-family";public const string ConceptUnknownConcept = "firmament-v2-concept-unknown-concept";@@ -234,6 +240,12 @@ public static class FirmamentV2Parser}source = templateExpansion.Source;+ if (Regex.IsMatch(source, @"\b(?:RoundedBox|Frustum|Box)\s*<\s*[A-Za-z_][A-Za-z0-9_]*\s*>\s+[A-Za-z_]", RegexOptions.CultureInvariant))+ return ParsePrimitiveConstructionPolicyDocument(source, diagnostics);++ if (Regex.IsMatch(source, @"\bRoundedBox\s+[A-Za-z_]", RegexOptions.CultureInvariant))+ return ParseRoundedBoxModelingDocument(source, diagnostics);+if (Regex.IsMatch(source, @"\bConcept\s+(?:Struct\s+)?[A-Za-z_]", RegexOptions.CultureInvariant)|| Regex.IsMatch(source, @"\b(?:Struct|Model)\s+[A-Za-z_][A-Za-z0-9_]*\s*(?::\s*[A-Za-z_][A-Za-z0-9_]*)?\s*\{", RegexOptions.CultureInvariant))return ParseConceptModelingDocument(source, diagnostics, templateExpansion.Instantiations);@@ -725,7 +737,7 @@ public static class FirmamentV2Parserif (!model.Success || !primitive.Success || !modify.Success || !edge.Success || model.Groups["units"].Value != "mm"|| Regex.Matches(source, @"\b(?:Box|Cylinder)\s+[A-Za-z_]", RegexOptions.CultureInvariant).Count != 1|| Regex.Matches(source, @"\bModify\s+[A-Za-z_]", RegexOptions.CultureInvariant).Count != 1- || edges.Length is < 1 or > 2)+ || edges.Length is < 1 or > 3)diagnostics.Add(Phase3EdgeFinishSyntaxInvalid);if (diagnostics.Contains(Phase3EdgeFinishSyntaxInvalid))@@ -795,6 +807,118 @@ public static class FirmamentV2Parserreturn FirmamentV2ParseResult.Success(document, diagnostics);}+ /// <summary>Bounded direct syntax for AIR-ROUNDED-BOX-M6. It intentionally+ /// accepts only one history-known rounded box and its single complete +Z boundary finish.</summary>+ private static FirmamentV2ParseResult ParseRoundedBoxModelingDocument(string source, List<string> diagnostics)+ {+ var model = Regex.Match(source, @"^\s*(?:Model|Struct)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)(?:\s+(?<units>[A-Za-z_][A-Za-z0-9_]*))?\s*\{?", RegexOptions.CultureInvariant);+ var primitive = Regex.Match(source, @"\bRoundedBox\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);+ if (!model.Success || !primitive.Success || Regex.Matches(source, @"\bRoundedBox\s+[A-Za-z_]", RegexOptions.CultureInvariant).Count != 1)+ return RoundedBoxParseFailure(diagnostics);+ if (model.Groups["units"].Success && model.Groups["units"].Value != "mm") return RoundedBoxParseFailure(diagnostics);+ var open = source.IndexOf('{', primitive.Index); var close = FindMatchingBrace(source, open);+ if (close < 0) return RoundedBoxParseFailure(diagnostics);+ var body = source[(open + 1)..close];+ var size = Regex.Match(body, @"\bSize\s*:\s*\[(?<values>[^\]]+)\]", RegexOptions.CultureInvariant);+ var corner = Regex.Match(body, @"\bCornerRadius\s*:\s*(?<value>[-+0-9.eE]+)mm\b", RegexOptions.CultureInvariant);+ var values = size.Success ? size.Groups["values"].Value.Split(',').Select(ParsePhase3Length).ToArray() : [];+ if (values.Length != 3 || values.Any(v => !double.IsFinite(v) || v <= 0d) || !corner.Success || !double.TryParse(corner.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var rc) || !double.IsFinite(rc) || rc <= 0d || rc >= double.Min(values[0], values[1]) / 2d)+ return RoundedBoxParseFailure(diagnostics);++ var solid = new FirmamentV2SolidBinding(primitive.Groups["name"].Value, "RoundedBox", new FirmamentV2RoundedBoxRecord(values, rc));+ var modifies = Regex.Matches(source, @"\bModify\s+(?<target>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant).Cast<Match>().ToArray();+ if (modifies.Length > 1 || (modifies.Length == 1 && modifies[0].Groups["target"].Value != solid.Name)) return RoundedBoxParseFailure(diagnostics);+ var blocks = new List<FirmamentV2ModifyBlock>();+ if (modifies.Length == 1)+ {+ var modify = modifies[0]; var modifyOpen = source.IndexOf('{', modify.Index); var modifyClose = FindMatchingBrace(source, modifyOpen);+ var finishes = Regex.Matches(source, @"\bEdgeFinish\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant).Cast<Match>().ToArray();+ if (modifyClose < 0 || finishes.Length != 1) return RoundedBoxParseFailure(diagnostics);+ var edge = finishes[0]; var edgeOpen = source.IndexOf('{', edge.Index); var edgeClose = FindMatchingBrace(source, edgeOpen);+ if (edgeClose < 0 || edge.Index < modifyOpen || edgeClose > modifyClose) return RoundedBoxParseFailure(diagnostics);+ var edgeBody = source[(edgeOpen + 1)..edgeClose];+ var face = Regex.Match(edgeBody, @"\bFace\s*:\s*(?<value>[+-][XYZ])", RegexOptions.CultureInvariant);+ var target = Regex.Match(edgeBody, @"\bTarget\s*:\s*(?<value>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant);+ var kind = Regex.Match(edgeBody, @"\bKind\s*:\s*(?<value>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant);+ var radius = Regex.Match(edgeBody, @"\bRadius\s*:\s*(?<value>[-+0-9.eE]+)mm\b", RegexOptions.CultureInvariant);+ if (!face.Success || !target.Success || !kind.Success || !radius.Success || !double.TryParse(radius.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var rf) || !double.IsFinite(rf)) return RoundedBoxParseFailure(diagnostics);+ blocks.Add(new FirmamentV2ModifyBlock(solid.Name, [], [], [new FirmamentV2EdgeFinishDecl(edge.Groups["name"].Value, face.Groups["value"].Value, target.Groups["value"].Value, kind.Groups["value"].Value, rf, new FirmamentV2SourceSpan(edge.Index, edgeClose - edge.Index + 1))]));+ }+ diagnostics.Add("firmament-v2-rounded-box-parsed"); diagnostics.Add("firmament-v2-parse-succeeded"); diagnostics.Sort(StringComparer.Ordinal);+ return FirmamentV2ParseResult.Success(new FirmamentV2Document(model.Groups["name"].Value, "mm", [solid], blocks), diagnostics.Distinct(StringComparer.Ordinal).ToArray());+ }++ private static FirmamentV2ParseResult RoundedBoxParseFailure(List<string> diagnostics)+ {+ diagnostics.Add(Phase3EdgeFinishSyntaxInvalid); diagnostics.Add("firmament-v2-parse-failed");+ return FirmamentV2ParseResult.Failure(diagnostics.Distinct(StringComparer.Ordinal).Order().ToArray());+ }++ /// <summary>+ /// Bounded generic primitive construction syntax. Angle brackets are not a general type-argument escape hatch:+ /// this parser accepts only the named construction policies and witnesses admitted by the production compiler.+ /// </summary>+ private static FirmamentV2ParseResult ParsePrimitiveConstructionPolicyDocument(string source, List<string> diagnostics)+ {+ var model = Regex.Match(source, @"^\s*(?:Struct|Model)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant);+ var primitive = Regex.Match(source, @"\b(?<type>[A-Za-z_][A-Za-z0-9_]*)\s*<\s*(?<policy>[A-Za-z_][A-Za-z0-9_]*)\s*>\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);+ if (!model.Success || !primitive.Success || Regex.Matches(source, @"\b(?:RoundedBox|Frustum|Box)\s*<\s*[A-Za-z_][A-Za-z0-9_]*\s*>\s+[A-Za-z_]", RegexOptions.CultureInvariant).Count != 1)+ return ConstructionPolicyParseFailure(diagnostics);++ var type = primitive.Groups["type"].Value;+ var policy = primitive.Groups["policy"].Value;+ if (policy != "Hollow") { diagnostics.Add(UnknownConstructionPolicy); return ConstructionPolicyParseFailure(diagnostics); }+ if (type is not ("RoundedBox" or "Frustum")) { diagnostics.Add(PrimitiveDoesNotSatisfyHollowConstructible); return ConstructionPolicyParseFailure(diagnostics); }+ var open = source.IndexOf('{', primitive.Index); var close = FindMatchingBrace(source, open);+ if (close < 0) return ConstructionPolicyParseFailure(diagnostics);+ var body = source[(open + 1)..close];+ var thickness = Regex.Match(body, @"\bWallThickness\s*:\s*(?<value>[-+0-9.eE]+)mm\b", RegexOptions.CultureInvariant);+ if (!thickness.Success) { diagnostics.Add(WallThicknessRequired); return ConstructionPolicyParseFailure(diagnostics); }+ if (!double.TryParse(thickness.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var wall) || !double.IsFinite(wall) || wall <= 0d)+ { diagnostics.Add(WallThicknessMustBePositive); return ConstructionPolicyParseFailure(diagnostics); }+ var openings = Regex.Match(body, @"\bOpenings\s*:\s*\[(?<items>[^\]]*)\]", RegexOptions.CultureInvariant);+ var openingItems = openings.Success ? openings.Groups["items"].Value.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries) : [];+ if (openingItems.Length != 1 || openingItems[0] != "Top")+ {+ diagnostics.Add(openingItems.Length > 1 ? MultipleOpeningsNotSupported : UnsupportedOpening);+ return ConstructionPolicyParseFailure(diagnostics);+ }++ FirmamentV2PrimitiveRecord? record = null;+ if (type == "RoundedBox")+ {+ var size = Regex.Match(body, @"\bSize\s*:\s*\[(?<values>[^\]]+)\]", RegexOptions.CultureInvariant);+ var corner = Regex.Match(body, @"\bCornerRadius\s*:\s*(?<value>[-+0-9.eE]+)mm\b", RegexOptions.CultureInvariant);+ var values = size.Success ? size.Groups["values"].Value.Split(',').Select(ParsePhase3Length).ToArray() : [];+ if (values.Length != 3 || values.Any(v => !double.IsFinite(v) || v <= 0d) || !corner.Success || !double.TryParse(corner.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var radius) || !double.IsFinite(radius) || radius <= 0d)+ return ConstructionPolicyParseFailure(diagnostics);+ record = new FirmamentV2RoundedBoxRecord(values, radius);+ }+ else+ {+ double Read(string field)+ {+ var m = Regex.Match(body, $@"\b{field}\s*:\s*(?<value>[-+0-9.eE]+)mm\b", RegexOptions.CultureInvariant);+ return m.Success && double.TryParse(m.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var value) ? value : double.NaN;+ }+ var bottom = Read("BottomRadius"); var top = Read("TopRadius"); var height = Read("Height");+ if (!double.IsFinite(bottom) || !double.IsFinite(top) || !double.IsFinite(height) || bottom <= 0d || top <= 0d || height <= 0d || double.Abs(top - bottom) <= 1e-12d)+ return ConstructionPolicyParseFailure(diagnostics);+ record = new FirmamentV2FrustumRecord(bottom, top, height);+ }++ var hollow = new FirmamentV2HollowIntent(wall, ["Top"], new FirmamentV2SourceSpan(primitive.Index, close - primitive.Index + 1));+ var solid = new FirmamentV2SolidBinding(primitive.Groups["name"].Value, type, record, ConstructionPolicy: FirmamentV2ConstructionPolicy.Hollow, Hollow: hollow);+ diagnostics.Add("firmament-v2-hollow-policy-parsed"); diagnostics.Add("firmament-v2-parse-succeeded"); diagnostics.Sort(StringComparer.Ordinal);+ return FirmamentV2ParseResult.Success(new FirmamentV2Document(model.Groups["name"].Value, "mm", [solid]), diagnostics.Distinct(StringComparer.Ordinal).ToArray());+ }++ private static FirmamentV2ParseResult ConstructionPolicyParseFailure(List<string> diagnostics)+ {+ diagnostics.Add("firmament-v2-parse-failed");+ return FirmamentV2ParseResult.Failure(diagnostics.Distinct(StringComparer.Ordinal).Order().ToArray());+ }+private static FirmamentV2ParseResult ParseConceptModelingDocument(string source, List<string> diagnostics, IReadOnlyList<ConceptIrTemplateInstantiation>? templateInstantiations = null){var resolution = ConceptIrResolver.Resolve(source, diagnostics);@@ -851,7 +975,7 @@ public static class FirmamentV2Parser|| code.StartsWith(ConceptIrResolver.PointProjectionUnsupported, StringComparison.Ordinal)|| code.StartsWith("firmament-static-", StringComparison.Ordinal);- public static bool IsFatalDiagnosticCode(string code) => IsConceptFatalDiagnostic(code) || code is Phase3EdgeFinishSyntaxInvalid or PrimitiveFieldMissing or PrimitiveFieldUnknown or PrimitiveFieldInvalid or MissingModel or MissingUnits or MissingSolid or UnsupportedConstruct or UnknownRecordType or BoxMissingSize or BoxSizeArity or DegenerateDimension or NameUnresolved or DuplicateName or WithRequiresRecord or WithRequiresBoxRecord or WithFieldNotFound or WithFieldTypeMismatch or WithForwardReference or WithDerivedRecordInvalid or ExposeBlockUnsupported or ExposeRequiresBoxRecord or ExposeAliasDuplicate or ExposeAliasInvalid or SelectorUnsupported or SelectorAxisInvalid or SelectorSubselectorUnsupported or FatArrowOutsideExpose or RawBackendIdReferenceForbidden or ModifyTargetUnresolved or ModifyTargetNotSolid or RegionUnsupported or RegionAttachmentSelectorUnsupported or CutUnsupported or CutToolUnsupported or CylinderRadiusMissing or CylinderRadiusInvalid or CylinderRadiusNotFinite or ThroughSelectorUnsupported or AliasUnresolved or AliasRefTypeUnsupported or SideHoleAliasMustResolveToFace or SideHoleAliasResolvesToUnsupportedFace or SideHoleOnlyPlusXMinusXSupported or SideHoleRouteUnsupported or SideHoleSameFaceUnsupported or SideHoleAxisNotYetSupported or SideHoleRadiusExceedsClearance or CylinderCenterInvalid or CylinderCenterArityInvalid or CylinderCenterNotFinite or SideHoleCenterExceedsClearance or HoleVariantUnknown or HoleEntryFaceMissing or HoleCenterMissing or HoleShaftMissing or HoleEndMissing or HoleDiameterInvalid or HoleDepthInvalid or HoleCounterboreInvalid or HoleCountersinkInvalid or PmiKindUnknown or PmiTargetMissing or PmiTargetUnresolved or PmiDiameterInvalid or PmiDuplicateName or InlineStepUnknownBody or InlineStepUnknownFace or PmiImportedTargetNotFace or PmiImportedTargetRequiresCanonicalStep or PmiInvalidImportedTarget or InlineStepPathMissing or InlineStepPathInvalid or InlineStepFileMissing or InlineStepRequiresCanonical or UnknownRecognitionBody or UnknownRecognitionFace or DuplicateRegion or UnknownRecognitionRegion or InvalidRecognitionKind or InvalidRecognitionConfidence or PmiRecognizedRegionKindMismatch or UnknownReplacementBody or UnknownReplacementRegion or ReplacementKindMismatch or ReplacementFaceUnresolved or ReplacementUnsupportedKind or ReplacementVerificationFailed or ReplacementRadiusInvalid or ReplacementEndUnsupported or LetDuplicateName or LetUnknownType or LetTypeMismatch or LetInvalidLiteral or LetUnitMismatch or LetLiteralOnly or LetRecordDuplicateName or LetRecordDuplicateField or LetReferenceUnknownRecord or LetReferenceUnknownField or LetReferenceNonRecord or LetReferenceRecordUsedAsValue or ExpressionUnknownSymbol or ExpressionUnknownRecord or ExpressionUnknownField or ExpressionRecordUsedAsValue or ExpressionScalarUsedAsRecord or ExpressionTypeMismatch or ExpressionInvalidOperator or ExpressionDivisionByZero or ExpressionCycle or ExpressionUnsupported or ToleranceInvalidType or ToleranceUnitMismatch or ToleranceInvalidLiteral or ToleranceNegativeBilateral or ToleranceMissingMinus or ToleranceMissingPlus or ToleranceUnsupported or RecognitionEvidenceRadiusInvalid or RecognitionEvidenceSurfaceFamilyUnknown or RecognitionEvidenceAxisInvalid or SemanticProposalKindMismatch or SemanticProposalRadiusInvalid or SemanticProposalTargetUnresolved or SemanticProposalEndUnsupported or ConceptUnknownFamily or ConceptUnknownConcept or ConceptMissingRequiredField or ConceptUnknownField or ConceptDuplicateField or ConceptFieldTypeMismatch or ConceptInvalidTarget or ConceptDescriptorUnavailable or PmiDuplicateBlock or PmiDuplicateRecord or PmiDuplicateDatum or PmiUnknownRecordKind or PmiMissingRequiredField or PmiUnknownField or PmiDuplicateField or PmiInvalidTarget or PmiUnknownDatum or PmiDimensionTypeMismatch or PmiDimensionMissingTolerance or PmiToleranceTypeMismatch;+ public static bool IsFatalDiagnosticCode(string code) => IsConceptFatalDiagnostic(code) || code is UnknownConstructionPolicy or PrimitiveDoesNotSatisfyHollowConstructible or WallThicknessRequired or WallThicknessMustBePositive or UnsupportedOpening or MultipleOpeningsNotSupported or Phase3EdgeFinishSyntaxInvalid or PrimitiveFieldMissing or PrimitiveFieldUnknown or PrimitiveFieldInvalid or MissingModel or MissingUnits or MissingSolid or UnsupportedConstruct or UnknownRecordType or BoxMissingSize or BoxSizeArity or DegenerateDimension or NameUnresolved or DuplicateName or WithRequiresRecord or WithRequiresBoxRecord or WithFieldNotFound or WithFieldTypeMismatch or WithForwardReference or WithDerivedRecordInvalid or ExposeBlockUnsupported or ExposeRequiresBoxRecord or ExposeAliasDuplicate or ExposeAliasInvalid or SelectorUnsupported or SelectorAxisInvalid or SelectorSubselectorUnsupported or FatArrowOutsideExpose or RawBackendIdReferenceForbidden or ModifyTargetUnresolved or ModifyTargetNotSolid or RegionUnsupported or RegionAttachmentSelectorUnsupported or CutUnsupported or CutToolUnsupported or CylinderRadiusMissing or CylinderRadiusInvalid or CylinderRadiusNotFinite or ThroughSelectorUnsupported or AliasUnresolved or AliasRefTypeUnsupported or SideHoleAliasMustResolveToFace or SideHoleAliasResolvesToUnsupportedFace or SideHoleOnlyPlusXMinusXSupported or SideHoleRouteUnsupported or SideHoleSameFaceUnsupported or SideHoleAxisNotYetSupported or SideHoleRadiusExceedsClearance or CylinderCenterInvalid or CylinderCenterArityInvalid or CylinderCenterNotFinite or SideHoleCenterExceedsClearance or HoleVariantUnknown or HoleEntryFaceMissing or HoleCenterMissing or HoleShaftMissing or HoleEndMissing or HoleDiameterInvalid or HoleDepthInvalid or HoleCounterboreInvalid or HoleCountersinkInvalid or PmiKindUnknown or PmiTargetMissing or PmiTargetUnresolved or PmiDiameterInvalid or PmiDuplicateName or InlineStepUnknownBody or InlineStepUnknownFace or PmiImportedTargetNotFace or PmiImportedTargetRequiresCanonicalStep or PmiInvalidImportedTarget or InlineStepPathMissing or InlineStepPathInvalid or InlineStepFileMissing or InlineStepRequiresCanonical or UnknownRecognitionBody or UnknownRecognitionFace or DuplicateRegion or UnknownRecognitionRegion or InvalidRecognitionKind or InvalidRecognitionConfidence or PmiRecognizedRegionKindMismatch or UnknownReplacementBody or UnknownReplacementRegion or ReplacementKindMismatch or ReplacementFaceUnresolved or ReplacementUnsupportedKind or ReplacementVerificationFailed or ReplacementRadiusInvalid or ReplacementEndUnsupported or LetDuplicateName or LetUnknownType or LetTypeMismatch or LetInvalidLiteral or LetUnitMismatch or LetLiteralOnly or LetRecordDuplicateName or LetRecordDuplicateField or LetReferenceUnknownRecord or LetReferenceUnknownField or LetReferenceNonRecord or LetReferenceRecordUsedAsValue or ExpressionUnknownSymbol or ExpressionUnknownRecord or ExpressionUnknownField or ExpressionRecordUsedAsValue or ExpressionScalarUsedAsRecord or ExpressionTypeMismatch or ExpressionInvalidOperator or ExpressionDivisionByZero or ExpressionCycle or ExpressionUnsupported or ToleranceInvalidType or ToleranceUnitMismatch or ToleranceInvalidLiteral or ToleranceNegativeBilateral or ToleranceMissingMinus or ToleranceMissingPlus or ToleranceUnsupported or RecognitionEvidenceRadiusInvalid or RecognitionEvidenceSurfaceFamilyUnknown or RecognitionEvidenceAxisInvalid or SemanticProposalKindMismatch or SemanticProposalRadiusInvalid or SemanticProposalTargetUnresolved or SemanticProposalEndUnsupported or ConceptUnknownFamily or ConceptUnknownConcept or ConceptMissingRequiredField or ConceptUnknownField or ConceptDuplicateField or ConceptFieldTypeMismatch or ConceptInvalidTarget or ConceptDescriptorUnavailable or PmiDuplicateBlock or PmiDuplicateRecord or PmiDuplicateDatum or PmiUnknownRecordKind or PmiMissingRequiredField or PmiUnknownField or PmiDuplicateField or PmiInvalidTarget or PmiUnknownDatum or PmiDimensionTypeMismatch or PmiDimensionMissingTolerance or PmiToleranceTypeMismatch;private static IReadOnlyList<FirmamentV2Exposure> ParseExposures(string body, List<string> diagnostics){diff --git a/docs/air/air-fillet-trihedral-m5.md b/docs/air/air-fillet-trihedral-m5.mdnew file mode 100644index 00000000..bb20a053--- /dev/null+++ b/docs/air/air-fillet-trihedral-m5.md@@ -0,0 +1,77 @@+# AIR-FILLET-TRIHEDRAL-M5++M5 admits exactly one three-edge fillet junction: a history-known axis-aligned box at+the `(+X,+Y,+Z)` vertex, with `SharedEdge(+X,+Z)`, `SharedEdge(+Y,+Z)`, and+`SharedEdge(+X,+Y)` selected as constant, equal-radius fillets. It is not a+general rolling-ball implementation.++## Exact construction++For box corner `O=(hx,hy,hz)` and radius `R`, the common center is+`C=O-R*(+X,+Y,+Z)`. The XZ, YZ, and XY cylinders have axes `+Y`, `+X`, and+`+Z`, respectively, all with radius `R` and origins on the corresponding axis+through `C`.++Each cylinder intersects the sphere `|P-C|=R` in the coordinate plane through+`C` normal to its cylinder axis. The admitted finite branch is a quarter circle:++- XZ: `y=Cy`, from `(hx,Cy,Cz)` to `(Cx,Cy,hz)`;+- YZ: `x=Cx`, from `(Cx,Cy,hz)` to `(Cx,hy,Cz)`;+- XY: `z=Cz`, from `(Cx,hy,Cz)` to `(hx,Cy,Cz)`.++These three curves close the positive spherical octant. They are exact `CIRCLE`+trims shared by the spherical and cylindrical faces; no full sphere is emitted or+heuristically trimmed.++## AIR and plan ownership++Three semantic `AirEdgeFinishFeature` values lower together into one immutable+`LocalizedTrihedralFilletConstruction`. It owns three cylindrical replacements,+the `SphericalCornerPatchConstruction`, three typed sphere-cylinder seam witnesses,+trimmed retained planes, remote endpoint arcs, material side, provenance, and one+`LocalizedEdgeJunctionTopologyPlan`.++The authoritative plan has 13 vertices, 21 edges, 10 loops/coedge loops, and 10+faces: six planes, three cylinders, and one sphere. Stable roles identify the+three replacement faces, the three sphere-cylinder seams, retained `+X/+Y/+Z`+supports, remote endpoints, and the spherical corner patch. The STEP emitter+consumes that one plan; it does not emit independent fillets and stitch them.++## Proof and preflight++The construction samples each exact seam midpoint and proves both sphere and+cylinder containment, with zero analytical residual. Sphere and cylinder normals+are equal on the seam (`G0` exact and `G1` normal deviation zero); M5 does not+claim G2. Standard Enforce preflight additionally verifies all topology vertex to+trim endpoint agreements, all trim/support containment checks, loop closure, and+shared edge ownership. M5's hard admission verifies the one shared canonical+vertex, planar orthogonal box history, positive equal radii, extent fit, exact+seams, closed patch, and manifold plan before STEP emission.++STEP uses `SPHERICAL_SURFACE`, `CYLINDRICAL_SURFACE`, `PLANE`, and `CIRCLE` /+`TRIMMED_CURVE`. The successful canonical fixture reimports as an enclosed+analytic manifold. Its generated report records the deterministic plan signature+and SHA-256 for the STEP artifact.++The independent analytic removed-volume check is+`(1-pi/4) R^2 ((W-R)+(D-R)+(H-R)) + (1-pi/6) R^3`: three non-overlapping remote+cylindrical strips plus the local `R` cube less its spherical octant. For the+canonical `10 x 8 x 6, R=1` fixture this is `4.983039793055287 mm^3` exactly in+terms of `pi` (the displayed decimal is numerical).++## Boundaries++Supported fixtures are `10 x 8 x 6, R=1`, `10 x 8 x 6, R=2`, and `12 x 5 x 7,+R=1` (millimetres). Invalid radii, overlarge radii, non-sharing selections,+mixed finish families, imported/no-history bodies, concave/non-orthogonal/curved+supports, and valences outside this exact three-edge set are rejected before BRep+or STEP emission.++Unequal radii are deliberately deferred with+`localized-trihedral-fillet-unequal-radius-corner-surface-required`. They are not+claimed to be toroidal: a future milestone must prove an appropriate distinct+corner surface and fixtures before admitting them.++The next recommended edge-finish milestone is a separately proven trihedral+orientation/history classifier (additional convex box corners), not unequal-radius+or generic rolling-ball support.diff --git a/docs/air/air-rounded-box-toroidal-edge-finish-m6.md b/docs/air/air-rounded-box-toroidal-edge-finish-m6.mdnew file mode 100644index 00000000..3103193a--- /dev/null+++ b/docs/air/air-rounded-box-toroidal-edge-finish-m6.md@@ -0,0 +1,80 @@+# AIR-ROUNDED-BOX-M6 — rounded primitive and toroidal top edge finish++## Semantic boundary++`RoundedBox` is a primitive. Its equal `CornerRadius` is part of its two-dimensional silhouette and is lowered as an exact `RoundedRectangleProfile` swept by `LinearSweep` along `+Z`. It is not represented as a sharp box followed by four large fillets.++`EdgeFinish` is a later local modification. In the admitted syntax it selects the complete `+Z` outer boundary and applies one constant-radius `Fillet`:++```firmament+Struct Enclosure {+ RoundedBox Body {+ Size: [120mm, 80mm, 18mm]+ CornerRadius: 12mm+ }++ Modify Body {+ EdgeFinish TopRound {+ Face: +Z+ Target: Boundary+ Kind: Fillet+ Radius: 2mm+ }+ }+}+```++The compiler preserves those as separate feature intents: `RoundedBoxFeature` and `RoundedBoxTopBoundaryFilletFeature`. Source never names B-rep entities.++## Construction and realization++The primitive profile has an ordered closed loop of four exact line segments and four exact quarter-circle arcs. It has stable segment identities and tangent continuity at all eight joins. The linear sweep emits top and bottom planes, four planar side faces, and four cylindrical corner-wall faces.++`RoundedBoxBRepPlan` is the immutable authority before materialization, not a post-emission prediction. Primitive-only topology has 16 vertices, 32 edges, 10 faces, 10 loops, and 48 coedges. The finished top loop has 24 vertices, 48 edges, 18 faces, 18 loops, and 96 coedges. The plan carries stable roles for retained top/bottom, planar sides, rounded cylinder walls, four straight fillets, four toroidal corner fillets, and eight top-boundary segments.++## Complete top-loop fillet++The top boundary is lowered as one ordered eight-segment loop, rather than eight independently stitched operations.++| Boundary support pair | Exact replacement |+| --- | --- |+| top plane + planar side | cylindrical quarter-round face |+| top plane + cylindrical corner wall | toroidal quarter-round face |++For a corner cylinder of radius `Rc`, top fillet `Rf`, corner axis `+Z`, and top height `zt`, the torus uses:++```text+center = corner-cylinder center at z = zt - Rf+axis = +Z+major radius = Rc - Rf+minor radius = Rf+```++At torus minor parameter `v = π/2`, the patch reaches `z = zt` at radial distance `Rc - Rf`: this is the retained top-plane trim. At `v = 0`, it reaches radial distance `Rc` at `z = zt - Rf`: this is the retained cylindrical-corner-wall trim. The same minor quarter circles are shared with the adjacent straight cylindrical fillet faces. Thus each shared boundary is on both supports (G0), and the support normals agree at the top plane and corner cylinder (G1). This is the material-side branch for an outside convex enclosure; no unequal-radius junction rule is involved.++## Admission and preflight++The admitted family is a history-known, axis-aligned positive `+Z` sweep with four equal corner radii and, optionally, exactly one `Face: +Z`, `Target: Boundary`, `Kind: Fillet` edge finish. `Rc < min(width, depth)/2`; when a top fillet exists, `0 < Rf < min(Rc, height)`.++The planner rejects degenerate profiles, oversized corner radius, zero/oversized top radius, and unsupported support-pair/finish selection before it builds topology. `BrepExportPreflightMode.Enforce` checks all shared loop chains, curve endpoints, trim containment on planes/cylinders/tori, and nondegenerate edges. The torus containment formula is explicitly covered by preflight.++Deferred deliberately: unequal/per-corner corner radii, nonrectangular or concave profiles, bottom/both-side finishes, variable radius, imported/no-history bodies, mixed finishes, and a radius which consumes the profile. This milestone makes no claim of arbitrary unequal-radius fillet support.++## Evidence++Canonical command results:++| Fixture | Faces / surfaces | STEP SHA-256 | Reimport |+| --- | --- | --- | --- |+| `rounded_box_basic.firmament` | 10; 6 planes, 4 cylinders, 0 tori; analytic volume `170575.008158 mm³` | `B1A46902EFA998D83F5AB7CD082F845539F7B71370F9E2D40FE1D689EC750F7C` | enclosed, manifold |+| `rounded_box_top_fillet.firmament` | 18; 6 planes, 8 cylinders, 4 tori; analytic volume `170251.739420 mm³` | `02DE113EACDCA270C657B28FF5235BFF3B477B5E64E52013D16A9F0A40372684` | enclosed, manifold |++Both artifacts retain bounds `[-60,-40,-9]..[60,40,9]`; their surface counts and hashes differ, proving the top local finish changed the geometry while preserving the silhouette envelope. The core test matrix also covers `80×50×20 Rc=8 Rf=1`, `150×90×25 Rc=15 Rf=3`, and invalid dimensions/radii.++The reported analytic volume is exact for this admitted family: start with `(W*D - (4-π)*Rc²)*H`, then for `Rf` subtract four straight square-minus-quarter-circle strips and four quarter-annular corner contributions. The generic `aetheris analyze volume` route is not used as evidence here: it currently misclassifies the primitive as a box-with-hole and defers trimmed curved-shell integration for the finished artifact.++CAD Assistant was launched against both hash-tied artifacts. The finished `Rf=2` file reached `Import …: 100%` and reported `Displaying: finished`; the primitive-only file reported `Displaying: finished` but remained at 99% import progress after 20 seconds. This is recorded as an incomplete independent visual smoke for the primitive-only file, not a CAD Assistant pass. Aetheris reimport/preflight is successful for both; re-run the primitive visual smoke in a clean viewer session before claiming independent CAD Assistant acceptance.++## Relationship to rounded web rectangles++The primitive corresponds to an extruded web-style rounded rectangle: its corner radius changes the outer outline. The small top round is closer to a physical enclosure finish: it changes only the post-construction edge neighborhood. Their related curvature does not make them the same compiler feature.diff --git a/docs/air/air-thinwall-hollow-m7.md b/docs/air/air-thinwall-hollow-m7.mdnew file mode 100644index 00000000..96c5b34a--- /dev/null+++ b/docs/air/air-thinwall-hollow-m7.md@@ -0,0 +1,53 @@+# AIR-THINWALL-HOLLOW-M7++`Hollow` is a constrained construction policy on a materialized primitive:++```firmament+RoundedBox<Hollow> Body { ... }+Frustum<Hollow> Body { ... }+```++It is not a policy on `Struct`. A struct can contain bodies, references, ports, and scaffolding, so making a whole struct hollow would be ambiguous. Solid remains the implicit primitive policy. This work does not provide general post-construction `Shell`.++## Doctrine++> A cup is not a cone with a Boolean crime committed inside it.++A hollow body is born as paired outer and inner analytic boundaries. The generic compiler owns the common `WallThickness`, `Openings: [Top]`, correspondence, rim, face-sense, common admission, and reporting semantics. Each admitted primitive supplies an immutable `HollowConstructionWitness` describing how its exact inner boundary is derived. The emitted `ThinWalledBodyBRepPlan` is the sole topology authority; there is no outer-solid/minus-inner-solid lowering and no safe-Boolean or legacy-shell route.++M7 admits exactly one top opening. Empty opening lists, multiple openings, side openings, and arbitrary face selections are rejected. Closed inaccessible cavities and general shelling remain deferred.++## Proof families++`RoundedBox<Hollow>` reuses the rounded-rectangle linear-sweep family. With thickness `T`, its witness proves the orthogonal offset equations:++```text+inner width = outer width - 2T+inner depth = outer depth - 2T+inner radius = outer radius - T+inner bottom = outer bottom + T+inner top = outer top+```++The plan has eight outer walls (four planes and four cylinders), eight paired inner walls, two bottom planes, and eight exact top-rim faces. It rejects `T <= 0`, consumed width/depth/height, and `cornerRadius <= T`.++`Frustum<Hollow>` uses a true parallel cone, not radial scaling. For `r(z)=Rb+kz`, `k=(Rt-Rb)/H`, the inner support is:++```text+rInner(z) = r(z) - T sqrt(1+k^2)+```++and is trimmed at `z=T` and `z=H`. The offset has support-normal distance `T`; merely subtracting `T` from both radii would not. M7 rejects the cylindrical degeneracy and any non-positive trimmed inner radius.++## Authority and export evidence++Feature AIR retains primitive parameters, policy, wall thickness, opening intent, provenance, and witness. Construction AIR retains outer/inner roles, rim roles, closed-bottom roles, and per-support thickness witnesses. The shared vessel plan owns vertices, edges, loops, coedges, face roles, analytic supports, opening loop, and deterministic signature.++The production route invokes `BrepExportPreflightMode.Enforce`, emits planes/cylinders/circles for the rounded vessel and planes/cones/circles for the frustum vessel, then reimports the STEP artifact. Canonical fixture evidence is produced by:++```text+testdata/firmament/air-thinwall-m7/rounded-enclosure.firmament+testdata/firmament/air-thinwall-m7/frustum-cup.firmament+```++The CLI reports the witness, exactness, topology and surface counts, deterministic plan signature, analytic volume expression, STEP SHA-256, and reimport result. Independent CAD Assistant inspection is not automated by this repository route and is therefore pending external review; no CAD Assistant admission is claimed here.diff --git a/testdata/firmament/air-thinwall-m7/frustum-cup-variation.firmament b/testdata/firmament/air-thinwall-m7/frustum-cup-variation.firmamentnew file mode 100644index 00000000..e67f8d70--- /dev/null+++ b/testdata/firmament/air-thinwall-m7/frustum-cup-variation.firmament@@ -0,0 +1,9 @@+Struct InwardCup {+ Frustum<Hollow> Body {+ BottomRadius: 40mm+ TopRadius: 30mm+ Height: 70mm+ WallThickness: 1.5mm+ Openings: [Top]+ }+}diff --git a/testdata/firmament/air-thinwall-m7/frustum-cup.firmament b/testdata/firmament/air-thinwall-m7/frustum-cup.firmamentnew file mode 100644index 00000000..9e39fa3d--- /dev/null+++ b/testdata/firmament/air-thinwall-m7/frustum-cup.firmament@@ -0,0 +1,9 @@+Struct Cup {+ Frustum<Hollow> Body {+ BottomRadius: 32mm+ TopRadius: 43mm+ Height: 90mm+ WallThickness: 2mm+ Openings: [Top]+ }+}diff --git a/testdata/firmament/air-thinwall-m7/invalid-multiple-openings.firmament b/testdata/firmament/air-thinwall-m7/invalid-multiple-openings.firmamentnew file mode 100644index 00000000..75fabfca--- /dev/null+++ b/testdata/firmament/air-thinwall-m7/invalid-multiple-openings.firmament@@ -0,0 +1,9 @@+Struct InvalidCup {+ Frustum<Hollow> Body {+ BottomRadius: 32mm+ TopRadius: 43mm+ Height: 90mm+ WallThickness: 2mm+ Openings: [Top, Bottom]+ }+}diff --git a/testdata/firmament/air-thinwall-m7/invalid-wall-zero.firmament b/testdata/firmament/air-thinwall-m7/invalid-wall-zero.firmamentnew file mode 100644index 00000000..5f5a8290--- /dev/null+++ b/testdata/firmament/air-thinwall-m7/invalid-wall-zero.firmament@@ -0,0 +1,8 @@+Struct InvalidWall {+ RoundedBox<Hollow> Body {+ Size: [120mm, 80mm, 24mm]+ CornerRadius: 12mm+ WallThickness: 0mm+ Openings: [Top]+ }+}diff --git a/testdata/firmament/air-thinwall-m7/rounded-enclosure-variation.firmament b/testdata/firmament/air-thinwall-m7/rounded-enclosure-variation.firmamentnew file mode 100644index 00000000..50f9f2d1--- /dev/null+++ b/testdata/firmament/air-thinwall-m7/rounded-enclosure-variation.firmament@@ -0,0 +1,8 @@+Struct EnclosureVariation {+ RoundedBox<Hollow> Body {+ Size: [80mm, 50mm, 18mm]+ CornerRadius: 8mm+ WallThickness: 1.5mm+ Openings: [Top]+ }+}diff --git a/testdata/firmament/air-thinwall-m7/rounded-enclosure.firmament b/testdata/firmament/air-thinwall-m7/rounded-enclosure.firmamentnew file mode 100644index 00000000..ad490239--- /dev/null+++ b/testdata/firmament/air-thinwall-m7/rounded-enclosure.firmament@@ -0,0 +1,8 @@+Struct Enclosure {+ RoundedBox<Hollow> Body {+ Size: [120mm, 80mm, 24mm]+ CornerRadius: 12mm+ WallThickness: 2mm+ Openings: [Top]+ }+}diff --git a/testdata/firmament/examples/rounded_box_basic.firmament b/testdata/firmament/examples/rounded_box_basic.firmamentnew file mode 100644index 00000000..4e084606--- /dev/null+++ b/testdata/firmament/examples/rounded_box_basic.firmament@@ -0,0 +1,6 @@+Struct Enclosure {+ RoundedBox Body {+ Size: [120mm, 80mm, 18mm]+ CornerRadius: 12mm+ }+}diff --git a/testdata/firmament/examples/rounded_box_top_fillet.firmament b/testdata/firmament/examples/rounded_box_top_fillet.firmamentnew file mode 100644index 00000000..2cf51a67--- /dev/null+++ b/testdata/firmament/examples/rounded_box_top_fillet.firmament@@ -0,0 +1,15 @@+Struct Enclosure {+ RoundedBox Body {+ Size: [120mm, 80mm, 18mm]+ CornerRadius: 12mm+ }++ Modify Body {+ EdgeFinish TopRound {+ Face: +Z+ Target: Boundary+ Kind: Fillet+ Radius: 2mm+ }+ }+}