Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add profile composition inspection and preserve STEP loop roles
Yuechen Li3078bfbd4ddb
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 4c1d6c32..82c592de 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -112,10 +112,11 @@ public static class CliRunnerstring? Error,string? Classification = null,int? RigidRootCount = null);- private const string TopLevelUsage = "Usage: aetheris <build|validate|inspect-profile|analyze|verify|match|trace|canon|asm|experimental> <path> [options]";+ private const string TopLevelUsage = "Usage: aetheris <build|validate|inspect-profile|inspect-compose|analyze|verify|match|trace|canon|asm|experimental> <path> [options]";private const string BuildUsage = "Usage: aetheris build <file.firmament> [--out <path>] [--json]";private const string ValidateUsage = "Usage: aetheris validate <file.firmament|file.firmfixture> [--forge-pack <path>] [--json]";private const string InspectProfileUsage = "Usage: aetheris inspect-profile <file.firmament> [--json]";+ private const string InspectComposeUsage = "Usage: aetheris inspect-compose <file.firmament> [--json]";private const string AnalyzeUsage = "Usage: aetheris analyze <file.step> [--face <id>] [--edge <id>] [--vertex <id>] [--json]";private const string AnalyzeMapUsage = "Usage: aetheris analyze map <file.step> (--plane <xy|xz|yz> --direction <+x|-x|+y|-y|+z|-z> | --views six --llm) --resolution <NxM> [--point <u,v>] [--rank-probes|--evidence-bundle] --json";private const string AnalyzeSectionUsage = "Usage: aetheris analyze section <file.step> (--xy|--xz|--yz) --offset <value> --json";@@ -173,6 +174,7 @@ public static class CliRunner"build" => RunBuild(args.Skip(1).ToArray(), stdout, stderr),"validate" => RunValidate(args.Skip(1).ToArray(), stdout, stderr),"inspect-profile" => RunInspectProfile(args.Skip(1).ToArray(), stdout, stderr),+ "inspect-compose" => RunInspectCompose(args.Skip(1).ToArray(), stdout, stderr),"analyze" => RunAnalyze(args.Skip(1).ToArray(), stdout, stderr),"verify" => RunVerify(args.Skip(1).ToArray(), stdout, stderr),"match" => RunMatch(args.Skip(1).ToArray(), stdout, stderr),@@ -417,7 +419,11 @@ public static class CliRunner{parsed.Profile.Name, parsed.Profile.PlaneFrame,loops = parsed.Profile.Loops.Count,- segments = parsed.Profile.Loops.SelectMany(x => x.Segments).Select(x => new { x.Name, guide = x.Provenance.ConceptStableId, stableId = x.Provenance.StableId, derivation = x.Provenance.Derivation, geometry = x.Geometry.GetType().Name }),+ segments = parsed.Profile.Loops.SelectMany(x => x.Segments).Select(x =>+ {+ var guide = DescribeProfileGuide(x.Provenance.ConceptStableId);+ return new { x.Name, guide = guide.Name, guideKind = guide.Kind, parentGuide = guide.Parent, stableId = x.Provenance.StableId, derivation = x.Provenance.Derivation, geometry = x.Geometry.GetType().Name };+ }),validation.IsValid, validation.SignedArea, validation.Diagnostics,extrusionHeight = parsed.Height}@@ -426,6 +432,77 @@ public static class CliRunnerreturn validation.IsValid ? 0 : 1;}+ private static (string Name, string Kind, string? Parent) DescribeProfileGuide(string stableId)+ {+ const string prefix = "concept:";+ var path = stableId.StartsWith(prefix, StringComparison.Ordinal) ? stableId[prefix.Length..] : stableId;+ var components = path.Split('.', StringSplitOptions.RemoveEmptyEntries);+ if (components.Length >= 3 && components[^1] is "Top" or "Bottom" or "Left" or "Right")+ {+ return ($"{components[^2]}.{components[^1]}", "Rect2Side", components[^2]);+ }++ return (stableId, "ConceptGuide", null);+ }++ private static int RunInspectCompose(string[] args, TextWriter stdout, TextWriter stderr)+ {+ if (args.Length == 0 || IsHelpFlag(args[0])) { stdout.WriteLine(InspectComposeUsage); return args.Length == 0 ? 1 : 0; }+ var json = args.Skip(1).All(x => x == "--json");+ if (!json) { stderr.WriteLine(InspectComposeUsage); return 1; }+ if (!File.Exists(args[0])) { stderr.WriteLine($"Composition source was not found: {args[0]}"); return 1; }+ var parsed = PrismaticProfileCompositionParser.Parse(File.ReadAllText(args[0]));+ var stack = PrismaticSectionStackCompiler.Normalize(parsed, out var diagnostics);+ if (stack is null) { stderr.WriteLine(string.Join(Environment.NewLine, diagnostics)); return 1; }+ var emitted = PrismaticSectionStackEmitter.Emit(stack);+ var mass = emitted.Body is null ? null : BrepMassProperties.Evaluate(emitted.Body);+ var report = new+ {+ composition = new+ {+ name = stack.Feature.Name, frame = stack.Feature.Frame, axis = stack.Feature.Axis,+ operations = stack.Feature.Operations.Select(x => new { x.Name, intent = x.Intent.ToString(), profile = x.ProfileReference, x.From, x.To, x.SemanticRole, x.SourceSpan }),+ criticalLevels = stack.Feature.CriticalLevels,+ slabs = stack.Slabs.Select(x => new+ {+ x.From,+ x.To,+ x.ActiveOperations,+ area = PrismaticSectionStackCompiler.Area(x.Region),+ outerLoops = 1,+ innerLoops = x.Region.Holes.Count,+ loops = new[]+ {+ new { role = "Outer", signedAreaInProfileFrame = PrismaticSectionStackCompiler.ProfileArea(x.Region.Outer), sourceWinding = PrismaticSectionStackCompiler.ProfileArea(x.Region.Outer) >= 0d ? "CounterClockwise" : "Clockwise", materialFacingWinding = "CounterClockwise" }+ }.Concat(x.Region.Holes.Select(h => new { role = "Inner", signedAreaInProfileFrame = PrismaticSectionStackCompiler.ProfileArea(h), sourceWinding = PrismaticSectionStackCompiler.ProfileArea(h) >= 0d ? "CounterClockwise" : "Clockwise", materialFacingWinding = "Clockwise" })),+ lineSegments = x.Region.Outer.Loops[0].Segments.Count(s => s.Geometry is LineArcLineSegment2D),+ arcSegments = x.Region.Outer.Loops[0].Segments.Count(s => s.Geometry is LineArcCircularArc2D)+ , arrangement = x.Arrangement is null ? null : new+ {+ sourceSegmentCount = x.Arrangement.SourceCurves.Count,+ intersectionVertexCount = x.Arrangement.IntersectionVertices.Count,+ atomicFragmentCount = x.Arrangement.AtomicFragments.Count,+ coincidentFragmentCount = x.Arrangement.CoincidentFragmentCount,+ retainedBoundaryFragmentCount = x.Arrangement.RetainedBoundaryFragmentCount,+ resultLoopCount = x.Arrangement.ResultLoops.Count,+ perimeter = x.Arrangement.ResultLoops.Sum(loop => loop.Perimeter),+ timingsMilliseconds = new { intersections = x.Arrangement.IntersectionTime.TotalMilliseconds, splitting = x.Arrangement.SplitTime.TotalMilliseconds, classification = x.Arrangement.ClassificationTime.TotalMilliseconds, reconstruction = x.Arrangement.ReconstructionTime.TotalMilliseconds },+ provenance = x.Region.Provenance,+ diagnostics = x.Arrangement.Diagnostics+ }+ }),+ transitions = stack.Transitions.Select(x => new { x.Level, upwardArea = x.UpwardRegion is null ? 0d : PrismaticSectionStackCompiler.Area(x.UpwardRegion), downwardArea = x.DownwardRegion is null ? 0d : PrismaticSectionStackCompiler.Area(x.DownwardRegion) }),+ analyticVolume = stack.AnalyticVolume,+ bRepVolume = mass?.AbsoluteVolume,+ volumeDelta = mass is null ? (double?)null : mass.AbsoluteVolume - stack.AnalyticVolume,+ bRepPlan = emitted.Plan,+ diagnostics = emitted.Diagnostics+ }+ };+ stdout.WriteLine(JsonSerializer.Serialize(report, JsonOptions));+ return 0;+ }+private static int RunValidate(string[] args, TextWriter stdout, TextWriter stderr){if (args.Length == 0)@@ -2428,6 +2505,7 @@ public static class CliRunnerstdout.WriteLine(" build Build a .firmament source file into STEP.");stdout.WriteLine(" validate Validate Firmament V2 manufacturing intent and emit report JSON.");stdout.WriteLine(" inspect-profile Resolve and validate a scaffold-referenced Profile.");+ stdout.WriteLine(" inspect-compose Normalize and inspect a profile-composition section stack.");stdout.WriteLine(" analyze Analyze STEP topology, geometry, map, and sections.");stdout.WriteLine(" verify Reimport STEP and emit independent B-rep/external-display evidence.");stdout.WriteLine(" match Match a compile-time Concept Struct against observed STEP geometry.");diff --git a/Aetheris.Kernel.Core/Step242/Step242Importer.cs b/Aetheris.Kernel.Core/Step242/Step242Importer.csindex 3bc49f8b..246d3ef0 100644--- a/Aetheris.Kernel.Core/Step242/Step242Importer.cs+++ b/Aetheris.Kernel.Core/Step242/Step242Importer.cs@@ -1629,20 +1629,61 @@ public static class Step242Importerreturn KernelResult<IReadOnlyList<LoopBuildData>>.Success(loops);}+ // STEP carries loop role explicitly: FACE_OUTER_BOUND is not a hint to be+ // replaced by an area/winding heuristic. Reordering or reversing a+ // declared EDGE_LOOP here loses source topology and can turn a void into+ // material after a round trip. The legacy classifier is used only as a+ // derivative validator when a declared outer bound exists; its rewritten+ // traversal is never substituted for the imported evidence.+ var declaredOuterCount = loops.Count(loop => loop.IsDeclaredOuter);+ if (declaredOuterCount == 1)+ {+ if (surface.Kind == SurfaceGeometryKind.Sphere)+ {+ // A spherical lattice node uses multiple trim loops as source+ // topology rather than a planar material-region-with-hole. It+ // has an explicit outer-bound declaration, so retain that+ // evidence without inventing a planar containment model.+ return KernelResult<IReadOnlyList<LoopBuildData>>.Success(loops);+ }++ // Keep the declared traversal authoritative, but still run the+ // established geometric classifier as a *derivative validator*.+ // Besides rejecting a declared hole outside its outer bound, this+ // retains the periodic-surface projection diagnostics used by the+ // corpus tests. Its normalized output is deliberately discarded:+ // import must not silently reorder or reverse STEP evidence.+ var validation = surface.Kind switch+ {+ SurfaceGeometryKind.Plane => ClassifyAndNormalizePlanarLoops(loops, surface.Plane!.Value),+ SurfaceGeometryKind.Cylinder => ClassifyAndNormalizeCylindricalLoops(faceEntityId, loops, surface.Cylinder!.Value),+ SurfaceGeometryKind.Torus => ClassifyAndNormalizeToroidalLoops(faceEntityId, loops, surface.Torus!.Value),+ SurfaceGeometryKind.Cone => ClassifyAndNormalizeConicalLoops(faceEntityId, loops, surface.Cone!.Value),+ _ => LoopRoleFailure<IReadOnlyList<LoopBuildData>>(+ $"Multi-loop hole classification is unsupported for surface type '{surface.Kind}'.",+ $"Importer.LoopRole.UnsupportedSurfaceForHoles.{surface.Kind}")+ };++ return validation.IsSuccess+ ? KernelResult<IReadOnlyList<LoopBuildData>>.Success(loops)+ : KernelResult<IReadOnlyList<LoopBuildData>>.Failure(validation.Diagnostics);+ }+ if (declaredOuterCount > 1)+ {+ return LoopRoleFailure<IReadOnlyList<LoopBuildData>>(+ $"FACE has {declaredOuterCount} FACE_OUTER_BOUND declarations; exactly one is required.",+ $"Importer.LoopRole.DuplicateDeclaredOuter.Face:{faceEntityId}");+ }+return surface.Kind switch{SurfaceGeometryKind.Plane => ClassifyAndNormalizePlanarLoops(loops, surface.Plane!.Value),SurfaceGeometryKind.Cylinder => ClassifyAndNormalizeCylindricalLoops(faceEntityId, loops, surface.Cylinder!.Value),SurfaceGeometryKind.Torus => ClassifyAndNormalizeToroidalLoops(faceEntityId, loops, surface.Torus!.Value),SurfaceGeometryKind.Cone => ClassifyAndNormalizeConicalLoops(faceEntityId, loops, surface.Cone!.Value),- // A sphere has no privileged planar-style outer loop. In particular,- // a constructive lattice node carries one disjoint circular trim for- // every incident member. The STEP face preserves each loop's exact- // orientation already, so deterministic loop-id order is sufficient- // and avoids inventing a containment relationship on a periodic- // spherical parameter domain.- SurfaceGeometryKind.Sphere => KernelResult<IReadOnlyList<LoopBuildData>>.Success(- loops.OrderBy(loop => loop.LoopId.Value).ToArray()),+ SurfaceGeometryKind.Sphere => LoopRoleFailure<IReadOnlyList<LoopBuildData>>(+ "Multi-loop spherical faces require an explicit FACE_OUTER_BOUND declaration.",+ "Importer.LoopRole.UnsupportedSurfaceForHoles.Sphere"),_ => LoopRoleFailure<IReadOnlyList<LoopBuildData>>($"Multi-loop hole classification is unsupported for surface type '{surface.Kind}'.",$"Importer.LoopRole.UnsupportedSurfaceForHoles.{surface.Kind}")diff --git a/Aetheris.Kernel.Firmament.Tests/PrismaticProfileCompositionRoundTripTests.cs b/Aetheris.Kernel.Firmament.Tests/PrismaticProfileCompositionRoundTripTests.csnew file mode 100644index 00000000..01b7a95d--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/PrismaticProfileCompositionRoundTripTests.cs@@ -0,0 +1,144 @@+using Aetheris.Kernel.Core.Brep.Verification;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.Materializer;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class PrismaticProfileCompositionRoundTripTests+{+ [Fact]+ public void MixedLineArcAdditiveOverlap_PreservesAnalyticCurvesAcrossStepRoundTrip()+ {+ var source = File.ReadAllText(Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "fixtures", "FirmamentV2", "ProfileComposition", "mixed-line-arc-additive-overlap.firmament")));+ var parsed = PrismaticProfileCompositionParser.Parse(source);+ Assert.Empty(parsed.Diagnostics);+ var stack = Assert.IsType<PrismaticSectionStackConstruction>(PrismaticSectionStackCompiler.Normalize(parsed, out var diagnostics));+ Assert.Empty(diagnostics);+ var top = Assert.Single(stack.Slabs.Where(x => x.From == 10d && x.To == 15d));+ Assert.Equal(458.72298071147134d, PrismaticSectionStackCompiler.Area(top.Region), 8);+ Assert.NotNull(top.Arrangement);+ Assert.Equal(4, top.Region.Outer.Loops[0].Segments.Count(x => x.Geometry is LineArcCircularArc2D));+ Assert.True(top.Arrangement!.AtomicFragments.Count > top.Arrangement.RetainedBoundaryFragmentCount);+ Assert.Contains(top.Arrangement.AtomicFragments, x => x.Source.Segment == "ArcEast" && x.StableId.EndsWith("part1", StringComparison.Ordinal));++ var emitted = PrismaticSectionStackEmitter.Emit(stack);+ Assert.DoesNotContain(emitted.Diagnostics, x => x.Contains("rejected", StringComparison.Ordinal));+ var body = Assert.IsType<Aetheris.Kernel.Core.Brep.BrepBody>(emitted.Body);+ var inMemory = BrepMassProperties.Evaluate(body);+ Assert.True(inMemory.IsEnclosed, string.Join(" | ", inMemory.Diagnostics));+ Assert.InRange(Math.Abs(inMemory.AbsoluteVolume - stack.AnalyticVolume), 0d, 0.01d);+ Assert.Equal(4, body.Geometry.Surfaces.Count(x => x.Value.Kind == Aetheris.Kernel.Core.Geometry.SurfaceGeometryKind.Cylinder));+ var step = Step242Exporter.ExportBody(body, new Step242ExportOptions { BrepExportPreflightMode = BrepExportPreflightMode.Enforce });+ Assert.True(step.IsSuccess, string.Join(" | ", step.Diagnostics.Select(x => x.Message)));+ Assert.DoesNotContain("B_SPLINE", step.Value, StringComparison.OrdinalIgnoreCase);+ var reimported = Step242Importer.ImportBody(step.Value);+ Assert.True(reimported.IsSuccess, string.Join(" | ", reimported.Diagnostics.Select(x => x.Message)));+ var reimportedMass = BrepMassProperties.Evaluate(reimported.Value);+ Assert.True(reimportedMass.IsEnclosed, string.Join(" | ", reimportedMass.Diagnostics));+ Assert.InRange(Math.Abs(reimportedMass.AbsoluteVolume - stack.AnalyticVolume), 0d, 0.01d);+ }++ [Theory]+ [InlineData("additive", 6400d, 480d, 0)]+ [InlineData("removal", 5520d, 304d, 1)]+ public void ProperOverlaps_NormalizeToOneExactSectionStack(string kind, double expectedVolume, double expectedTopArea, int expectedHoles)+ {+ var parsed = PrismaticProfileCompositionParser.Parse(OverlapSource(kind));+ Assert.Empty(parsed.Diagnostics);+ var stack = Assert.IsType<PrismaticSectionStackConstruction>(PrismaticSectionStackCompiler.Normalize(parsed, out var diagnostics));+ Assert.Empty(diagnostics);+ var top = Assert.Single(stack.Slabs.Where(x => x.From == 10d && x.To == 15d));+ Assert.Equal(expectedTopArea, PrismaticSectionStackCompiler.Area(top.Region), 6);+ Assert.Equal(expectedHoles, top.Region.Holes.Count);+ Assert.NotNull(top.Arrangement);+ Assert.True(top.Arrangement!.IntersectionVertices.Count > 0);+ Assert.True(top.Arrangement.RetainedBoundaryFragmentCount < top.Arrangement.AtomicFragments.Count || top.Arrangement.CoincidentFragmentCount > 0);+ Assert.Equal(expectedVolume, stack.AnalyticVolume, 6);++ var emitted = PrismaticSectionStackEmitter.Emit(stack);+ var body = Assert.IsType<Aetheris.Kernel.Core.Brep.BrepBody>(emitted.Body);+ Assert.Equal(expectedVolume, BrepMassProperties.Evaluate(body).AbsoluteVolume, 6);+ var step = Step242Exporter.ExportBody(body, new Step242ExportOptions { BrepExportPreflightMode = BrepExportPreflightMode.Enforce });+ Assert.True(step.IsSuccess, string.Join(" | ", step.Diagnostics.Select(x => x.Message)));+ var reimported = Step242Importer.ImportBody(step.Value);+ Assert.True(reimported.IsSuccess, string.Join(" | ", reimported.Diagnostics.Select(x => x.Message)));+ Assert.Equal(expectedVolume, BrepMassProperties.Evaluate(reimported.Value).AbsoluteVolume, 6);+ }++ [Theory]+ [InlineData("shallow-pocket", 3808d)]+ [InlineData("through-cut", 3640d)]+ public void NestedRect2Composition_PreservesAnalyticVolumeAcrossStepRoundTrip(string kind, double expectedVolume)+ {+ var parsed = PrismaticProfileCompositionParser.Parse(Source(kind));+ Assert.Empty(parsed.Diagnostics);++ var stack = Assert.IsType<PrismaticSectionStackConstruction>(PrismaticSectionStackCompiler.Normalize(parsed, out var normalizeDiagnostics));+ Assert.Empty(normalizeDiagnostics);+ Assert.Equal(expectedVolume, stack.AnalyticVolume, 6);++ var emitted = PrismaticSectionStackEmitter.Emit(stack);+ Assert.DoesNotContain(emitted.Diagnostics, d => d.StartsWith("compose-rejected", StringComparison.Ordinal));+ var body = Assert.IsType<Aetheris.Kernel.Core.Brep.BrepBody>(emitted.Body);+ var inMemory = BrepMassProperties.Evaluate(body);+ Assert.True(inMemory.IsEnclosed, string.Join(" | ", inMemory.Diagnostics));+ Assert.Equal(expectedVolume, inMemory.AbsoluteVolume, 6);++ var step = Step242Exporter.ExportBody(body, new Step242ExportOptions { BrepExportPreflightMode = BrepExportPreflightMode.Enforce });+ Assert.True(step.IsSuccess, string.Join(" | ", step.Diagnostics.Select(d => d.Message)));+ var imported = Step242Importer.ImportBody(step.Value);+ Assert.True(imported.IsSuccess, string.Join(" | ", imported.Diagnostics.Select(d => d.Message)));+ var reimported = BrepMassProperties.Evaluate(imported.Value);+ Assert.True(reimported.IsEnclosed, string.Join(" | ", reimported.Diagnostics));+ Assert.Equal(expectedVolume, reimported.AbsoluteVolume, 6);+ }++ private static string Source(string kind) => $$"""+ Concept Struct Layout On XY {+ Rect2 Base { Center: [0mm, 0mm]; Size: [20mm, 20mm]; Role: ProfileGuide }+ Rect2 Inner { Center: [0mm, 0mm]; Size: [{{(kind == "shallow-pocket" ? 8 : 6)}}mm, {{(kind == "shallow-pocket" ? 8 : 6)}}mm]; Role: ProfileGuide }+ }+ Profile Plate Using Layout { Loop Outer {+ Segment South { Trace: Base.Bottom; From: Base.BottomLeft; To: Base.BottomRight }+ Segment East { Trace: Base.Right; From: Base.BottomRight; To: Base.TopRight }+ Segment North { Trace: Base.Top; From: Base.TopRight; To: Base.TopLeft }+ Segment West { Trace: Base.Left; From: Base.TopLeft; To: Base.BottomLeft }+ } }+ Profile Void Using Layout { Loop Outer {+ Segment South { Trace: Inner.Bottom; From: Inner.BottomLeft; To: Inner.BottomRight }+ Segment East { Trace: Inner.Right; From: Inner.BottomRight; To: Inner.TopRight }+ Segment North { Trace: Inner.Top; From: Inner.TopRight; To: Inner.TopLeft }+ Segment West { Trace: Inner.Left; From: Inner.TopLeft; To: Inner.BottomLeft }+ } }+ Struct Composition { Compose Body {+ Base Stock { Profile: Plate; From: 0mm; To: 10mm; Role: Stock }+ Remove Cut { Profile: Void; From: {{(kind == "shallow-pocket" ? 7 : 0)}}mm; To: 10mm; Role: Relief }+ } }+ """;++ private static string OverlapSource(string kind) => $$"""+ Concept Struct Layout On XY {+ Rect2 BaseGuide { Center: [0mm, 0mm]; Size: [20mm, 20mm]; Role: ProfileGuide }+ Rect2 LeftGuide { Center: [-3mm, 10mm]; Size: [10mm, 10mm]; Role: ProfileGuide }+ Rect2 RightGuide { Center: [3mm, 10mm]; Size: [10mm, 10mm]; Role: ProfileGuide }+ Rect2 VoidLeftGuide { Center: [-2mm, 0mm]; Size: [8mm, 8mm]; Role: ProfileGuide }+ Rect2 VoidRightGuide { Center: [2mm, 0mm]; Size: [8mm, 8mm]; Role: ProfileGuide }+ }+ {{RectProfile("BaseProfile", "BaseGuide")}}+ {{RectProfile("LeftProfile", kind == "additive" ? "LeftGuide" : "VoidLeftGuide")}}+ {{RectProfile("RightProfile", kind == "additive" ? "RightGuide" : "VoidRightGuide")}}+ Struct Composition { Compose Body {+ Base Stock { Profile: BaseProfile; From: 0mm; To: 15mm; Role: Stock }+ {{(kind == "additive" ? "Add Left { Profile: LeftProfile; From: 10mm; To: 15mm; Role: Pad }\n Add Right { Profile: RightProfile; From: 10mm; To: 15mm; Role: Pad }" : "Remove Left { Profile: LeftProfile; From: 10mm; To: 15mm; Role: Relief }\n Remove Right { Profile: RightProfile; From: 10mm; To: 15mm; Role: Relief }")}}+ } }+ """;++ private static string RectProfile(string profile, string guide) => $$"""+ Profile {{profile}} Using Layout { Loop Outer {+ Segment South { Trace: {{guide}}.Bottom; From: {{guide}}.BottomLeft; To: {{guide}}.BottomRight }+ Segment East { Trace: {{guide}}.Right; From: {{guide}}.BottomRight; To: {{guide}}.TopRight }+ Segment North { Trace: {{guide}}.Top; From: {{guide}}.TopRight; To: {{guide}}.TopLeft }+ Segment West { Trace: {{guide}}.Left; From: {{guide}}.TopLeft; To: {{guide}}.BottomLeft }+ } }+ """;+}diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex 59a73af1..771a5a3c 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -49,6 +49,19 @@ public static class FirmamentBuildAndExportprivate static KernelResult<FirmamentStepExportResult> ExportSource(string sourceText, string? sourceDirectory = null){+ if (PrismaticProfileCompositionParser.IsCompositionSource(sourceText))+ {+ var parsed = PrismaticProfileCompositionParser.Parse(sourceText);+ var stack = PrismaticSectionStackCompiler.Normalize(parsed, out var diagnostics);+ if (stack is null)+ return KernelResult<FirmamentStepExportResult>.Failure(diagnostics.Select(x => new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, x, "FirmamentV2.ProfileComposition")).ToArray());+ var emitted = PrismaticSectionStackEmitter.Emit(stack);+ if (emitted.Body is null)+ return KernelResult<FirmamentStepExportResult>.Failure(emitted.Diagnostics.Select(x => new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, x, "FirmamentV2.ProfileComposition")).ToArray());+ var step = Step242Exporter.ExportBody(emitted.Body);+ if (!step.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);+ return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, stack.Feature.Name, 0, "prismatic-section-stack", "line-arc-profile-composition"));+ }if (ProfileAuthoringParser.IsProfileSource(sourceText)){var parsed = ProfileAuthoringParser.Parse(sourceText);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.csindex 883c2006..c998b002 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs@@ -10,8 +10,9 @@ public static class ProfileAuthoringParserprivate static readonly Regex Point = new(@"\bPoint2\s+(?<n>\w+)\s*\{\s*Position\s*:\s*\[(?<x>[-+.\d]+)mm\s*,\s*(?<y>[-+.\d]+)mm\]", RegexOptions.Singleline);private static readonly Regex Line = new(@"\bLine2\s+(?<n>\w+)\s*\{\s*From\s*:\s*(?<a>\w+)\s*;?\s*To\s*:\s*(?<b>\w+)", RegexOptions.Singleline);private static readonly Regex Circle = new(@"\bCircle2\s+(?<n>\w+)\s*\{\s*Center\s*:\s*(?<c>\w+)\s*;?\s*Radius\s*:\s*(?<r>[-+.\d]+)mm", RegexOptions.Singleline);+ private static readonly Regex Rect = new(@"\bRect2\s+(?<n>\w+)\s*\{\s*Center\s*:\s*\[(?<x>[-+.\d]+)mm\s*,\s*(?<y>[-+.\d]+)mm\]\s*;?\s*Size\s*:\s*\[(?<w>[-+.\d]+)mm\s*,\s*(?<h>[-+.\d]+)mm\]", RegexOptions.Singleline);private static readonly Regex Header = new(@"\bProfile\s+(?<n>\w+)\s+Using\s+(?<layout>\w+)\s*\{(?<body>[\s\S]*)", RegexOptions.CultureInvariant);- private static readonly Regex Segment = new(@"\bSegment\s+(?<n>\w+)\s*\{\s*Trace\s*:\s*(?<trace>\w+)\s*;?\s*From\s*:\s*(?<from>\w+)\s*;?\s*To\s*:\s*(?<to>\w+)(?:\s*;?\s*Sweep\s*:\s*(?<sweep>Clockwise|CounterClockwise))?", RegexOptions.Singleline);+ private static readonly Regex Segment = new(@"\bSegment\s+(?<n>\w+)\s*\{\s*Trace\s*:\s*(?<trace>[\w.]+)\s*;?\s*From\s*:\s*(?<from>[\w.]+)\s*;?\s*To\s*:\s*(?<to>[\w.]+)(?:\s*;?\s*Sweep\s*:\s*(?<sweep>Clockwise|CounterClockwise))?", RegexOptions.Singleline);private static readonly Regex Extrude = new(@"\bExtrude\s+\w+\s*\{\s*Profile\s*:\s*(?<p>\w+)\s*;?\s*From\s*:\s*(?<a>[-+.\d]+)mm\s*;?\s*To\s*:\s*(?<b>[-+.\d]+)mm", RegexOptions.Singleline);public static bool IsProfileSource(string source) => Header.IsMatch(source);@@ -20,8 +21,20 @@ public static class ProfileAuthoringParservar d=new List<string>(); var h=Header.Match(source); if(!h.Success)return(null,0,["profile-source-missing-profile"]);var pts=new Dictionary<string,(double X,double Y)>(StringComparer.Ordinal);foreach(Match m in Point.Matches(source))pts[m.Groups["n"].Value]=(N(m,"x"),N(m,"y"));+ foreach (Match m in Rect.Matches(source))+ {+ var w=N(m,"w"); var rectHeight=N(m,"h"); var x=N(m,"x"); var y=N(m,"y"); var n=m.Groups["n"].Value;+ if (!double.IsFinite(w) || !double.IsFinite(rectHeight) || w<=0 || rectHeight<=0) { d.Add($"rect2-invalid-size:{n}"); continue; }+ pts[$"{n}.BottomLeft"]=(x-w/2,y-rectHeight/2); pts[$"{n}.BottomRight"]=(x+w/2,y-rectHeight/2); pts[$"{n}.TopRight"]=(x+w/2,y+rectHeight/2); pts[$"{n}.TopLeft"]=(x-w/2,y+rectHeight/2);+ }var lines=new Dictionary<string,LineArcLineSegment2D>(StringComparer.Ordinal);foreach(Match m in Line.Matches(source)){if(!pts.TryGetValue(m.Groups["a"].Value,out var a)||!pts.TryGetValue(m.Groups["b"].Value,out var b))d.Add($"profile-layout-unresolved-line:{m.Groups["n"].Value}");else lines[m.Groups["n"].Value]=new(a,b);}+ foreach (Match m in Rect.Matches(source))+ {+ var n=m.Groups["n"].Value;+ if (pts.TryGetValue($"{n}.BottomLeft",out var bl) && pts.TryGetValue($"{n}.BottomRight",out var br) && pts.TryGetValue($"{n}.TopRight",out var tr) && pts.TryGetValue($"{n}.TopLeft",out var tl))+ { lines[$"{n}.Bottom"]=new(bl,br); lines[$"{n}.Right"]=new(br,tr); lines[$"{n}.Top"]=new(tr,tl); lines[$"{n}.Left"]=new(tl,bl); }+ }var circles=new Dictionary<string,((double X,double Y) C,double R)>(StringComparer.Ordinal);foreach(Match m in Circle.Matches(source)){if(!pts.TryGetValue(m.Groups["c"].Value,out var c))d.Add($"profile-layout-unresolved-circle:{m.Groups["n"].Value}");else circles[m.Groups["n"].Value]=(c,N(m,"r"));}var segments=new List<ResolvedProfileSegment2D>();diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.csnew file mode 100644index 00000000..13b6af0c--- /dev/null+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs@@ -0,0 +1,139 @@+using System.Globalization;+using System.Text.RegularExpressions;++namespace Aetheris.Kernel.Firmament.Materializer;++/// <summary>+/// Source-owned intent for a single material body whose cross section changes only+/// at declared axial levels. This is deliberately not a list of Boolean solids.+/// </summary>+public enum PrismaticProfileIntent { Base, Add, Remove }+public sealed record PrismaticProfileOperation(+ string Name, PrismaticProfileIntent Intent, string ProfileReference, double From, double To,+ string SemanticRole, string SourceSpan);+public sealed record PrismaticProfileCompositionFeature(+ string Name, string Frame, string Axis, IReadOnlyList<PrismaticProfileOperation> Operations,+ IReadOnlyList<double> CriticalLevels, string Provenance);+public sealed record PrismaticSectionRegion(+ ResolvedProfile2D Outer, IReadOnlyList<ResolvedProfile2D> Holes, IReadOnlyList<string> Provenance);+public sealed record PrismaticSectionSlab(+ double From, double To, PrismaticSectionRegion Region, IReadOnlyList<string> ActiveOperations,+ ProfileArrangement2D? Arrangement = null);+public sealed record PrismaticSectionTransition(double Level, PrismaticSectionRegion? UpwardRegion, PrismaticSectionRegion? DownwardRegion);+public sealed record PrismaticSectionStackConstruction(+ PrismaticProfileCompositionFeature Feature, IReadOnlyList<PrismaticSectionSlab> Slabs,+ IReadOnlyList<PrismaticSectionTransition> Transitions, double AnalyticVolume, IReadOnlyList<string> Diagnostics);+public sealed record PrismaticProfileCompositionParseResult(+ PrismaticProfileCompositionFeature? Feature, IReadOnlyDictionary<string, ResolvedProfile2D> Profiles, IReadOnlyList<string> Diagnostics);++/// <summary>+/// Bounded parser for the composition source form. It intentionally reuses the+/// same Point2/Line2/Circle2/Profile vocabulary as the first profile route.+/// </summary>+public static class PrismaticProfileCompositionParser+{+ private static readonly Regex Point = new(@"\bPoint2\s+(?<n>\w+)\s*\{\s*Position\s*:\s*\[(?<x>[-+.\d]+)mm\s*,\s*(?<y>[-+.\d]+)mm\]", RegexOptions.Singleline | RegexOptions.CultureInvariant);+ private static readonly Regex Line = new(@"\bLine2\s+(?<n>\w+)\s*\{\s*From\s*:\s*(?<a>\w+)\s*;?\s*To\s*:\s*(?<b>\w+)", RegexOptions.Singleline | RegexOptions.CultureInvariant);+ private static readonly Regex Circle = new(@"\bCircle2\s+(?<n>\w+)\s*\{\s*Center\s*:\s*(?<c>\w+)\s*;?\s*Radius\s*:\s*(?<r>[-+.\d]+)mm", RegexOptions.Singleline | RegexOptions.CultureInvariant);+ private static readonly Regex Rect = new(@"\bRect2\s+(?<n>\w+)\s*\{\s*Center\s*:\s*\[(?<x>[-+.\d]+)mm\s*,\s*(?<y>[-+.\d]+)mm\]\s*;?\s*Size\s*:\s*\[(?<w>[-+.\d]+)mm\s*,\s*(?<h>[-+.\d]+)mm\]", RegexOptions.Singleline | RegexOptions.CultureInvariant);+ private static readonly Regex ProfileHead = new(@"\bProfile\s+(?<n>\w+)\s+Using\s+(?<layout>\w+)\s*\{", RegexOptions.CultureInvariant);+ private static readonly Regex Segment = new(@"\bSegment\s+(?<n>\w+)\s*\{\s*Trace\s*:\s*(?<trace>[\w.]+)\s*;?\s*From\s*:\s*(?<from>[\w.]+)\s*;?\s*To\s*:\s*(?<to>[\w.]+)(?:\s*;?\s*Sweep\s*:\s*(?<sweep>Clockwise|CounterClockwise))?", RegexOptions.Singleline | RegexOptions.CultureInvariant);+ private static readonly Regex ComposeHead = new(@"\bCompose\s+(?<n>\w+)\s*\{", RegexOptions.CultureInvariant);+ private static readonly Regex Operation = new(@"\b(?<intent>Base|Add|Remove)\s+(?<n>\w+)\s*\{\s*Profile\s*:\s*(?<profile>\w+)\s*;?\s*From\s*:\s*(?<from>[-+.\d]+)mm\s*;?\s*To\s*:\s*(?<to>[-+.\d]+)mm(?:\s*;?\s*Role\s*:\s*(?<role>\w+))?", RegexOptions.Singleline | RegexOptions.CultureInvariant);++ public static bool IsCompositionSource(string source) => ComposeHead.IsMatch(source);++ public static PrismaticProfileCompositionParseResult Parse(string source)+ {+ var diagnostics = new List<string>();+ var points = Point.Matches(source).ToDictionary(m => m.Groups["n"].Value, m => (X: N(m, "x"), Y: N(m, "y")), StringComparer.Ordinal);+ foreach (Match match in Rect.Matches(source))+ {+ var width=N(match,"w"); var height=N(match,"h"); var x=N(match,"x"); var y=N(match,"y"); var name=match.Groups["n"].Value;+ if (!double.IsFinite(width) || !double.IsFinite(height) || width<=0 || height<=0) { diagnostics.Add($"rect2-invalid-size:{name}"); continue; }+ points[$"{name}.BottomLeft"]=(x-width/2,y-height/2); points[$"{name}.BottomRight"]=(x+width/2,y-height/2); points[$"{name}.TopRight"]=(x+width/2,y+height/2); points[$"{name}.TopLeft"]=(x-width/2,y+height/2);+ }+ var lines = new Dictionary<string, LineArcLineSegment2D>(StringComparer.Ordinal);+ foreach (Match match in Line.Matches(source))+ {+ if (!points.TryGetValue(match.Groups["a"].Value, out var a) || !points.TryGetValue(match.Groups["b"].Value, out var b))+ diagnostics.Add($"compose-layout-unresolved-line:{match.Groups["n"].Value}");+ else lines[match.Groups["n"].Value] = new(a, b);+ }+ foreach (Match match in Rect.Matches(source))+ {+ var n=match.Groups["n"].Value;+ if (points.TryGetValue($"{n}.BottomLeft",out var bl) && points.TryGetValue($"{n}.BottomRight",out var br) && points.TryGetValue($"{n}.TopRight",out var tr) && points.TryGetValue($"{n}.TopLeft",out var tl))+ { lines[$"{n}.Bottom"]=new(bl,br); lines[$"{n}.Right"]=new(br,tr); lines[$"{n}.Top"]=new(tr,tl); lines[$"{n}.Left"]=new(tl,bl); }+ }+ var circles = new Dictionary<string, ((double X, double Y) Center, double Radius)>(StringComparer.Ordinal);+ foreach (Match match in Circle.Matches(source))+ {+ if (!points.TryGetValue(match.Groups["c"].Value, out var center)) diagnostics.Add($"compose-layout-unresolved-circle:{match.Groups["n"].Value}");+ else circles[match.Groups["n"].Value] = (center, N(match, "r"));+ }++ var profiles = new Dictionary<string, ResolvedProfile2D>(StringComparer.Ordinal);+ foreach (Match header in ProfileHead.Matches(source))+ {+ var body = Block(source, header.Index + header.Length - 1);+ if (body is null) { diagnostics.Add($"compose-profile-unclosed:{header.Groups["n"].Value}"); continue; }+ var segments = new List<ResolvedProfileSegment2D>();+ foreach (Match match in Segment.Matches(body))+ {+ var name = match.Groups["n"].Value;+ if (!points.TryGetValue(match.Groups["from"].Value, out var from) || !points.TryGetValue(match.Groups["to"].Value, out var to)) { diagnostics.Add($"compose-profile-segment-unresolved:{name}"); continue; }+ LineArcProfileCurve2D? geometry = null;+ var trace = match.Groups["trace"].Value;+ if (lines.ContainsKey(trace)) geometry = new LineArcLineSegment2D(from, to);+ else if (circles.TryGetValue(trace, out var circle) && match.Groups["sweep"].Success)+ {+ var start = Math.Atan2(from.Y - circle.Center.Y, from.X - circle.Center.X);+ var sweep = Math.Atan2(to.Y - circle.Center.Y, to.X - circle.Center.X) - start;+ if (match.Groups["sweep"].Value == "CounterClockwise") while (sweep <= 0) sweep += 2 * Math.PI;+ else while (sweep >= 0) sweep -= 2 * Math.PI;+ geometry = new LineArcCircularArc2D(circle.Center, circle.Radius, start, sweep);+ }+ else diagnostics.Add($"compose-profile-guide-missing-or-arc-sweep:{header.Groups["n"].Value}.{name}");+ if (geometry is not null) segments.Add(new(name, geometry, new($"profile:{header.Groups["n"].Value}.Outer.{name}", $"concept:{header.Groups["layout"].Value}.{trace}", name, $"Trace({trace})", "XY")));+ }+ var profile = new ResolvedProfile2D(header.Groups["n"].Value, "XY", [new ResolvedProfileLoop2D("Outer", true, segments)]);+ var validation = ResolvedProfile2DValidator.Validate(profile);+ diagnostics.AddRange(validation.Diagnostics);+ if (validation.IsValid) profiles.Add(profile.Name, profile);+ }++ var compose = ComposeHead.Match(source);+ if (!compose.Success) return new(null, profiles, diagnostics.Append("compose-source-missing-compose").ToArray());+ var composeBody = Block(source, compose.Index + compose.Length - 1);+ if (composeBody is null) return new(null, profiles, diagnostics.Append("compose-source-unclosed-compose").ToArray());+ var operations = new List<PrismaticProfileOperation>();+ var names = new HashSet<string>(StringComparer.Ordinal);+ foreach (Match match in Operation.Matches(composeBody))+ {+ var name = match.Groups["n"].Value;+ var profile = match.Groups["profile"].Value;+ var from = N(match, "from"); var to = N(match, "to");+ if (!names.Add(name)) diagnostics.Add($"compose-duplicate-operation:{name}");+ if (!profiles.ContainsKey(profile)) diagnostics.Add($"compose-operation-unresolved-profile:{name}:{profile}");+ if (!double.IsFinite(from) || !double.IsFinite(to) || from >= to) diagnostics.Add($"compose-invalid-interval:{name}:{from:R}:{to:R}");+ operations.Add(new(name, Enum.Parse<PrismaticProfileIntent>(match.Groups["intent"].Value), profile, from, to, match.Groups["role"].Success ? match.Groups["role"].Value : match.Groups["intent"].Value, $"offset:{match.Index}"));+ }+ if (operations.Count(o => o.Intent == PrismaticProfileIntent.Base) != 1) diagnostics.Add("compose-requires-exactly-one-base-operation");+ var levels = operations.SelectMany(o => new[] { o.From, o.To }).Distinct().Order().ToArray();+ var feature = diagnostics.Count == 0 ? new PrismaticProfileCompositionFeature(compose.Groups["n"].Value, "XY", "+Z", operations, levels, "parser-backed-scaffold-profile-composition") : null;+ return new(feature, profiles, diagnostics.Distinct().ToArray());+ }++ private static double N(Match match, string name) => double.Parse(match.Groups[name].Value, CultureInfo.InvariantCulture);+ private static string? Block(string text, int open)+ {+ var depth = 0;+ for (var i = open; i < text.Length; i++)+ {+ if (text[i] == '{') depth++;+ else if (text[i] == '}' && --depth == 0) return text[(open + 1)..i];+ }+ return null;+ }+}diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.csnew file mode 100644index 00000000..fcd96c23--- /dev/null+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs@@ -0,0 +1,188 @@+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.Firmament.Materializer;++public sealed record PrismaticSectionStackBrepPlan(string Signature, int Vertices, int Edges, int Faces, string Policy, bool Authoritative);+public sealed record PrismaticSectionStackEmissionResult(BrepBody? Body, PrismaticSectionStackBrepPlan? Plan, IReadOnlyList<string> Diagnostics);++/// <summary>Normalizes bounded line/arc Profiles through a planar material arrangement into slabs.</summary>+public static class PrismaticSectionStackCompiler+{+ private const double Tol = 1e-7;++ public static PrismaticSectionStackConstruction? Normalize(PrismaticProfileCompositionParseResult parsed, out IReadOnlyList<string> diagnostics)+ {+ var d = parsed.Diagnostics.ToList();+ if (parsed.Feature is null) { diagnostics = d; return null; }+ var slabs = new List<PrismaticSectionSlab>();+ foreach (var pair in parsed.Feature.CriticalLevels.Zip(parsed.Feature.CriticalLevels.Skip(1)))+ {+ var mid = (pair.First + pair.Second) / 2d;+ var active = parsed.Feature.Operations.Where(o => o.From < mid && mid < o.To).ToArray();+ if (active.Length == 0) continue;+ var arrangement = ProfileArrangementBuilder.Compose(parsed.Feature.Frame, active, parsed.Profiles, $"slab=({pair.First:R},{pair.Second:R})");+ d.AddRange(arrangement.Arrangement.Diagnostics);+ if (arrangement.Region is not null) slabs.Add(new(pair.First, pair.Second, arrangement.Region, active.Select(x => x.Name).Order().ToArray(), arrangement.Arrangement));+ }+ if (slabs.Count == 0) d.Add("compose-no-material-slabs");+ var transitions = new List<PrismaticSectionTransition>();+ foreach (var level in parsed.Feature.CriticalLevels)+ {+ var below = slabs.SingleOrDefault(s => Math.Abs(s.To - level) < Tol)?.Region;+ var above = slabs.SingleOrDefault(s => Math.Abs(s.From - level) < Tol)?.Region;+ var upwardResult = ProfileArrangementBuilder.Difference(parsed.Feature.Frame, below, above, $"transition={level:R}:below-minus-above");+ var downwardResult = ProfileArrangementBuilder.Difference(parsed.Feature.Frame, above, below, $"transition={level:R}:above-minus-below");+ d.AddRange(upwardResult.Arrangement.Diagnostics);+ d.AddRange(downwardResult.Arrangement.Diagnostics);+ var upward = upwardResult.Region;+ var downward = downwardResult.Region;+ if (upward is not null || downward is not null) transitions.Add(new(level, upward, downward));+ }+ var volume = slabs.Sum(s => Area(s.Region) * (s.To - s.From));+ diagnostics = d.Distinct().ToArray();+ return d.Any(x => x.Contains("rejected", StringComparison.Ordinal))+ ? null+ : new(parsed.Feature, slabs, transitions, volume, diagnostics);+ }++ public static double Area(PrismaticSectionRegion region) => Math.Abs(ProfileArea(region.Outer)) - region.Holes.Sum(x => Math.Abs(ProfileArea(x)));+ /// <summary>Signed source-loop area in the owning profile frame, retained for inspection evidence.</summary>+ public static double ProfileArea(ResolvedProfile2D profile)+ {+ var sum = 0d;+ foreach (var curve in profile.Loops[0].Segments.Select(s => s.Geometry))+ sum += curve switch+ {+ LineArcLineSegment2D line => line.Start.X * line.End.Y - line.End.X * line.Start.Y,+ LineArcCircularArc2D arc => ArcArea(arc),+ _ => 0d+ };+ return sum / 2d;+ }+ private static double ArcArea(LineArcCircularArc2D arc)+ {+ var a = arc.StartAngleRadians; var b = a + arc.SweepAngleRadians; var r = arc.Radius; var (x, y) = arc.Center;+ return x * r * (Math.Sin(b) - Math.Sin(a)) - y * r * (Math.Cos(b) - Math.Cos(a)) + r * r * (b - a);+ }+}++/// <summary>One topology plan and one body for the normalized stack. Slab partitions are preserved for stable semantic selection.</summary>+public static class PrismaticSectionStackEmitter+{+ private const double Tol = 1e-6;+ public static PrismaticSectionStackEmissionResult Emit(PrismaticSectionStackConstruction stack)+ {+ var d = stack.Diagnostics.ToList();+ var builder = new TopologyBuilder(); var points = new Dictionary<VertexId, Point3D>(); var curves = new Dictionary<EdgeId, CurveGeometry>(); var profileCurves = new Dictionary<EdgeId, LineArcProfileCurve2D>();+ var vertices = new Dictionary<(long X, long Y, long Z), VertexId>(); var edges = new Dictionary<string, EdgeId>();+ var sideFaces = new List<(LoopId Loop, SurfaceGeometry Surface)>(); var capFaces = new List<(FaceId Face, double Z, bool Up)>();+ var splitPoints = stack.Slabs.SelectMany(s => Loops(s.Region)).Concat(stack.Transitions.SelectMany(t =>+ new[] { t.UpwardRegion, t.DownwardRegion }.Where(r => r is not null).SelectMany(r => Loops(r!))))+ .SelectMany(x => x.Profile.Loops[0].Segments).SelectMany(x => Ends(x.Geometry)).DistinctBy(p => $"{Math.Round(p.X / Tol):F0},{Math.Round(p.Y / Tol):F0}").ToArray();+ (long X, long Y, long Z) Key((double X, double Y) p, double z) => ((long)Math.Round(p.X / Tol), (long)Math.Round(p.Y / Tol), (long)Math.Round(z / Tol));+ VertexId Vertex((double X, double Y) p, double z) { var key = Key(p, z); if (vertices.TryGetValue(key, out var id)) return id; id = builder.AddVertex(); vertices[key] = id; points[id] = new(p.X, p.Y, z); return id; }+ (EdgeId Edge, bool Reverse) Edge(LineArcProfileCurve2D curve, double z)+ {+ var endpoints = Ends(curve); var a = endpoints[0]; var b = endpoints[1]; var forward = CurveKey(curve, z, a, b); var reverse = CurveKey(curve, z, b, a);+ if (edges.TryGetValue(forward, out var existing)) return (existing, false);+ if (edges.TryGetValue(reverse, out existing)) return (existing, true);+ var created = builder.AddEdge(Vertex(a, z), Vertex(b, z)); edges[forward] = created; curves[created] = Curve(curve, z); profileCurves[created] = curve; return (created, false);+ }+ (EdgeId Edge, bool Reverse) Vertical((double X, double Y) p, double from, double to)+ {+ var key = $"V:{Key(p, from)}:{Key(p, to)}"; var reverse = $"V:{Key(p, to)}:{Key(p, from)}";+ if (edges.TryGetValue(key, out var e)) return (e, false); if (edges.TryGetValue(reverse, out e)) return (e, true);+ var created = builder.AddEdge(Vertex(p, from), Vertex(p, to)); edges[key] = created; curves[created] = CurveGeometry.FromLine(new Line3Curve(points[Vertex(p, from)], Direction3D.Create(points[Vertex(p, to)] - points[Vertex(p, from)]))); return (created, false);+ }+ foreach (var slab in stack.Slabs)+ foreach (var item in Loops(slab.Region))+ foreach (var segment in item.Profile.Loops[0].Segments)+ foreach (var curve in Split(segment.Geometry, splitPoints))+ {+ var endpoints = Ends(curve); var a = endpoints[0]; var b = endpoints[1]; var bottom = Edge(curve, slab.From); var top = Edge(curve, slab.To); var v0 = Vertical(a, slab.From, slab.To); var v1 = Vertical(b, slab.From, slab.To);+ var loop = AddLoop(builder, [new(bottom.Edge, bottom.Reverse), new(v1.Edge, v1.Reverse), new(top.Edge, !top.Reverse), new(v0.Edge, !v0.Reverse)]);+ sideFaces.Add((loop, SideSurface(curve, slab.From, item.IsHole)));+ }+ foreach (var transition in stack.Transitions)+ {+ if (transition.UpwardRegion is not null) capFaces.Add((AddCap(builder, transition.UpwardRegion, transition.Level, Edge, splitPoints), transition.Level, true));+ if (transition.DownwardRegion is not null) capFaces.Add((AddCap(builder, transition.DownwardRegion, transition.Level, Edge, splitPoints), transition.Level, false));+ }+ var faces = new List<FaceId>();+ foreach (var cap in capFaces) faces.Add(cap.Face);+ foreach (var side in sideFaces) faces.Add(builder.AddFace([side.Loop]));+ var shell = builder.AddShell(faces); builder.AddBody([shell]);+ var geometry = new BrepGeometryStore(); var bindings = new BrepBindingModel(); var curveId = 1;+ foreach (var edge in builder.Model.Edges.OrderBy(e => e.Id.Value))+ {+ var curve = curves[edge.Id];+ geometry.AddCurve(new CurveGeometryId(curveId), curve);+ var (trim, oriented) = profileCurves.TryGetValue(edge.Id, out var sourceCurve) ? CurveTrim(sourceCurve) : (new ParameterInterval(0d, (points[edge.EndVertexId] - points[edge.StartVertexId]).Length), true);+ bindings.AddEdgeBinding(new EdgeGeometryBinding(edge.Id, new CurveGeometryId(curveId), trim, OrientedEdgeSense: oriented));+ curveId++;+ }+ var surfaceId = 1;+ foreach (var cap in capFaces) { geometry.AddSurface(new SurfaceGeometryId(surfaceId), SurfaceGeometry.FromPlane(new PlaneSurface(new Point3D(0, 0, cap.Z), Direction3D.Create(new Vector3D(0, 0, cap.Up ? 1 : -1)), Direction3D.Create(new Vector3D(1, 0, 0))))); bindings.AddFaceBinding(new FaceGeometryBinding(cap.Face, new SurfaceGeometryId(surfaceId++))); }+ foreach (var side in sideFaces) { var face = faces[capFaces.Count + sideFaces.IndexOf(side)]; geometry.AddSurface(new SurfaceGeometryId(surfaceId), side.Surface); bindings.AddFaceBinding(new FaceGeometryBinding(face, new SurfaceGeometryId(surfaceId++))); }+ foreach (var incidence in builder.Model.Coedges.GroupBy(x => x.EdgeId).Where(x => x.Count() != 2))+ {+ var edge = builder.Model.Edges.Single(x => x.Id == incidence.Key);+ var a = points[edge.StartVertexId]; var b = points[edge.EndVertexId];+ d.Add($"compose-rejected:non-manifold-edge-use:edge={incidence.Key.Value}:uses={incidence.Count()}:curve={curves[incidence.Key].Kind}:from=({a.X:R},{a.Y:R},{a.Z:R}):to=({b.X:R},{b.Y:R},{b.Z:R})");+ }+ var body = new BrepBody(builder.Model, geometry, bindings, points);+ var plan = new PrismaticSectionStackBrepPlan($"compose:{stack.Feature.Name}:slabs={stack.Slabs.Count}:transitions={stack.Transitions.Count}", points.Count, builder.Model.Edges.Count(), faces.Count, "deterministic-slab-partitions", true);+ d.Add("compose-authoritative-section-stack-brep-plan"); d.Add("compose-no-3d-boolean-used");+ return new(body, plan, d.Distinct().ToArray());+ }+ private static FaceId AddCap(TopologyBuilder builder, PrismaticSectionRegion region, double z, Func<LineArcProfileCurve2D, double, (EdgeId Edge, bool Reverse)> edge, IReadOnlyList<(double X, double Y)> splitPoints)+ {+ var loops = new List<LoopId>();+ foreach (var item in Loops(region))+ {+ var segments = item.IsHole ? item.Profile.Loops[0].Segments.Reverse() : item.Profile.Loops[0].Segments;+ var curves = segments.SelectMany(s => Split(s.Geometry, splitPoints)).ToArray();+ loops.Add(AddLoop(builder, curves.Select(curve => { var e = edge(curve, z); return new Use(e.Edge, item.IsHole ? !e.Reverse : e.Reverse); }).ToArray()));+ }+ return builder.AddFace(loops);+ }+ private static IEnumerable<(ResolvedProfile2D Profile, bool IsHole)> Loops(PrismaticSectionRegion region) { yield return (region.Outer, false); foreach (var h in region.Holes) yield return (h, true); }+ private static (double X, double Y)[] Ends(LineArcProfileCurve2D curve) => curve switch { LineArcLineSegment2D l => [l.Start, l.End], LineArcCircularArc2D a => [(a.Center.X + a.Radius * Math.Cos(a.StartAngleRadians), a.Center.Y + a.Radius * Math.Sin(a.StartAngleRadians)), (a.Center.X + a.Radius * Math.Cos(a.StartAngleRadians + a.SweepAngleRadians), a.Center.Y + a.Radius * Math.Sin(a.StartAngleRadians + a.SweepAngleRadians))], _ => throw new NotSupportedException("X1 composition requires bounded line/arc segments.") };+ private static IEnumerable<LineArcProfileCurve2D> Split(LineArcProfileCurve2D curve, IReadOnlyList<(double X, double Y)> points)+ {+ var parameters = points.Select(p => Parameter(curve, p)).Where(x => x is not null).Select(x => x!.Value).Append(0d).Append(1d).Order().Aggregate(new List<double>(), (list, value) => { if (list.Count == 0 || Math.Abs(list[^1] - value) > Tol) list.Add(value); return list; });+ for (var i = 0; i < parameters.Count - 1; i++) if (parameters[i + 1] - parameters[i] > Tol) yield return Trim(curve, parameters[i], parameters[i + 1]);+ }+ private static double? Parameter(LineArcProfileCurve2D curve, (double X, double Y) p)+ {+ if (curve is LineArcLineSegment2D line) { var dx = line.End.X - line.Start.X; var dy = line.End.Y - line.Start.Y; var length2 = dx * dx + dy * dy; var t = ((p.X - line.Start.X) * dx + (p.Y - line.Start.Y) * dy) / length2; return t >= -Tol && t <= 1d + Tol && Math.Abs((line.Start.X + t * dx - p.X)) <= Tol && Math.Abs((line.Start.Y + t * dy - p.Y)) <= Tol ? Math.Clamp(t, 0d, 1d) : null; }+ if (curve is LineArcCircularArc2D arc) { if (Math.Abs(Math.Sqrt((p.X - arc.Center.X) * (p.X - arc.Center.X) + (p.Y - arc.Center.Y) * (p.Y - arc.Center.Y)) - arc.Radius) > Tol) return null; var delta = Math.Atan2(p.Y - arc.Center.Y, p.X - arc.Center.X) - arc.StartAngleRadians; if (arc.SweepAngleRadians >= 0d) while (delta < 0d) delta += 2d * Math.PI; else while (delta > 0d) delta -= 2d * Math.PI; var t = delta / arc.SweepAngleRadians; return t >= -Tol && t <= 1d + Tol ? Math.Clamp(t, 0d, 1d) : null; }+ return null;+ }+ private static LineArcProfileCurve2D Trim(LineArcProfileCurve2D curve, double from, double to) => curve switch { LineArcLineSegment2D line => new LineArcLineSegment2D((line.Start.X + (line.End.X - line.Start.X) * from, line.Start.Y + (line.End.Y - line.Start.Y) * from), (line.Start.X + (line.End.X - line.Start.X) * to, line.Start.Y + (line.End.Y - line.Start.Y) * to)), LineArcCircularArc2D arc => new LineArcCircularArc2D(arc.Center, arc.Radius, arc.StartAngleRadians + arc.SweepAngleRadians * from, arc.SweepAngleRadians * (to - from)), _ => throw new NotSupportedException() };+ private static LineArcProfileCurve2D Reverse(LineArcProfileCurve2D curve) => curve switch { LineArcLineSegment2D line => new LineArcLineSegment2D(line.End, line.Start), LineArcCircularArc2D arc => new LineArcCircularArc2D(arc.Center, arc.Radius, arc.StartAngleRadians + arc.SweepAngleRadians, -arc.SweepAngleRadians), _ => throw new NotSupportedException() };+ private static string CurveKey(LineArcProfileCurve2D curve, double z, (double X, double Y) a, (double X, double Y) b) => curve switch+ {+ LineArcLineSegment2D => $"L:{P(a)}:{P(b)}:{Q(z)}",+ LineArcCircularArc2D arc => $"A:{P(arc.Center)}:{Q(arc.Radius)}:{P(a)}:{P(b)}:{Q(z)}",+ _ => throw new NotSupportedException()+ };+ private static string P((double X, double Y) point) => $"{Q(point.X)},{Q(point.Y)}";+ private static long Q(double value) => (long)Math.Round(value / Tol);+ private static (ParameterInterval Trim, bool Oriented) CurveTrim(LineArcProfileCurve2D curve) => curve switch+ {+ LineArcLineSegment2D line => (new ParameterInterval(0d, Math.Sqrt((line.End.X - line.Start.X) * (line.End.X - line.Start.X) + (line.End.Y - line.Start.Y) * (line.End.Y - line.Start.Y))), true),+ LineArcCircularArc2D arc when arc.SweepAngleRadians >= 0d => (new ParameterInterval(arc.StartAngleRadians, arc.StartAngleRadians + arc.SweepAngleRadians), true),+ LineArcCircularArc2D arc => (new ParameterInterval(arc.StartAngleRadians + arc.SweepAngleRadians, arc.StartAngleRadians), false),+ _ => throw new NotSupportedException()+ };+ private static CurveGeometry Curve(LineArcProfileCurve2D curve, double z) => curve switch { LineArcLineSegment2D l => CurveGeometry.FromLine(new Line3Curve(new Point3D(l.Start.X, l.Start.Y, z), Direction3D.Create(new Vector3D(l.End.X - l.Start.X, l.End.Y - l.Start.Y, 0)))), LineArcCircularArc2D a => CurveGeometry.FromCircle(new Circle3Curve(new Point3D(a.Center.X, a.Center.Y, z), Direction3D.Create(new Vector3D(0, 0, 1)), a.Radius, Direction3D.Create(new Vector3D(1, 0, 0)))), _ => throw new NotSupportedException() };+ private static SurfaceGeometry SideSurface(LineArcProfileCurve2D curve, double z, bool hole) => curve switch { LineArcLineSegment2D l => SurfaceGeometry.FromPlane(new PlaneSurface(new Point3D(l.Start.X, l.Start.Y, z), Direction3D.Create(new Vector3D(hole ? l.Start.Y - l.End.Y : l.End.Y - l.Start.Y, hole ? l.End.X - l.Start.X : l.Start.X - l.End.X, 0)), Direction3D.Create(new Vector3D(0, 0, 1)))), LineArcCircularArc2D a => SurfaceGeometry.FromCylinder(new CylinderSurface(new Point3D(a.Center.X, a.Center.Y, z), Direction3D.Create(new Vector3D(0, 0, 1)), a.Radius, Direction3D.Create(new Vector3D(1, 0, 0)))), _ => throw new NotSupportedException() };+ private static LoopId AddLoop(TopologyBuilder builder, IReadOnlyList<Use> uses) { var id = builder.AllocateLoopId(); var coedges = uses.Select(_ => builder.AllocateCoedgeId()).ToArray(); for (var i = 0; i < uses.Count; i++) builder.AddCoedge(new Coedge(coedges[i], uses[i].Edge, id, coedges[(i + 1) % coedges.Length], coedges[(i + coedges.Length - 1) % coedges.Length], uses[i].Reverse)); builder.AddLoop(new Loop(id, coedges)); return id; }+ private readonly record struct Use(EdgeId Edge, bool Reverse);+}diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.csnew file mode 100644index 00000000..81a3a1ea--- /dev/null+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs@@ -0,0 +1,356 @@+using System.Diagnostics;++namespace Aetheris.Kernel.Firmament.Materializer;++/// <summary>+/// A bounded analytic arrangement of resolved line and circular-arc profile curves.+/// It is construction IR: source curves retain their profile/operation provenance and+/// result loops contain only boundary fragments that separate material from void.+/// </summary>+public sealed record ArrangementSourceCurve2D(+ string StableId, string Operation, string Profile, string Loop, string Segment,+ LineArcProfileCurve2D Geometry, ProfileSegmentProvenance Provenance);+public sealed record ArrangementVertex2D(string StableId, (double X, double Y) Position);+public sealed record ArrangementFragment2D(+ string StableId, ArrangementSourceCurve2D Source, double FromParameter, double ToParameter,+ LineArcProfileCurve2D Geometry, bool MaterialOnLeft, bool Retained);+public sealed record ArrangementLoop2D(string StableId, bool IsOuter, IReadOnlyList<ArrangementFragment2D> Fragments, double SignedArea, double Perimeter);+public sealed record ProfileArrangement2D(+ string Frame, IReadOnlyList<ArrangementSourceCurve2D> SourceCurves,+ IReadOnlyList<ArrangementVertex2D> IntersectionVertices, IReadOnlyList<ArrangementFragment2D> AtomicFragments,+ IReadOnlyList<ArrangementLoop2D> ResultLoops, int CoincidentFragmentCount,+ IReadOnlyList<string> Diagnostics, TimeSpan IntersectionTime, TimeSpan SplitTime,+ TimeSpan ClassificationTime, TimeSpan ReconstructionTime)+{+ public int RetainedBoundaryFragmentCount => AtomicFragments.Count(x => x.Retained);+}++public sealed record ProfileArrangementResult(ProfileArrangement2D Arrangement, PrismaticSectionRegion? Region);++public static class ProfileArrangementBuilder+{+ private const double Tol = 1e-7;+ private const double SideSample = 1e-5;++ public static ProfileArrangementResult Compose(+ string frame,+ IReadOnlyList<PrismaticProfileOperation> active,+ IReadOnlyDictionary<string, ResolvedProfile2D> profiles,+ string context)+ {+ var sources = active.SelectMany(operation => profiles[operation.ProfileReference].Loops.SelectMany(loop => loop.Segments.Select(segment =>+ new ArrangementSourceCurve2D(+ $"compose:{operation.Name}.{operation.ProfileReference}.{loop.Name}.{segment.Name}", operation.Name,+ operation.ProfileReference, loop.Name, segment.Name, segment.Geometry, segment.Provenance)))).ToArray();+ var positive = active.Where(x => x.Intent is PrismaticProfileIntent.Base or PrismaticProfileIntent.Add)+ .Select(x => profiles[x.ProfileReference]).ToArray();+ var negative = active.Where(x => x.Intent == PrismaticProfileIntent.Remove)+ .Select(x => profiles[x.ProfileReference]).ToArray();+ return Build(frame, sources, p => positive.Any(profile => PointInProfile(profile, p) == ArrangementPointLocation.Inside)+ && !negative.Any(profile => PointInProfile(profile, p) == ArrangementPointLocation.Inside), context);+ }++ /// <summary>Exact region subtraction used only to derive horizontal section transitions.</summary>+ public static ProfileArrangementResult Difference(string frame, PrismaticSectionRegion? left, PrismaticSectionRegion? right, string context)+ {+ if (left is null) return Empty(frame, context);+ var sourceRegions = new[] { (Name: "left", Region: left), (Name: "right", Region: right) }+ .Where(x => x.Region is not null).ToArray();+ var sources = sourceRegions.SelectMany(item => RegionSources(item.Name, item.Region!)).ToArray();+ return Build(frame, sources, p => InRegion(left, p) && !InRegion(right, p), context);+ }++ public static ArrangementPointLocation PointInProfile(ResolvedProfile2D profile, (double X, double Y) point)+ {+ var loop = profile.Loops.SingleOrDefault();+ if (loop is null) return ArrangementPointLocation.Outside;+ return PointInLoop(loop.Segments.Select(x => x.Geometry).ToArray(), point);+ }++ private static ProfileArrangementResult Empty(string frame, string context) =>+ new(new(frame, [], [], [], [], 0, [], TimeSpan.Zero, TimeSpan.Zero, TimeSpan.Zero, TimeSpan.Zero), null);++ private static IEnumerable<ArrangementSourceCurve2D> RegionSources(string name, PrismaticSectionRegion region)+ {+ foreach (var item in new[] { (region.Outer, "Outer") }.Concat(region.Holes.Select(x => (x, "Inner"))))+ foreach (var segment in item.Item1.Loops[0].Segments)+ yield return new ArrangementSourceCurve2D($"transition:{name}.{item.Item2}.{segment.Name}", name, item.Item1.Name, item.Item2,+ segment.Name, segment.Geometry, segment.Provenance);+ }++ private static bool InRegion(PrismaticSectionRegion? region, (double X, double Y) point)+ {+ if (region is null || PointInProfile(region.Outer, point) != ArrangementPointLocation.Inside) return false;+ return !region.Holes.Any(hole => PointInProfile(hole, point) == ArrangementPointLocation.Inside);+ }++ private static ProfileArrangementResult Build(string frame, IReadOnlyList<ArrangementSourceCurve2D> sources, Func<(double X, double Y), bool> material, string context)+ {+ var diagnostics = new List<string>();+ var intersectionClock = Stopwatch.StartNew();+ var parameters = sources.ToDictionary(x => x.StableId, _ => new List<double> { 0d, 1d }, StringComparer.Ordinal);+ var vertices = new List<(double X, double Y)>();+ for (var i = 0; i < sources.Count; i++)+ for (var j = i + 1; j < sources.Count; j++)+ {+ var intersections = Intersections(sources[i].Geometry, sources[j].Geometry, out var coincident);+ if (coincident)+ {+ // Collinear/co-circular support needs endpoint transfer before side+ // classification; otherwise an internal shared interval can leave a+ // mismatched fragment at a transition boundary.+ foreach (var point in new[] { Ends(sources[i].Geometry).Start, Ends(sources[i].Geometry).End })+ if (OnCurve(sources[j].Geometry, point, out var parameter)) { parameters[sources[j].StableId].Add(parameter); vertices.Add(point); }+ foreach (var point in new[] { Ends(sources[j].Geometry).Start, Ends(sources[j].Geometry).End })+ if (OnCurve(sources[i].Geometry, point, out var parameter)) { parameters[sources[i].StableId].Add(parameter); vertices.Add(point); }+ continue;+ }+ foreach (var hit in intersections)+ {+ if (!OnCurve(sources[i].Geometry, hit, out var a) || !OnCurve(sources[j].Geometry, hit, out var b)) continue;+ parameters[sources[i].StableId].Add(a); parameters[sources[j].StableId].Add(b); vertices.Add(hit);+ }+ }+ intersectionClock.Stop();++ var splitClock = Stopwatch.StartNew();+ var fragments = new List<ArrangementFragment2D>();+ foreach (var source in sources.OrderBy(x => x.StableId, StringComparer.Ordinal))+ {+ var ordered = parameters[source.StableId].OrderBy(x => x).Aggregate(new List<double>(), (list, value) =>+ { if (list.Count == 0 || Math.Abs(list[^1] - value) > Tol) list.Add(Math.Clamp(value, 0d, 1d)); return list; });+ for (var i = 0; i < ordered.Count - 1; i++)+ {+ if (ordered[i + 1] - ordered[i] <= Tol) continue;+ var geometry = Trim(source.Geometry, ordered[i], ordered[i + 1]);+ fragments.Add(new ArrangementFragment2D($"{source.StableId}.part{i}", source, ordered[i], ordered[i + 1], geometry, false, false));+ }+ }+ splitClock.Stop();++ var classificationClock = Stopwatch.StartNew();+ var oriented = new List<ArrangementFragment2D>();+ foreach (var fragment in fragments)+ {+ var midpoint = At(fragment.Geometry, .5d); var tangent = Tangent(fragment.Geometry, .5d);+ var length = Math.Sqrt(tangent.X * tangent.X + tangent.Y * tangent.Y);+ if (length <= Tol) { diagnostics.Add($"arrangement-rejected:degenerate-fragment:{fragment.StableId}"); continue; }+ var offset = SideSample;+ var left = (midpoint.X - tangent.Y / length * offset, midpoint.Y + tangent.X / length * offset);+ var right = (midpoint.X + tangent.Y / length * offset, midpoint.Y - tangent.X / length * offset);+ var leftMaterial = material(left); var rightMaterial = material(right);+ if (leftMaterial == rightMaterial) continue;+ var curve = leftMaterial ? fragment.Geometry : Reverse(fragment.Geometry);+ oriented.Add(fragment with { Geometry = curve, MaterialOnLeft = true, Retained = true });+ }+ // Multiple source curves can normalize to the same material-oriented support interval. Keep the lowest semantic id.+ var retained = oriented.GroupBy(x => GeometryKey(x.Geometry), StringComparer.Ordinal).Select(x => x.OrderBy(y => y.StableId, StringComparer.Ordinal).First()).ToArray();+ var coincidentCount = oriented.Count - retained.Length;+ classificationClock.Stop();++ var reconstructionClock = Stopwatch.StartNew();+ var loops = Reconstruct(retained, diagnostics, context);+ reconstructionClock.Stop();+ var allFragments = fragments.Select(fragment => retained.FirstOrDefault(x => x.StableId == fragment.StableId) ?? fragment).ToArray();+ var arrangement = new ProfileArrangement2D(frame, sources, vertices.DistinctBy(VertexKey).OrderBy(VertexKey).Select((p, i) => new ArrangementVertex2D($"vertex:{i}", p)).ToArray(),+ allFragments, loops, coincidentCount, diagnostics.Distinct().ToArray(), intersectionClock.Elapsed, splitClock.Elapsed, classificationClock.Elapsed, reconstructionClock.Elapsed);+ if (diagnostics.Any(x => x.StartsWith("arrangement-rejected", StringComparison.Ordinal))) return new(arrangement, null);+ var region = ToRegion(loops, diagnostics, context);+ return new(arrangement with { Diagnostics = diagnostics.Distinct().ToArray() }, region);+ }++ private static IReadOnlyList<ArrangementLoop2D> Reconstruct(IReadOnlyList<ArrangementFragment2D> fragments, List<string> diagnostics, string context)+ {+ if (fragments.Count == 0) return [];+ var starts = fragments.GroupBy(x => VertexKey(Ends(x.Geometry).Start), StringComparer.Ordinal)+ .ToDictionary(x => x.Key, x => x.OrderBy(y => y.StableId, StringComparer.Ordinal).ToArray(), StringComparer.Ordinal);+ var used = new HashSet<string>(StringComparer.Ordinal); var loops = new List<ArrangementLoop2D>();+ foreach (var seed in fragments.OrderBy(x => x.StableId, StringComparer.Ordinal))+ {+ if (!used.Add(seed.StableId)) continue;+ var current = seed; var chain = new List<ArrangementFragment2D> { seed }; var first = VertexKey(Ends(seed.Geometry).Start);+ for (var guard = 0; guard <= fragments.Count; guard++)+ {+ var at = VertexKey(Ends(current.Geometry).End);+ if (at == first) break;+ if (!starts.TryGetValue(at, out var candidates)) { diagnostics.Add($"arrangement-rejected:dangling-edge:{current.StableId}:context={context}"); break; }+ var next = candidates.Where(x => !used.Contains(x.StableId)).OrderBy(x => Turn(current.Geometry, x.Geometry)).ThenBy(x => x.StableId, StringComparer.Ordinal).FirstOrDefault();+ if (next is null) { diagnostics.Add($"arrangement-rejected:unresolved-angular-order:{current.StableId}:context={context}"); break; }+ used.Add(next.StableId); chain.Add(next); current = next;+ }+ if (VertexKey(Ends(current.Geometry).End) != first) continue;+ var area = chain.Sum(x => SignedAreaContribution(x.Geometry)) / 2d;+ if (Math.Abs(area) <= Tol) { diagnostics.Add($"arrangement-rejected:zero-width-loop:{seed.StableId}:context={context}"); continue; }+ loops.Add(new ArrangementLoop2D($"arrangement-loop:{loops.Count}", area > 0d, chain, area, chain.Sum(x => Length(x.Geometry))));+ }+ if (used.Count != fragments.Count) diagnostics.Add($"arrangement-rejected:unwalked-boundary-fragment:context={context}");+ return loops;+ }++ private static PrismaticSectionRegion? ToRegion(IReadOnlyList<ArrangementLoop2D> loops, List<string> diagnostics, string context)+ {+ if (loops.Count == 0) return null;+ var outers = loops.Where(x => x.IsOuter).OrderByDescending(x => x.SignedArea).ToArray();+ if (outers.Length != 1) { diagnostics.Add($"arrangement-rejected:disconnected-or-invalid-material:outer-loops={outers.Length}:context={context}"); return null; }+ var outer = ToProfile(outers[0], "Outer");+ var holes = loops.Where(x => !x.IsOuter).Select((loop, index) => ToProfile(loop, $"Inner{index}")).ToArray();+ foreach (var hole in holes)+ if (PointInProfile(outer, Ends(hole.Loops[0].Segments[0].Geometry).Start) != ArrangementPointLocation.Inside)+ { diagnostics.Add($"arrangement-rejected:inner-loop-not-nested:context={context}"); return null; }+ return new PrismaticSectionRegion(outer, holes, loops.SelectMany(x => x.Fragments).Select(x => x.Source.StableId).Distinct().OrderBy(x => x, StringComparer.Ordinal).ToArray());+ }++ private static ResolvedProfile2D ToProfile(ArrangementLoop2D loop, string role)+ {+ // The section-stack emitter's explicit inner-loop contract stores source loops CCW+ // and applies the material-facing reversal while lowering FACE_BOUND. Arrangement+ // traversal itself is material-left (thus clockwise for a void), so reverse here.+ var fragments = role == "Outer" ? loop.Fragments : loop.Fragments.Reverse().Select(x => x with { Geometry = Reverse(x.Geometry) }).ToArray();+ return new(+ $"{loop.StableId}.{role}", "XY", [new ResolvedProfileLoop2D(role, role == "Outer", fragments.Select((x, i) =>+ new ResolvedProfileSegment2D($"{x.Source.Segment}.part{i}", x.Geometry,+ x.Source.Provenance with { StableId = $"{x.Source.Provenance.StableId}.arrangement.part{i}", Derivation = $"arrangement:{x.Source.StableId}:{x.FromParameter:R}..{x.ToParameter:R}" })).ToArray())]);+ }++ private static double Turn(LineArcProfileCurve2D incoming, LineArcProfileCurve2D outgoing)+ {+ var a = Tangent(incoming, 1d); var b = Tangent(outgoing, 0d);+ var reverse = Math.Atan2(-a.Y, -a.X); var candidate = Math.Atan2(b.Y, b.X);+ var delta = reverse - candidate; while (delta < 0d) delta += 2d * Math.PI; while (delta >= 2d * Math.PI) delta -= 2d * Math.PI;+ return delta;+ }++ private static IReadOnlyList<(double X, double Y)> Intersections(LineArcProfileCurve2D a, LineArcProfileCurve2D b, out bool coincident)+ {+ coincident = false;+ return (a, b) switch+ {+ (LineArcLineSegment2D x, LineArcLineSegment2D y) => LineLine(x, y, ref coincident),+ (LineArcLineSegment2D x, LineArcCircularArc2D y) => LineCircle(x, y),+ (LineArcCircularArc2D x, LineArcLineSegment2D y) => LineCircle(y, x),+ (LineArcCircularArc2D x, LineArcCircularArc2D y) => CircleCircle(x, y, ref coincident),+ _ => []+ };+ }++ private static IReadOnlyList<(double X, double Y)> LineLine(LineArcLineSegment2D a, LineArcLineSegment2D b, ref bool coincident)+ {+ var r = (X: a.End.X - a.Start.X, Y: a.End.Y - a.Start.Y); var s = (X: b.End.X - b.Start.X, Y: b.End.Y - b.Start.Y);+ var cross = Cross(r, s); var delta = (X: b.Start.X - a.Start.X, Y: b.Start.Y - a.Start.Y);+ if (Math.Abs(cross) <= Tol) { coincident = Math.Abs(Cross(delta, r)) <= Tol; return []; }+ var t = Cross(delta, s) / cross; var u = Cross(delta, r) / cross;+ return t >= -Tol && t <= 1d + Tol && u >= -Tol && u <= 1d + Tol ? [(a.Start.X + t * r.X, a.Start.Y + t * r.Y)] : [];+ }++ private static IReadOnlyList<(double X, double Y)> LineCircle(LineArcLineSegment2D line, LineArcCircularArc2D arc)+ {+ var dx = line.End.X - line.Start.X; var dy = line.End.Y - line.Start.Y; var fx = line.Start.X - arc.Center.X; var fy = line.Start.Y - arc.Center.Y;+ var aa = dx * dx + dy * dy; var bb = 2d * (fx * dx + fy * dy); var cc = fx * fx + fy * fy - arc.Radius * arc.Radius; var discriminant = bb * bb - 4d * aa * cc;+ if (discriminant < -Tol) return []; if (Math.Abs(discriminant) <= Tol) discriminant = 0d;+ var root = Math.Sqrt(discriminant); double[] values = root <= Tol ? [(-bb) / (2d * aa)] : [(-bb - root) / (2d * aa), (-bb + root) / (2d * aa)];+ return values.Where(t => t >= -Tol && t <= 1d + Tol).Select(t => (line.Start.X + dx * t, line.Start.Y + dy * t)).Where(p => OnCurve(arc, p, out _)).ToArray();+ }++ private static IReadOnlyList<(double X, double Y)> CircleCircle(LineArcCircularArc2D a, LineArcCircularArc2D b, ref bool coincident)+ {+ var dx = b.Center.X - a.Center.X; var dy = b.Center.Y - a.Center.Y; var d = Math.Sqrt(dx * dx + dy * dy);+ if (d <= Tol) { coincident = Math.Abs(a.Radius - b.Radius) <= Tol; return []; }+ if (d > a.Radius + b.Radius + Tol || d < Math.Abs(a.Radius - b.Radius) - Tol) return [];+ var x = (a.Radius * a.Radius - b.Radius * b.Radius + d * d) / (2d * d); var h2 = a.Radius * a.Radius - x * x;+ if (h2 < -Tol) return []; var h = Math.Sqrt(Math.Max(0d, h2)); var px = a.Center.X + x * dx / d; var py = a.Center.Y + x * dy / d;+ (double X, double Y)[] candidates = h <= Tol ? [(px, py)] : [(px + -dy * h / d, py + dx * h / d), (px - -dy * h / d, py - dx * h / d)];+ return candidates.Where(p => OnCurve(a, p, out _) && OnCurve(b, p, out _)).ToArray();+ }++ private static bool OnCurve(LineArcProfileCurve2D curve, (double X, double Y) p, out double parameter)+ {+ switch (curve)+ {+ case LineArcLineSegment2D line:+ var dx = line.End.X - line.Start.X; var dy = line.End.Y - line.Start.Y; var length2 = dx * dx + dy * dy;+ parameter = ((p.X - line.Start.X) * dx + (p.Y - line.Start.Y) * dy) / length2;+ var projection = (line.Start.X + parameter * dx, line.Start.Y + parameter * dy);+ return parameter >= -Tol && parameter <= 1d + Tol && Distance(projection, p) <= Tol;+ case LineArcCircularArc2D arc:+ if (Math.Abs(Distance(arc.Center, p) - arc.Radius) > Tol) { parameter = 0; return false; }+ var angle = Math.Atan2(p.Y - arc.Center.Y, p.X - arc.Center.X); parameter = ArcParameter(arc, angle);+ return parameter >= -Tol && parameter <= 1d + Tol;+ default: parameter = 0; return false;+ }+ }++ private static double ArcParameter(LineArcCircularArc2D arc, double angle)+ {+ var delta = angle - arc.StartAngleRadians;+ if (arc.SweepAngleRadians >= 0d) while (delta < 0d) delta += 2d * Math.PI;+ else while (delta > 0d) delta -= 2d * Math.PI;+ return delta / arc.SweepAngleRadians;+ }+ private static LineArcProfileCurve2D Trim(LineArcProfileCurve2D curve, double from, double to) => curve switch+ {+ LineArcLineSegment2D line => new LineArcLineSegment2D(At(line, from), At(line, to)),+ LineArcCircularArc2D arc => new LineArcCircularArc2D(arc.Center, arc.Radius, arc.StartAngleRadians + arc.SweepAngleRadians * from, arc.SweepAngleRadians * (to - from)),+ _ => throw new NotSupportedException("Profile arrangements require bounded line or circular-arc source curves.")+ };+ private static LineArcProfileCurve2D Reverse(LineArcProfileCurve2D curve) => curve switch+ {+ LineArcLineSegment2D line => new LineArcLineSegment2D(line.End, line.Start),+ LineArcCircularArc2D arc => new LineArcCircularArc2D(arc.Center, arc.Radius, arc.StartAngleRadians + arc.SweepAngleRadians, -arc.SweepAngleRadians),+ _ => throw new NotSupportedException()+ };+ private static (double X, double Y) At(LineArcProfileCurve2D curve, double parameter) => curve switch+ {+ LineArcLineSegment2D line => (line.Start.X + (line.End.X - line.Start.X) * parameter, line.Start.Y + (line.End.Y - line.Start.Y) * parameter),+ LineArcCircularArc2D arc => (arc.Center.X + arc.Radius * Math.Cos(arc.StartAngleRadians + arc.SweepAngleRadians * parameter), arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngleRadians + arc.SweepAngleRadians * parameter)),+ _ => throw new NotSupportedException()+ };+ private static (double X, double Y) Tangent(LineArcProfileCurve2D curve, double parameter) => curve switch+ {+ LineArcLineSegment2D line => (line.End.X - line.Start.X, line.End.Y - line.Start.Y),+ LineArcCircularArc2D arc => (-arc.Radius * Math.Sin(arc.StartAngleRadians + arc.SweepAngleRadians * parameter) * Math.Sign(arc.SweepAngleRadians), arc.Radius * Math.Cos(arc.StartAngleRadians + arc.SweepAngleRadians * parameter) * Math.Sign(arc.SweepAngleRadians)),+ _ => throw new NotSupportedException()+ };+ private static ((double X, double Y) Start, (double X, double Y) End) Ends(LineArcProfileCurve2D curve) => (At(curve, 0d), At(curve, 1d));+ private static double SignedAreaContribution(LineArcProfileCurve2D curve) => curve switch+ {+ LineArcLineSegment2D line => line.Start.X * line.End.Y - line.End.X * line.Start.Y,+ LineArcCircularArc2D arc => ArcArea(arc),+ _ => 0d+ };+ private static double ArcArea(LineArcCircularArc2D arc) { var a = arc.StartAngleRadians; var b = a + arc.SweepAngleRadians; return arc.Center.X * arc.Radius * (Math.Sin(b) - Math.Sin(a)) - arc.Center.Y * arc.Radius * (Math.Cos(b) - Math.Cos(a)) + arc.Radius * arc.Radius * (b - a); }+ private static double Length(LineArcProfileCurve2D curve) => curve switch { LineArcLineSegment2D line => Distance(line.Start, line.End), LineArcCircularArc2D arc => Math.Abs(arc.Radius * arc.SweepAngleRadians), _ => 0d };+ private static ArrangementPointLocation PointInLoop(IReadOnlyList<LineArcProfileCurve2D> curves, (double X, double Y) point)+ {+ if (curves.Any(curve => OnCurve(curve, point, out _))) return ArrangementPointLocation.OnBoundary;+ // A horizontal ray to +X; half-open endpoint ownership avoids ray-through-vertex double counting.+ var crossings = 0;+ foreach (var curve in curves)+ {+ if (curve is LineArcLineSegment2D line) crossings += RayLine(point, line);+ else if (curve is LineArcCircularArc2D arc) crossings += RayArc(point, arc);+ }+ return crossings % 2 == 1 ? ArrangementPointLocation.Inside : ArrangementPointLocation.Outside;+ }+ private static int RayLine((double X, double Y) p, LineArcLineSegment2D line)+ { var a = line.Start; var b = line.End; if ((a.Y > p.Y) == (b.Y > p.Y)) return 0; var x = a.X + (p.Y - a.Y) * (b.X - a.X) / (b.Y - a.Y); return x > p.X + Tol ? 1 : 0; }+ private static int RayArc((double X, double Y) p, LineArcCircularArc2D arc)+ {+ var dy = p.Y - arc.Center.Y; if (Math.Abs(dy) >= arc.Radius - Tol) return 0; var dx = Math.Sqrt(Math.Max(0d, arc.Radius * arc.Radius - dy * dy)); var count = 0;+ foreach (var x in new[] { arc.Center.X - dx, arc.Center.X + dx }) if (x > p.X + Tol && OnCurve(arc, (x, p.Y), out var t) && t > Tol && t <= 1d + Tol) count++;+ return count;+ }+ private static string GeometryKey(LineArcProfileCurve2D curve)+ {+ var (a, b) = Ends(curve); return curve switch+ {+ LineArcLineSegment2D => $"L:{VertexKey(a)}:{VertexKey(b)}",+ LineArcCircularArc2D arc => $"A:{VertexKey(arc.Center)}:{arc.Radius:R}:{a.X:R}:{a.Y:R}:{b.X:R}:{b.Y:R}:{Math.Sign(arc.SweepAngleRadians)}",+ _ => throw new NotSupportedException()+ };+ }+ private static string VertexKey((double X, double Y) p) => $"{Math.Round(p.X / Tol):F0},{Math.Round(p.Y / Tol):F0}";+ private static double Cross((double X, double Y) a, (double X, double Y) b) => a.X * b.Y - a.Y * b.X;+ private static double Distance((double X, double Y) a, (double X, double Y) b) => Math.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y));+}++public enum ArrangementPointLocation { Outside, Inside, OnBoundary, AmbiguousWithinTolerance }diff --git a/docs/firmament/profile-arrangement-x1.md b/docs/firmament/profile-arrangement-x1.mdnew file mode 100644index 00000000..88f83f5c--- /dev/null+++ b/docs/firmament/profile-arrangement-x1.md@@ -0,0 +1,21 @@+# Profile arrangement X1++Proper overlap is a planar problem. Aetheris resolves each active Base/Add/Remove slab as one bounded analytic arrangement, then emits the resulting section topology once.++> Compose material regions first. Emit topology once.++`ProfileArrangement2D` preserves source curve identity (`operation`, `Profile`, loop, named segment, parameter interval, and profile provenance). Lines use a normalized endpoint-distance parameter; circular arcs use a normalized traversal over their signed angular sweep. Pairwise analytic line-line, line-circle, and circle-circle intersections are filtered to those bounded domains. Source curves are split in parameter order and receive stable `.partN` identities.++Each atomic fragment is classified by two deterministic normal-offset samples under:++```text+IsMaterial(p) = (InsideBase(p) or InsideAnyAdd(p)) and not InsideAnyRemove(p)+```++Only a fragment whose sides differ is retained; it is oriented material-left. Coincident same-side support collapses to the lowest stable source ID, removing Add/Add and Remove/Remove internal walls without losing provenance. Directed boundary fragments are then walked using the deterministic angular successor around every vertex. A valid production result has exactly one CCW outer loop, zero or more nested inner loops, no dangling fragment, and no zero-area loop. Point-only connections reject as disconnected/non-manifold instead of being healed.++The arrangement result is the existing `PrismaticSectionRegion`. Adjacent regions use the same machinery for exact horizontal differences. The emitter additionally splits section edges at global arrangement vertices so a changed section boundary shares directed edges with the neighboring slab and transition face. It remains one `PrismaticSectionStackBrepPlan` and one analytic BRep/STEP body, with planes, cylinders, lines, circles, and trimmed curves only.++`inspect-compose --json` reports per-slab arrangement curve, intersection, fragment, coincident-normalization, loop, perimeter, timing, diagnostic, and provenance evidence. The included overlapping-additive rectangle fixture reports a 480 mm² upper section and 6400 mm³ total volume after STEP round-trip. The overlapping-removal unit fixture reports a 304 mm² upper material section and 5520 mm³ total volume. `mixed-line-arc-additive-overlap.firmament` forces two transverse line/circle crossings: its upper section is `458.72298071147134 mm²`, with five retained lines and four retained circular arcs. Its analytic volume is `6293.614903557356 mm³`; in-memory and STEP-reimport values are within `0.01 mm³` under the existing bounded mass-property tessellation tolerance. The exported STEP contains planes and four cylindrical surfaces, with no B-spline fallback.++X1 remains deliberately bounded: it does not support splines, offsets, non-planar profiles, disconnected multibody output, or fuzzy tolerance healing. Coincident support with contradictory local material state and unresolved equal-angle continuations rejects before BRep emission.diff --git a/docs/firmament/profile-composition-x1.md b/docs/firmament/profile-composition-x1.mdnew file mode 100644index 00000000..7ee1d7df--- /dev/null+++ b/docs/firmament/profile-composition-x1.md@@ -0,0 +1,33 @@+# Profile composition X1++`Compose` is the first source form for one prismatic material body whose section changes at named axial levels. Its doctrine is:++> Compose material regions first. Emit topology once.++```firmament+Struct Part {+ Compose Body {+ Base Stock { Profile: Plate; From: 0mm; To: 10mm; Role: Stock }+ Add Boss { Profile: Pad; From: 10mm; To: 15mm; Role: Boss }+ Remove Relief { Profile: Pocket; From: 7mm; To: 10mm; Role: Relief }+ }+}+```++`Base` is mandatory and unique. `Add` and `Remove` retain operation name, referenced scaffold-backed `Profile`, interval, role, and source span. The parser resolves every named profile independently using the existing `Point2`/`Line2`/`Circle2` profile route.++The Feature AIR is `PrismaticProfileCompositionFeature`; lowering creates `PrismaticSectionStackConstruction` with sorted critical levels, open slabs, explicit material regions, transition regions, provenance, and analytic volume. The emitter owns one `PrismaticSectionStackBrepPlan` and preserves deterministic slab partitions rather than aggressively merging faces.++X1 normalizes each active slab through `ProfileArrangement2D`: it analytically intersects bounded line-line, line-circle, and circle-circle source curves, splits every source parameter interval deterministically, samples the two sides of each atomic fragment with the set predicate `(Base ∪ Add) − Remove`, and retains only material/void boundaries. Source curves are split by geometry, but never stripped of provenance. The resulting material-left loops are reconstructed deterministically; the production route rejects disconnected material, dangling boundaries, zero-area loops, and ambiguous angular continuation.++Coincident source support is normalized by side classification: duplicate Add/Add and Remove/Remove fragments vanish as internal boundaries, while the stable lowest source ID retains the provenance of a surviving boundary. Point-only tangencies naturally produce multiple outer loops and are rejected instead of being perturbed into a crossing. The arrangement output is converted to the same explicit outer/inner section-region contract consumed by the one authoritative section-stack BRep plan; no operation solids or 3D Booleans are materialized.++At a critical level the compiler compares the two adjacent sections. `below - above` produces upward material (including a pocket floor); `above - below` produces downward material. Lines become planar vertical faces and arcs cylindrical vertical faces. Directed edge topology is shared across slabs and caps; coedge reversal is used exactly once per traversal.++Use `aetheris inspect-compose file.firmament --json` before `build`. The report includes operations, levels, active slabs, areas, transitions, analytic volume, independently evaluated in-memory BRep volume, plan signature, and per-slab arrangement source/intersection/fragment/loop/perimeter/timing/provenance evidence.++The raised-pad, shallow-pocket, and through-cut fixtures remain enclosed manifold STEPs with analytic/in-memory/reimported BRep agreement. Overlapping additive rectangles and overlapping removal rectangles now normalize to one exact line-only region and round-trip as an enclosed analytic STEP. The line parameter is normalized endpoint distance `[0,1]`; an arc parameter is normalized along its explicit signed angular sweep. This distinction is required because STEP export may resolve a vertex from its incident edge trim.++The mixed line/arc additive fixture additionally proves that a split arc is emitted as a `CIRCLE` with its actual bounded angular trim, including reverse traversal, rather than as a full circle or a spline. Profiles are the bounded planar escape hatch for custom prismatic blockout, not the default representation for every semantic CNC feature.++`Rect2` may replace manually declared rectangular corners and sides in this source route. It uses `Center: [xmm, ymm]` and `Size: [wmm, hmm]`; derived finite sides are traced as `Base.Bottom`, `Base.Right`, `Base.Top`, and `Base.Left` with corresponding named corners.diff --git a/docs/llm-cad-strategy/06-profiles-as-constructive-regions.md b/docs/llm-cad-strategy/06-profiles-as-constructive-regions.mdindex 4626a8c8..acbb42c7 100644--- a/docs/llm-cad-strategy/06-profiles-as-constructive-regions.md+++ b/docs/llm-cad-strategy/06-profiles-as-constructive-regions.md@@ -391,6 +391,10 @@ Precision is not the same as intent. A coordinate-perfect loop can still be a poThis lesson extends the spatial decomposition approach from [04 — Spatial decomposition first pass](04-spatial-decomposition-first-pass.md). Constructive profiles are part of the shape spine and blockout layer: they help an LLM decide what the gross 2D mass is before adding smaller children and finish details.+## Section-stack composition++When several named profiles describe one stepped prismatic body, author one shared Concept scaffold, inspect every Profile, then declare explicit `Base`, `Add`, and `Remove` axial intervals in `Compose`. Inspect the normalized section stack before building. The compiler must resolve material per open Z interval and emit one final topology plan; do not construct temporary solids and ask generic 3D Booleans to recover the intended topology afterward. See [profile composition X1](../firmament/profile-composition-x1.md) for the admitted contact policy and current verification boundary.+It also follows [05 — CAD as semantic dependency graph](05-cad-as-semantic-dependency-graph.md). Raw boundaries are lowered forms. Constructive profile regions belong before extrusion when they define the trunk shape. Profile cornering belongs before extrusion when it changes the silhouette. 3D edge finish remains a late decorator in the dependency graph.The dependency question is therefore: does this 2D curve define the region that becomes mass, or does it decorate an edge after mass exists? Answer that before choosing profile syntax.diff --git a/docs/reconstruction/ctc01-compose-x1.md b/docs/reconstruction/ctc01-compose-x1.mdnew file mode 100644index 00000000..3ca4341e--- /dev/null+++ b/docs/reconstruction/ctc01-compose-x1.md@@ -0,0 +1,9 @@+# CTC-01 compose X1 status++CTC-01 is no longer blocked by the core proper-overlap arrangement primitive. `Compose` now resolves active Profiles into one analytic line/arc arrangement before producing one section-stack topology plan; it does not create temporary operation solids. A bounded CTC reconstruction remains deferred because the source-analysis evidence has not yet isolated an Observed/StrongInference prismatic subset worth promoting.++The executable raised-pad proof has critical levels `0, 10, 15`, slab areas `400, 64`, analytic volume `4320 mm³`, and independent in-memory BRep volume `4319.999999999998 mm³`. Its exported STEP (`artifacts/raised-pad-compose.step`) reimports as one enclosed manifold body.++The shallow-pocket proof now has analytic, in-memory, and STEP-reimported mass `3808 mm³` (reimport result `3807.9999999999995`). The contained through-cut has the corresponding four-way material evidence at `3640 mm³` (reimport result `3639.9999999999995`). The repaired artifacts are topology-enclosed and orientation-consistent under independent BRep mass evaluation. Consequently no CTC profiles, observed Z-levels, or reference-equivalence claims are promoted by this increment: the remaining CTC gate is exact proper-overlap line/arc arrangement.++The mixed line/arc fixture now proves transverse line/circle splitting through analytic STEP round-trip. The remaining CTC pressure-test blocker is not the arrangement kernel but a high-confidence observed/strong-inference CTC subset whose source profile can be stated without inventing named silhouette geometry; no complete CTC claim is made.diff --git a/docs/verification/profile-compose-inner-loop-x1.md b/docs/verification/profile-compose-inner-loop-x1.mdnew file mode 100644index 00000000..34ffe79f--- /dev/null+++ b/docs/verification/profile-compose-inner-loop-x1.md@@ -0,0 +1,26 @@+# Profile composition inner-loop X1 investigation++Inner loops are explicit material semantics, not inferred decoration.++The STEP exporter serializes the shallow-pocket top cap as one `FACE_OUTER_BOUND` and one `FACE_BOUND`; the latter preserves its clockwise `EDGE_LOOP` traversal. The importer now preserves that declared order and role when exactly one outer bound is present, instead of silently reclassifying and normalizing it from area/winding.++The proven defect was producer-side trim binding. The section-stack emitter assigned `0..2π` to every edge, including lines. During STEP export, vertices without a direct point binding may be recovered from that interval; therefore vertical seam vertices were emitted `2π` units along their line rather than at the declared slab level. The shallow pocket exposed this because its exterior wall is partitioned at the pocket floor. Line bindings now use their exact endpoint distance; circles retain `0..2π`.++After the repair, the shallow-pocket analytic, in-memory, and reimported volumes agree at `3808 mm³` (floating-point result `3807.9999999999995`). The through-cut reimports at `3639.9999999999995 mm³`, matching `3640 mm³`; the raised pad remains `4319.999999999998 mm³` against analytic `4320 mm³`.++Canonical policy: topology edge start/end and `ORIENTED_EDGE.orientation` determine coedge traversal; `EDGE_CURVE.same_sense` only maps curve parameter direction to topology endpoints; `FACE_OUTER_BOUND`/`FACE_BOUND` carry explicit loop role; `FACE_BOUND.orientation` is retained as STEP source evidence; `ADVANCED_FACE.same_sense` applies once between support surface and face orientation. Import must not mutate `EDGE_LOOP` order to satisfy a local winding preference.++`Rect2` is available to the profile-authoring and composition source route with `Center` and `Size`. It derives stable `BottomLeft`, `BottomRight`, `TopRight`, `TopLeft`, `Bottom`, `Right`, `Top`, and `Left` guides. Profiles trace the derived sides through normal Profile IR, with provenance such as `concept:Rect2Layout.Base.Bottom`.++## Hash-tied evidence++The 2026-08-04 artifacts were emitted beneath `artifacts/profile-compose-inner-loop-x1/` and then reimported by `aetheris verify`. Independent BRep mass is enclosed and orientation-consistent in every row. The CLI correctly records external CAD inspection as `ExternalInspectionPending`; that is not substituted for a visual-CAD claim.++| Artifact | SHA-256 | Analytic | Reimported BRep mass |+| --- | --- | ---: | ---: |+| raised pad | `f605df9f5136d51b6a19df46a030684731969928e19f580efb69ee375f5a8924` | 4320 | 4319.999999999998 |+| shallow pocket | `650b43bea4732edafd67c0081fd836967d51e9768b9d1b1c0c37520f80455259` | 3808 | 3807.9999999999995 |+| through cut | `e7c59ede59a3de2546dfef73f9da54cd228d086ed473ae2c0a6a2b3e44bfddf0` | 3640 | 3639.9999999999995 |+| Rect2 profile extrusion | `7dba6137e1c34b008cc238a5558eca6462119928135bfd5f96bc511882382666` | 1000 | build smoke |++The focused regression test `PrismaticProfileCompositionRoundTripTests` asserts the analytic, in-memory mass, STEP export with enforcing preflight, and reimported mass for both the shallow pocket and through cut.diff --git a/fixtures/FirmamentV2/ProfileComposition/mixed-line-arc-additive-overlap.firmament b/fixtures/FirmamentV2/ProfileComposition/mixed-line-arc-additive-overlap.firmamentnew file mode 100644index 00000000..550bd903--- /dev/null+++ b/fixtures/FirmamentV2/ProfileComposition/mixed-line-arc-additive-overlap.firmament@@ -0,0 +1,25 @@+Concept Struct Layout On XY {+ Rect2 BaseGuide { Center: [0mm, 0mm]; Size: [20mm, 20mm]; Role: ProfileGuide }+ Point2 RoundCenter { Position: [0mm, 12mm] }+ Point2 RoundBottom { Position: [0mm, 7mm] }+ Point2 RoundRight { Position: [5mm, 12mm] }+ Point2 RoundTop { Position: [0mm, 17mm] }+ Point2 RoundLeft { Position: [-5mm, 12mm] }+ Circle2 RoundGuide { Center: RoundCenter; Radius: 5mm }+}+Profile BaseProfile Using Layout { Loop Outer {+ Segment South { Trace: BaseGuide.Bottom; From: BaseGuide.BottomLeft; To: BaseGuide.BottomRight }+ Segment East { Trace: BaseGuide.Right; From: BaseGuide.BottomRight; To: BaseGuide.TopRight }+ Segment North { Trace: BaseGuide.Top; From: BaseGuide.TopRight; To: BaseGuide.TopLeft }+ Segment West { Trace: BaseGuide.Left; From: BaseGuide.TopLeft; To: BaseGuide.BottomLeft }+} }+Profile RoundPad Using Layout { Loop Outer {+ Segment ArcEast { Trace: RoundGuide; From: RoundBottom; To: RoundRight; Sweep: CounterClockwise }+ Segment ArcNorth { Trace: RoundGuide; From: RoundRight; To: RoundTop; Sweep: CounterClockwise }+ Segment ArcWest { Trace: RoundGuide; From: RoundTop; To: RoundLeft; Sweep: CounterClockwise }+ Segment ArcSouth { Trace: RoundGuide; From: RoundLeft; To: RoundBottom; Sweep: CounterClockwise }+} }+Struct Composition { Compose Body {+ Base Stock { Profile: BaseProfile; From: 0mm; To: 15mm; Role: Stock }+ Add Round { Profile: RoundPad; From: 10mm; To: 15mm; Role: Pad }+} }diff --git a/fixtures/FirmamentV2/ProfileComposition/overlapping-additive-rectangles.firmament b/fixtures/FirmamentV2/ProfileComposition/overlapping-additive-rectangles.firmamentnew file mode 100644index 00000000..34e23caf--- /dev/null+++ b/fixtures/FirmamentV2/ProfileComposition/overlapping-additive-rectangles.firmament@@ -0,0 +1,28 @@+Concept Struct Layout On XY {+ Rect2 BaseGuide { Center: [0mm, 0mm]; Size: [20mm, 20mm]; Role: ProfileGuide }+ Rect2 LeftGuide { Center: [-3mm, 10mm]; Size: [10mm, 10mm]; Role: ProfileGuide }+ Rect2 RightGuide { Center: [3mm, 10mm]; Size: [10mm, 10mm]; Role: ProfileGuide }+}+Profile BaseProfile Using Layout { Loop Outer {+ Segment South { Trace: BaseGuide.Bottom; From: BaseGuide.BottomLeft; To: BaseGuide.BottomRight }+ Segment East { Trace: BaseGuide.Right; From: BaseGuide.BottomRight; To: BaseGuide.TopRight }+ Segment North { Trace: BaseGuide.Top; From: BaseGuide.TopRight; To: BaseGuide.TopLeft }+ Segment West { Trace: BaseGuide.Left; From: BaseGuide.TopLeft; To: BaseGuide.BottomLeft }+} }+Profile LeftProfile Using Layout { Loop Outer {+ Segment South { Trace: LeftGuide.Bottom; From: LeftGuide.BottomLeft; To: LeftGuide.BottomRight }+ Segment East { Trace: LeftGuide.Right; From: LeftGuide.BottomRight; To: LeftGuide.TopRight }+ Segment North { Trace: LeftGuide.Top; From: LeftGuide.TopRight; To: LeftGuide.TopLeft }+ Segment West { Trace: LeftGuide.Left; From: LeftGuide.TopLeft; To: LeftGuide.BottomLeft }+} }+Profile RightProfile Using Layout { Loop Outer {+ Segment South { Trace: RightGuide.Bottom; From: RightGuide.BottomLeft; To: RightGuide.BottomRight }+ Segment East { Trace: RightGuide.Right; From: RightGuide.BottomRight; To: RightGuide.TopRight }+ Segment North { Trace: RightGuide.Top; From: RightGuide.TopRight; To: RightGuide.TopLeft }+ Segment West { Trace: RightGuide.Left; From: RightGuide.TopLeft; To: RightGuide.BottomLeft }+} }+Struct Composition { Compose Body {+ Base Stock { Profile: BaseProfile; From: 0mm; To: 15mm; Role: Stock }+ Add Left { Profile: LeftProfile; From: 10mm; To: 15mm; Role: Pad }+ Add Right { Profile: RightProfile; From: 10mm; To: 15mm; Role: Pad }+} }diff --git a/fixtures/FirmamentV2/ProfileComposition/valid/raised-pad.firmament b/fixtures/FirmamentV2/ProfileComposition/valid/raised-pad.firmamentnew file mode 100644index 00000000..1b9ddf9c--- /dev/null+++ b/fixtures/FirmamentV2/ProfileComposition/valid/raised-pad.firmament@@ -0,0 +1,30 @@+Concept Struct RaisedPadLayout On XY {+ Point2 A { Position: [-10mm, -10mm] }+ Point2 B { Position: [10mm, -10mm] }+ Point2 C { Position: [10mm, 10mm] }+ Point2 D { Position: [-10mm, 10mm] }+ Point2 E { Position: [-4mm, -4mm] }+ Point2 F { Position: [4mm, -4mm] }+ Point2 G { Position: [4mm, 4mm] }+ Point2 H { Position: [-4mm, 4mm] }+ Line2 AB { From: A; To: B } Line2 BC { From: B; To: C } Line2 CD { From: C; To: D } Line2 DA { From: D; To: A }+ Line2 EF { From: E; To: F } Line2 FG { From: F; To: G } Line2 GH { From: G; To: H } Line2 HE { From: H; To: E }+}+Profile Plate Using RaisedPadLayout {+ Loop Outer {+ Segment AB { Trace: AB; From: A; To: B } Segment BC { Trace: BC; From: B; To: C }+ Segment CD { Trace: CD; From: C; To: D } Segment DA { Trace: DA; From: D; To: A }+ }+}+Profile Pad Using RaisedPadLayout {+ Loop Outer {+ Segment EF { Trace: EF; From: E; To: F } Segment FG { Trace: FG; From: F; To: G }+ Segment GH { Trace: GH; From: G; To: H } Segment HE { Trace: HE; From: H; To: E }+ }+}+Struct RaisedPad {+ Compose Body {+ Base PrimaryPlate { Profile: Plate; From: 0mm; To: 10mm; Role: Stock }+ Add CentralPad { Profile: Pad; From: 10mm; To: 15mm; Role: Boss }+ }+}diff --git a/fixtures/FirmamentV2/ProfileComposition/valid/rect2-profile-extrude.firmament b/fixtures/FirmamentV2/ProfileComposition/valid/rect2-profile-extrude.firmamentnew file mode 100644index 00000000..2d63ea77--- /dev/null+++ b/fixtures/FirmamentV2/ProfileComposition/valid/rect2-profile-extrude.firmament@@ -0,0 +1,12 @@+Concept Struct Rect2Layout On XY {+ Rect2 Base { Center: [0mm, 0mm]; Size: [20mm, 10mm]; Role: ProfileGuide }+}+Profile MainPlate Using Rect2Layout {+ Loop Outer {+ Segment South { Trace: Base.Bottom; From: Base.BottomLeft; To: Base.BottomRight }+ Segment East { Trace: Base.Right; From: Base.BottomRight; To: Base.TopRight }+ Segment North { Trace: Base.Top; From: Base.TopRight; To: Base.TopLeft }+ Segment West { Trace: Base.Left; From: Base.TopLeft; To: Base.BottomLeft }+ }+}+Struct Plate { Extrude MainPlate { Profile: MainPlate; From: 0mm; To: 5mm } }diff --git a/fixtures/FirmamentV2/ProfileComposition/valid/shallow-pocket.firmament b/fixtures/FirmamentV2/ProfileComposition/valid/shallow-pocket.firmamentnew file mode 100644index 00000000..1abf78c4--- /dev/null+++ b/fixtures/FirmamentV2/ProfileComposition/valid/shallow-pocket.firmament@@ -0,0 +1,9 @@+Concept Struct PocketLayout On XY {+ Point2 A { Position: [-10mm, -10mm] } Point2 B { Position: [10mm, -10mm] } Point2 C { Position: [10mm, 10mm] } Point2 D { Position: [-10mm, 10mm] }+ Point2 E { Position: [-4mm, -4mm] } Point2 F { Position: [4mm, -4mm] } Point2 G { Position: [4mm, 4mm] } Point2 H { Position: [-4mm, 4mm] }+ Line2 AB { From: A; To: B } Line2 BC { From: B; To: C } Line2 CD { From: C; To: D } Line2 DA { From: D; To: A }+ Line2 EF { From: E; To: F } Line2 FG { From: F; To: G } Line2 GH { From: G; To: H } Line2 HE { From: H; To: E }+}+Profile Plate Using PocketLayout { Loop Outer { Segment AB { Trace: AB; From: A; To: B } Segment BC { Trace: BC; From: B; To: C } Segment CD { Trace: CD; From: C; To: D } Segment DA { Trace: DA; From: D; To: A } } }+Profile Pocket Using PocketLayout { Loop Outer { Segment EF { Trace: EF; From: E; To: F } Segment FG { Trace: FG; From: F; To: G } Segment GH { Trace: GH; From: G; To: H } Segment HE { Trace: HE; From: H; To: E } } }+Struct Pocket { Compose Body { Base PrimaryPlate { Profile: Plate; From: 0mm; To: 10mm; Role: Stock } Remove TopPocket { Profile: Pocket; From: 7mm; To: 10mm; Role: Relief } } }diff --git a/fixtures/FirmamentV2/ProfileComposition/valid/through-profile-cut.firmament b/fixtures/FirmamentV2/ProfileComposition/valid/through-profile-cut.firmamentnew file mode 100644index 00000000..7d663133--- /dev/null+++ b/fixtures/FirmamentV2/ProfileComposition/valid/through-profile-cut.firmament@@ -0,0 +1,9 @@+Concept Struct ThroughCutLayout On XY {+ Point2 A { Position: [-10mm, -10mm] } Point2 B { Position: [10mm, -10mm] } Point2 C { Position: [10mm, 10mm] } Point2 D { Position: [-10mm, 10mm] }+ Point2 E { Position: [-3mm, -3mm] } Point2 F { Position: [3mm, -3mm] } Point2 G { Position: [3mm, 3mm] } Point2 H { Position: [-3mm, 3mm] }+ Line2 AB { From: A; To: B } Line2 BC { From: B; To: C } Line2 CD { From: C; To: D } Line2 DA { From: D; To: A }+ Line2 EF { From: E; To: F } Line2 FG { From: F; To: G } Line2 GH { From: G; To: H } Line2 HE { From: H; To: E }+}+Profile Plate Using ThroughCutLayout { Loop Outer { Segment AB { Trace: AB; From: A; To: B } Segment BC { Trace: BC; From: B; To: C } Segment CD { Trace: CD; From: C; To: D } Segment DA { Trace: DA; From: D; To: A } } }+Profile Cut Using ThroughCutLayout { Loop Outer { Segment EF { Trace: EF; From: E; To: F } Segment FG { Trace: FG; From: F; To: G } Segment GH { Trace: GH; From: G; To: H } Segment HE { Trace: HE; From: H; To: E } } }+Struct ThroughCut { Compose Body { Base PrimaryPlate { Profile: Plate; From: 0mm; To: 10mm; Role: Stock } Remove ThroughCut { Profile: Cut; From: 0mm; To: 10mm; Role: Opening } } }