Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add section inspection and composition materialization diagnostics

Yuechen Lid65e80f4b945
diff --git a/Aetheris.CLI.Tests/InspectComposeArrangementPolicyTests.cs b/Aetheris.CLI.Tests/InspectComposeArrangementPolicyTests.cs
index bffb2194..74608aac 100644
--- a/Aetheris.CLI.Tests/InspectComposeArrangementPolicyTests.cs
+++ b/Aetheris.CLI.Tests/InspectComposeArrangementPolicyTests.cs
@@ -11,7 +11,7 @@ public sealed class InspectComposeArrangementPolicyTests
{
var source = Path.Combine(RepoRoot, "testdata/firmament/reconstructions/nist_ctc_01/ctc01_prismatic_blockout_x2.firmament");
var stdout = new StringWriter(); var stderr = new StringWriter();
- var exit = Aetheris.CLI.CliRunner.Run(["inspect-compose", source, "--json"], stdout, stderr);
+ var exit = Aetheris.CLI.CliRunner.Run(["inspect-compose", source, "--json", "--materialize"], stdout, stderr);
Assert.Equal(0, exit); Assert.True(string.IsNullOrWhiteSpace(stderr.ToString()), stderr.ToString());
using var json = JsonDocument.Parse(stdout.ToString());
var composition = json.RootElement.GetProperty("composition");
@@ -21,11 +21,11 @@ public sealed class InspectComposeArrangementPolicyTests
Assert.Equal("XY", placement.GetProperty("profilePlane").GetString());
Assert.Equal("+Z", placement.GetProperty("axis").GetString());
Assert.Equal("+X", placement.GetProperty("referenceDirection").GetString());
- Assert.Equal("NumericalWithBound", composition.GetProperty("bRepStatus").GetString());
- Assert.True(composition.GetProperty("bRepEnclosed").GetBoolean());
+ Assert.Equal("NumericalWithBound", composition.GetProperty("materialization").GetProperty("bRepStatus").GetString());
+ Assert.True(composition.GetProperty("materialization").GetProperty("bRepEnclosed").GetBoolean());
var shoulder = Assert.Single(composition.GetProperty("transitions").EnumerateArray(), item => item.GetProperty("level").GetDouble() == -60d);
Assert.Equal(2, shoulder.GetProperty("downwardRegionCount").GetInt32());
- Assert.True(composition.GetProperty("bRepPlan").GetProperty("authoritative").GetBoolean());
+ Assert.True(composition.GetProperty("materialization").GetProperty("bRepPlan").GetProperty("authoritative").GetBoolean());
}
[Fact]
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index c302e096..217e971e 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -1,4 +1,5 @@
using System.Security.Cryptography;
+using System.Diagnostics;
using System.Text.Json;
using System.Text.Json.Serialization;
using Aetheris.Forge.Abstractions.FirmamentInterop;
@@ -112,16 +113,17 @@ public static class CliRunner
string? Error,
string? Classification = null,
int? RigidRootCount = null);
- private const string TopLevelUsage = "Usage: aetheris <build|validate|inspect-profile|inspect-compose|analyze|verify|match|trace|canon|asm|experimental> <path> [options]";
+ private const string TopLevelUsage = "Usage: aetheris <build|validate|inspect-profile|inspect-compose|sections|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 InspectComposeUsage = "Usage: aetheris inspect-compose <file.firmament> --json [--materialize]";
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";
private const string AnalyzeVolumeUsage = "Usage: aetheris analyze volume <file.step> [--approximate --resolution <N>] [--json]";
private const string AnalyzeCompareUsage = "Usage: aetheris analyze compare <reference.step> <candidate.step> [--approximate-volume --resolution <N>] [--json]";
+ private const string SectionsUsage = "Usage: aetheris sections <artifact.step> --axis Z --levels <z,...> [--epsilon <mm>] --json";
private const string VerifyUsage = "Usage: aetheris verify <artifact.step> [--expected-volume <value>] [--cad-assistant] [--cad-assistant-path <path>] [--timeout <seconds>] [--evidence-dir <path>] [--require-external] [--json]";
private const string MatchUsage = "Usage: aetheris match <file.step> <concept.firmament> [--linear-tolerance <mm>] [--angular-tolerance <deg>] [--json]";
private const string TraceUsage = "Usage: aetheris trace (--case <name>|--fixture <path>) [--out-dir <dir>] [--json]";
@@ -175,6 +177,7 @@ public static class CliRunner
"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),
+ "sections" => RunSections(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),
@@ -427,7 +430,7 @@ public static class CliRunner
provenance = profile.Loops.SelectMany(x => x.Segments).Select(x => new { x.Name, x.Provenance.StableId, x.Provenance.ConceptStableId, x.Provenance.Derivation })
};
}).ToArray();
- stdout.WriteLine(JsonSerializer.Serialize(new { profiles, diagnostics = composition.Diagnostics }, JsonOptions));
+ stdout.WriteLine(JsonSerializer.Serialize(new { profiles, expansion = composition.Expansion, diagnostics = composition.Diagnostics }, JsonOptions));
return composition.Diagnostics.Count == 0 && profiles.All(x => x.IsValid) ? 0 : 1;
}
var parsed = ProfileAuthoringParser.Parse(source);
@@ -468,28 +471,36 @@ public static class CliRunner
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; }
+ var json = args.Skip(1).Any(x => x == "--json");
+ var materialize = args.Skip(1).Any(x => x == "--materialize");
+ if (!json || args.Skip(1).Any(x => x is not "--json" and not "--materialize")) { stderr.WriteLine(InspectComposeUsage); return 1; }
if (!File.Exists(args[0])) { stderr.WriteLine($"Composition source was not found: {args[0]}"); return 1; }
+ var total = Stopwatch.StartNew();
+ var parseClock = Stopwatch.StartNew();
var parsed = PrismaticProfileCompositionParser.Parse(File.ReadAllText(args[0]));
+ parseClock.Stop(); var normalizeClock = Stopwatch.StartNew();
var stack = PrismaticSectionStackCompiler.Normalize(parsed, out var diagnostics);
+ normalizeClock.Stop();
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);
+ PrismaticSectionStackEmissionResult? emitted = null; BrepMassPropertiesResult? mass = null;
+ var materializeClock = TimeSpan.Zero;
+ if (materialize) { var clock = Stopwatch.StartNew(); emitted = PrismaticSectionStackEmitter.Emit(stack); mass = emitted.Body is null ? null : BrepMassProperties.Evaluate(emitted.Body); clock.Stop(); materializeClock = clock.Elapsed; }
+ total.Stop();
var report = new
{
composition = new
{
name = stack.Feature.Name, frame = stack.Feature.Frame, axis = stack.Feature.Axis,
placement = new { stack.Feature.Placement.Name, anchor = new[] { stack.Feature.Placement.AnchorX, stack.Feature.Placement.AnchorY, stack.Feature.Placement.AnchorZ }, profilePlane = stack.Feature.Placement.ProfilePlane, stack.Feature.Placement.Axis, stack.Feature.Placement.ReferenceDirection, stack.Feature.Placement.IsExplicit },
- operations = stack.Feature.Operations.Select(x => new { x.Name, intent = x.Intent.ToString(), profile = x.ProfileReference, x.From, x.To, x.SemanticRole, x.SourceSpan }),
+ signatures = new { composition = CompositionSignature(stack), profiles = parsed.Profiles.OrderBy(x => x.Key, StringComparer.Ordinal).ToDictionary(x => x.Key, x => ProfileSignature(x.Value), StringComparer.Ordinal) },
+ operations = stack.Feature.Operations.Select(x => new { x.Name, intent = x.Intent.ToString(), profile = x.ProfileReference, x.From, x.To, x.SemanticRole, x.SourceSpan, signature = Hash($"{x.Intent}|{x.ProfileReference}|{x.From:R}|{x.To:R}|{x.SemanticRole}") }),
criticalLevels = stack.Feature.CriticalLevels,
slabs = stack.Slabs.Select(x => new
{
x.From,
x.To,
x.ActiveOperations,
- area = PrismaticSectionStackCompiler.Area(x.Region),
+ area = PrismaticSectionStackCompiler.Area(x.Region), signature = ProfileSignature(x.Region.Outer),
outerLoops = 1,
innerLoops = x.Region.Holes.Count,
loops = new[]
@@ -514,14 +525,11 @@ public static class CliRunner
}),
transitions = stack.Transitions.Select(x => new { x.Level, upwardRegionCount = x.UpwardRegions.Count, downwardRegionCount = x.DownwardRegions.Count, upwardArea = x.UpwardRegions.Sum(PrismaticSectionStackCompiler.Area), downwardArea = x.DownwardRegions.Sum(PrismaticSectionStackCompiler.Area) }),
analyticVolume = stack.AnalyticVolume,
- bRepStatus = mass?.Status.ToString(),
- bRepVolume = mass?.AbsoluteVolume,
- volumeDelta = mass is null ? (double?)null : mass.AbsoluteVolume - stack.AnalyticVolume,
- bRepErrorBound = mass?.ErrorBound,
- bRepEnclosed = mass?.IsEnclosed,
- bRepDiagnostics = mass?.Diagnostics,
- bRepPlan = emitted.Plan,
- diagnostics = emitted.Diagnostics
+ materialization = materialize ? new { bRepStatus = mass?.Status.ToString(), bRepVolume = mass?.AbsoluteVolume, volumeDelta = mass is null ? (double?)null : mass.AbsoluteVolume - stack.AnalyticVolume, bRepErrorBound = mass?.ErrorBound, bRepEnclosed = mass?.IsEnclosed, bRepDiagnostics = mass?.Diagnostics, bRepPlan = emitted?.Plan } : null,
+ expansion = parsed.Expansion,
+ timingsMilliseconds = new { parse = parseClock.Elapsed.TotalMilliseconds, normalize = normalizeClock.Elapsed.TotalMilliseconds, materialize = materializeClock.TotalMilliseconds, total = total.Elapsed.TotalMilliseconds },
+ executionBoundary = new { inspectionOnly = !materialize, bRepMaterialized = materialize, stepExported = false, m8Executed = false, cirExecuted = false },
+ diagnostics = emitted?.Diagnostics ?? stack.Diagnostics
}
};
stdout.WriteLine(JsonSerializer.Serialize(report, JsonOptions));
@@ -2392,6 +2400,31 @@ public static class CliRunner
return 0;
}
+ private static int RunSections(string[] args, TextWriter stdout, TextWriter stderr)
+ {
+ if (args.Length == 0 || IsHelpFlag(args[0])) { stdout.WriteLine(SectionsUsage); return args.Length == 0 ? 1 : 0; }
+ var step = args[0]; string? axis = null; string? levelText = null; var epsilon = .001d; var json = false;
+ for (var i = 1; i < args.Length; i++)
+ switch (args[i])
+ {
+ case "--axis" when i + 1 < args.Length: axis = args[++i]; break;
+ case "--levels" when i + 1 < args.Length: levelText = args[++i]; break;
+ case "--epsilon" when i + 1 < args.Length && double.TryParse(args[++i], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var e) && e > 0: epsilon = e; break;
+ case "--json": json = true; break;
+ default: stderr.WriteLine(SectionsUsage); return 1;
+ }
+ if (!json || !string.Equals(axis, "Z", StringComparison.OrdinalIgnoreCase) || string.IsNullOrWhiteSpace(levelText)) { stderr.WriteLine(SectionsUsage); return 1; }
+ var levels = levelText.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(x => double.TryParse(x, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var z) ? (double?)z : null).ToArray();
+ if (levels.Length == 0 || levels.Any(x => x is null)) { stderr.WriteLine("--levels requires comma-separated numeric values."); return 1; }
+ try
+ {
+ var result = new { artifact = Path.GetFullPath(step), axis = "Z", epsilon, policy = "Below/Above are requested level ± epsilon; At is never shifted and is diagnostic.", levels = levels.Select(x => new { requestedLevel = x!.Value, below = StepAnalyzer.AnalyzeSection(step, SectionPlaneFamily.XY, x.Value - epsilon), at = StepAnalyzer.AnalyzeSection(step, SectionPlaneFamily.XY, x.Value), above = StepAnalyzer.AnalyzeSection(step, SectionPlaneFamily.XY, x.Value + epsilon) }).ToArray() };
+ stdout.WriteLine(JsonSerializer.Serialize(result, JsonOptions)); return 0;
+ }
+ catch (Exception ex) { stderr.WriteLine($"sections failed: {ex.Message}"); return 1; }
+ }
+
+
private static void WriteSummaryText(AnalyzeResult analysis, TextWriter stdout)
{
var summary = analysis.Summary;
@@ -2531,6 +2564,7 @@ public static class CliRunner
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(" sections Normalize exact horizontal STEP section fragments.");
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.");
@@ -2560,6 +2594,7 @@ public static class CliRunner
stdout.WriteLine(" aetheris experimental prismatic-map --case rectangle-inset --rows 16 --cols 16 --json");
stdout.WriteLine(" aetheris analyze map model.step --top --rows 40 --cols 60 --json");
stdout.WriteLine(" aetheris analyze section model.step --xy --offset 2.5 --json");
+ stdout.WriteLine(" aetheris sections model.step --axis Z --levels -100,-60,-50,0,5,50 --json");
stdout.WriteLine(" aetheris analyze volume model.step --json");
stdout.WriteLine(" aetheris verify model.step --json");
stdout.WriteLine();
@@ -2930,4 +2965,15 @@ public static class CliRunner
vector is null ? "n/a" : $"({vector.Value.X:F6},{vector.Value.Y:F6},{vector.Value.Z:F6})";
private static string FormatDouble(double? value) => value?.ToString("G17") ?? "n/a";
+
+ private static string ProfileSignature(ResolvedProfile2D profile) => Hash(string.Join(";", profile.Loops.SelectMany(l => l.Segments).Select(s => s.Geometry switch
+ {
+ LineArcLineSegment2D line => $"L:{Q(line.Start.X)},{Q(line.Start.Y)}:{Q(line.End.X)},{Q(line.End.Y)}",
+ LineArcCircularArc2D arc => $"A:{Q(arc.Center.X)},{Q(arc.Center.Y)}:{Q(arc.Radius)}:{Q(arc.StartAngleRadians)}:{Q(arc.SweepAngleRadians)}",
+ _ => s.Geometry.GetType().Name
+ }).OrderBy(x => x, StringComparer.Ordinal)));
+
+ private static string CompositionSignature(PrismaticSectionStackConstruction stack) => Hash(string.Join("|", stack.Slabs.Select(s => $"{Q(s.From)}:{Q(s.To)}:{ProfileSignature(s.Region.Outer)}:{Q(PrismaticSectionStackCompiler.Area(s.Region))}")));
+ private static string Hash(string value) => Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(value))).ToLowerInvariant();
+ private static long Q(double value) => (long)Math.Round(value * 1_000_000d, MidpointRounding.AwayFromZero);
}
diff --git a/Aetheris.CLI/StepAnalysisModels.cs b/Aetheris.CLI/StepAnalysisModels.cs
index 634a08f2..5a07d303 100644
--- a/Aetheris.CLI/StepAnalysisModels.cs
+++ b/Aetheris.CLI/StepAnalysisModels.cs
@@ -190,17 +190,58 @@ public sealed record SectionSegment(
double? Radius,
string? Direction,
double? SweepRadians,
- string? UnsupportedReason);
+ string? UnsupportedReason,
+ int? SourceFace = null,
+ string? SourceEntity = null,
+ string? SurfaceFamily = null,
+ string? ParameterKind = null,
+ double? ParameterFrom = null,
+ double? ParameterTo = null,
+ string? MaterialSideEvidence = null);
+
+public sealed record SectionFragmentEvidence(
+ string FragmentId,
+ int SourceFace,
+ string SourceEntity,
+ string SurfaceFamily,
+ string CurveFamily,
+ string ParameterKind,
+ double ParameterFrom,
+ double ParameterTo,
+ Point2D Start,
+ Point2D End,
+ Point2D? Center,
+ double? Radius,
+ string MaterialSideEvidence);
public sealed record SectionLoop(
int LoopId,
bool IsClosed,
string? Winding,
BoundingBox2D? BoundingBox2D,
- IReadOnlyList<SectionSegment> Segments);
+ IReadOnlyList<SectionSegment> Segments,
+ string? Role = null);
+
+/// <summary>Accounting for the deterministic analytic section-normalization route.</summary>
+public sealed record SectionNormalizationDiagnostics(
+ int RawFragmentCount,
+ int CanonicalVertexCount,
+ int AtomicFragmentCount,
+ int CollapsedDuplicateCount,
+ int NormalizedLoopCount,
+ int OuterLoopCount,
+ int InnerLoopCount,
+ int UnaccountedFragmentCount,
+ IReadOnlyList<SectionFragmentEvidence> RawFragments,
+ IReadOnlyList<string> Diagnostics,
+ double IntersectionMilliseconds,
+ double SplittingMilliseconds,
+ double GraphConstructionMilliseconds,
+ double LoopWalkingMilliseconds);
public sealed record SectionAnalysisResult(
SectionAnalysisMetadata Metadata,
SectionAnalysisSummary Summary,
IReadOnlyList<SectionLoop> Loops,
- IReadOnlyList<string> Notes);
+ IReadOnlyList<string> Notes,
+ SectionNormalizationDiagnostics? Normalization = null);
diff --git a/Aetheris.CLI/StepAnalyzer.cs b/Aetheris.CLI/StepAnalyzer.cs
index 821d634f..25a69d54 100644
--- a/Aetheris.CLI/StepAnalyzer.cs
+++ b/Aetheris.CLI/StepAnalyzer.cs
@@ -8,6 +8,7 @@ using Aetheris.Kernel.Core.Math;
using Aetheris.Kernel.Core.Numerics;
using Aetheris.Kernel.Core.Step242;
using Aetheris.Kernel.Core.Topology;
+using Aetheris.Kernel.Firmament.Materializer;
namespace Aetheris.CLI;
@@ -831,10 +832,31 @@ public sealed record VolumeAnalysisResult(
if (surface.Kind == SurfaceGeometryKind.Cylinder && surface.Cylinder is CylinderSurface cylinder)
{
rawSegments.AddRange(BuildCylinderFaceSectionSegments(body, face, cylinder, frame, epsilon, notes));
+ continue;
+ }
+
+ if (surface.Kind == SurfaceGeometryKind.Cone && surface.Cone is ConeSurface cone)
+ {
+ rawSegments.AddRange(BuildConeFaceSectionSegments(body, face, cone, frame, epsilon, notes));
+ continue;
}
+
+ notes.Add($"UnsupportedSectionCurve:face={face.Id.Value}:surface={surface.Kind}:plane={frame.FixedAxis}={offset:R}:bounded analytic intersection adapter is not implemented");
}
- var loops = BuildLoops(rawSegments, epsilon);
+ // Importer fragments are normalized by the shared analytic arrangement; do
+ // not reintroduce the former first-neighbour greedy chain walker here.
+ var arrangement = NormalizeSectionFragments(rawSegments, frame, offset, notes);
+ var loops = arrangement.Diagnostics.Count == 0
+ ? arrangement.ResultLoops.Select((loop, index) => new SectionLoop(index + 1, true, loop.SignedArea > 0d ? "ccw" : "cw", ComputeBoundingBox2D(loop.Fragments.SelectMany(x => x.Geometry switch
+ {
+ LineArcLineSegment2D l => new[] { new Point2D(l.Start.X, l.Start.Y), new Point2D(l.End.X, l.End.Y) },
+ LineArcCircularArc2D a => new[] { new Point2D(a.Center.X + a.Radius * Math.Cos(a.StartAngleRadians), a.Center.Y + a.Radius * Math.Sin(a.StartAngleRadians)), new Point2D(a.Center.X + a.Radius * Math.Cos(a.StartAngleRadians + a.SweepAngleRadians), a.Center.Y + a.Radius * Math.Sin(a.StartAngleRadians + a.SweepAngleRadians)) },
+ _ => [] }).ToArray()), loop.Fragments.Select(ToSectionSegment).ToArray(), loop.IsOuter ? "Outer" : "Inner"))
+ .Concat(rawSegments.Where(x => x.IsClosed).GroupBy(x => $"{x.Center!.U:R}:{x.Center.V:R}:{x.Radius:R}", StringComparer.Ordinal).Select((g, index) => FullCircleLoop(arrangement.ResultLoops.Count + index + 1, g.First()))).ToArray()
+ : Array.Empty<SectionLoop>();
+ notes.AddRange(arrangement.Diagnostics);
+ notes.Add($"section-normalization:raw={rawSegments.Count}:canonicalVertices={arrangement.IntersectionVertices.Count}:atomic={arrangement.AtomicFragments.Count}:collapsedDuplicates={arrangement.CoincidentFragmentCount}:loops={loops.Length}");
var metadata = new SectionAnalysisMetadata(
stepPath,
bbox,
@@ -846,7 +868,45 @@ public sealed record VolumeAnalysisResult(
frame.AxisV,
frame.MappingDescription);
var summary = BuildSectionSummary(loops);
- return new SectionAnalysisResult(metadata, summary, loops, notes);
+ var unaccounted = arrangement.Diagnostics.Where(x => x.StartsWith("OpenSection:unaccounted-atomic-fragments:", StringComparison.Ordinal)).Select(x => x.Split(':')).Select(x => x.Length > 2 && int.TryParse(x[2], out var n) ? n : 0).Sum();
+ var normalization = new SectionNormalizationDiagnostics(rawSegments.Count, arrangement.IntersectionVertices.Count, arrangement.AtomicFragments.Count,
+ arrangement.CoincidentFragmentCount, loops.Length, loops.Count(x => x.Role == "Outer"), loops.Count(x => x.Role == "Inner"), unaccounted, rawSegments.Select((x, i) => new SectionFragmentEvidence($"raw:{i}", x.SourceFace, x.SourceEntity ?? $"ADVANCED_FACE:{x.SourceFace}", x.SurfaceFamily ?? "Unknown", x.Kind.ToString(), x.Kind == RawSectionSegmentKind.Arc ? "AngularRadians" : "NormalizedLinear", 0d, x.Kind == RawSectionSegmentKind.Arc ? x.SweepRadians ?? 0d : 1d, x.Start, x.End, x.Center, x.Radius, x.MaterialSideEvidence ?? "unresolved")).ToArray(), arrangement.Diagnostics,
+ arrangement.IntersectionTime.TotalMilliseconds, arrangement.SplitTime.TotalMilliseconds,
+ arrangement.ClassificationTime.TotalMilliseconds, arrangement.ReconstructionTime.TotalMilliseconds);
+ return new SectionAnalysisResult(metadata, summary, loops, notes, normalization);
+ }
+
+ private static ProfileArrangement2D NormalizeSectionFragments(IReadOnlyList<RawSectionSegment> raw, SectionFrame frame, double offset, ICollection<string> notes)
+ {
+ var sources = new List<ArrangementSourceCurve2D>();
+ foreach (var (segment, index) in raw.Select((x, i) => (x, i)))
+ {
+ var provenance = new ProfileSegmentProvenance($"step-section:{frame.FixedAxis}:{offset:R}:{index}", segment.SourceEntity ?? $"face:{segment.SourceFace}", $"face:{segment.SourceFace}", $"STEP plane/surface intersection; {segment.MaterialSideEvidence ?? "material-side-unresolved"}", "XY");
+ var common = (StableId: $"step:{segment.SourceFace}:{index}", Provenance: provenance);
+ switch (segment.Kind)
+ {
+ case RawSectionSegmentKind.Line:
+ sources.Add(new(common.StableId, $"face:{segment.SourceFace}", PrismaticProfileIntent.Base, "STEP", "Boundary", $"segment:{index}", new LineArcLineSegment2D((segment.Start.U, segment.Start.V), (segment.End.U, segment.End.V)), common.Provenance));
+ break;
+ case RawSectionSegmentKind.Arc when segment.Center is not null && segment.Radius is not null && segment.SweepRadians is not null:
+ var start = Math.Atan2(segment.Start.V - segment.Center.V, segment.Start.U - segment.Center.U);
+ var sweep = string.Equals(segment.Direction, "cw", StringComparison.Ordinal) ? -Math.Abs(segment.SweepRadians.Value) : Math.Abs(segment.SweepRadians.Value);
+ // A full circle is already a closed analytic component. It is
+ // accounted for separately by the caller; adding a synthetic
+ // seam to the graph would turn a valid circle into a false
+ // high-valence coincidence with adjacent face partitions.
+ if (Math.Abs(sweep) >= 2d * Math.PI - 1e-9d)
+ {
+ notes.Add($"section-normalization:closed-full-circle:fragment={index}:face={segment.SourceFace}");
+ }
+ else sources.Add(new(common.StableId, $"face:{segment.SourceFace}", PrismaticProfileIntent.Base, "STEP", "Boundary", $"segment:{index}", new LineArcCircularArc2D((segment.Center.U, segment.Center.V), segment.Radius.Value, start, sweep), common.Provenance));
+ break;
+ default:
+ notes.Add($"UnsupportedSectionCurve:fragment={index}:face={segment.SourceFace}:family={segment.Kind}:reason={segment.UnsupportedReason ?? "missing analytic support"}");
+ break;
+ }
+ }
+ return ProfileArrangementBuilder.NormalizeBoundary("XY", sources, $"section:{frame.FixedAxis}={offset:R}");
}
public static OrthographicMapResult AnalyzeImportedBodyMap(BrepBody body, string stepPath, OrthographicView view, int rows, int cols)
@@ -1963,13 +2023,16 @@ public sealed record VolumeAnalysisResult(
.Select(point => (Point: point, T: (point - linePoint).Dot(lineDirection)))
.OrderBy(item => item.T)
.ToArray();
- if (ordered.Length != 2)
+ if (ordered.Length % 2 != 0)
{
- notes.Add($"Skipped planar face {face.Id.Value}: section clipping produced {ordered.Length} intersections (v1 supports 2-point clipping only).");
+ notes.Add($"OpenSection:planar-face-odd-intersection-count:face={face.Id.Value}:count={ordered.Length}");
return [];
}
- return [RawSectionSegment.Line(ProjectPoint(frame, ordered[0].Point), ProjectPoint(frame, ordered[1].Point))];
+ var outward = facePlane.Normal.ToVector();
+ var hasFaceBinding = body.Bindings.TryGetFaceBinding(face.Id, out var faceBinding);
+ if (hasFaceBinding && !faceBinding.SameSense) outward = -outward;
+ return Enumerable.Range(0, ordered.Length / 2).Select(i => OrientForMaterialLeft(RawSectionSegment.Line(ProjectPoint(frame, ordered[i * 2].Point), ProjectPoint(frame, ordered[i * 2 + 1].Point)) with { SourceFace = face.Id.Value, SurfaceFamily = "Plane", SourceEntity = $"ADVANCED_FACE:{face.Id.Value}", MaterialSideEvidence = $"faceSameSense={(hasFaceBinding ? faceBinding.SameSense : null)}" }, frame, outward)).ToArray();
}
private static IReadOnlyList<RawSectionSegment> BuildCylinderFaceSectionSegments(BrepBody body, Face face, CylinderSurface cylinder, SectionFrame frame, double epsilon, ICollection<string> notes)
@@ -2009,8 +2072,63 @@ public sealed record VolumeAnalysisResult(
var axisOriginCoord = (cylinder.Origin - Point3D.Origin).Dot(frame.Normal);
var center3D = cylinder.Origin + (cylinder.Axis.ToVector() * (frame.Offset - axisOriginCoord));
var center = ProjectPoint(frame, center3D);
- var start = new Point2D(center.U + cylinder.Radius, center.V);
- return [RawSectionSegment.Arc(start, start, center, cylinder.Radius, "ccw", 2d * double.Pi)];
+ // A cylindrical B-rep face may be angularly trimmed by vertical seam edges.
+ // The old extractor emitted its entire support circle for every such face,
+ // leaving the planar-outline fragments dangling. Preserve the bounded trim.
+ var angles = body.GetEdges(face.Id).SelectMany(edge => IntersectEdgeWithSectionPlane(body, edge, frame, epsilon)).Select(p => ProjectPoint(frame, p)).Where(p => Math.Abs(Math.Sqrt((p.U-center.U)*(p.U-center.U)+(p.V-center.V)*(p.V-center.V))-cylinder.Radius) <= epsilon * 32d).Select(p => Math.Atan2(p.V-center.V,p.U-center.U)).Order().Aggregate(new List<double>(), (a,x) => { if(a.Count==0 || Math.Abs(a[^1]-x)>1e-7d) a.Add(x); return a; });
+ if (angles.Count == 2)
+ {
+ var sweep = angles[1] - angles[0];
+ if (sweep > Math.PI) { (angles[0], angles[1]) = (angles[1], angles[0]); sweep = 2d * Math.PI - sweep; }
+ var start = new Point2D(center.U + cylinder.Radius * Math.Cos(angles[0]), center.V + cylinder.Radius * Math.Sin(angles[0]));
+ var end = new Point2D(center.U + cylinder.Radius * Math.Cos(angles[0] + sweep), center.V + cylinder.Radius * Math.Sin(angles[0] + sweep));
+ var sameSense = body.Bindings.TryGetFaceBinding(face.Id, out var binding) && binding.SameSense;
+ notes.Add($"section-fragment:cylinder:face={face.Id.Value}:sameSense={sameSense}:center=({center.U:R},{center.V:R}):radius={cylinder.Radius:R}:angles=({angles[0]:R},{angles[1]:R}):sweep={sweep:R}:start=({start.U:R},{start.V:R}):end=({end.U:R},{end.V:R})");
+ var midAngle = angles[0] + sweep * .5d;
+ var radial = (center3D - cylinder.Origin) + (frame.UAxis * (cylinder.Radius * Math.Cos(midAngle))) + (frame.VAxis * (cylinder.Radius * Math.Sin(midAngle)));
+ var hasCylinderBinding = body.Bindings.TryGetFaceBinding(face.Id, out var cylinderBinding);
+ if (hasCylinderBinding && !cylinderBinding.SameSense) radial = -radial;
+ return [OrientForMaterialLeft(RawSectionSegment.Arc(start, end, center, cylinder.Radius, "ccw", sweep) with { SourceFace = face.Id.Value, SurfaceFamily = "Cylinder", SourceEntity = $"ADVANCED_FACE:{face.Id.Value}", MaterialSideEvidence = $"faceSameSense={(hasCylinderBinding ? cylinderBinding.SameSense : null)}" }, frame, radial)];
+ }
+ if (angles.Count > 2) notes.Add($"UnsupportedSectionCurve:cylinder-trim-ambiguous:face={face.Id.Value}:angularVertices={angles.Count}");
+ var fullStart = new Point2D(center.U + cylinder.Radius, center.V);
+ return [RawSectionSegment.Arc(fullStart, fullStart, center, cylinder.Radius, "ccw", 2d * double.Pi) with { SourceFace = face.Id.Value, SurfaceFamily = "Cylinder", SourceEntity = $"ADVANCED_FACE:{face.Id.Value}", MaterialSideEvidence = "full-circle:face-boundary" }];
+ }
+
+ private static IReadOnlyList<RawSectionSegment> BuildConeFaceSectionSegments(BrepBody body, Face face, ConeSurface cone, SectionFrame frame, double epsilon, ICollection<string> notes)
+ {
+ var axisDot = Math.Abs(cone.Axis.ToVector().Dot(frame.Normal));
+ if (axisDot < 1d - epsilon * 8d) { notes.Add($"UnsupportedSectionCurve:face={face.Id.Value}:surface=Cone:plane-not-normal-to-axis"); return []; }
+ var v = (frame.Offset - (cone.Apex - Point3D.Origin).Dot(frame.Normal)) / (cone.Axis.ToVector().Dot(frame.Normal));
+ var radius = Math.Abs(v * Math.Tan(cone.SemiAngleRadians));
+ if (radius <= epsilon) { notes.Add($"DegenerateLoop:cone-apex-section:face={face.Id.Value}"); return []; }
+ var center3D = cone.Apex + cone.Axis.ToVector() * v;
+ var center = ProjectPoint(frame, center3D);
+ var edgeHits = body.GetEdges(face.Id).SelectMany(edge => IntersectEdgeWithSectionPlane(body, edge, frame, epsilon)).Select(p => ProjectPoint(frame, p)).Where(p => Math.Abs(Math.Sqrt((p.U-center.U)*(p.U-center.U)+(p.V-center.V)*(p.V-center.V))-radius) <= epsilon * 32d).ToArray();
+ var angles = edgeHits.Select(p => Math.Atan2(p.V-center.V,p.U-center.U)).Order().Aggregate(new List<double>(), (a,x) => { if(a.Count==0 || Math.Abs(a[^1]-x)>1e-7d) a.Add(x); return a; });
+ if (angles.Count == 2)
+ {
+ var sweep = angles[1]-angles[0]; if (sweep > Math.PI) { (angles[0],angles[1])=(angles[1],angles[0]); sweep=2*Math.PI-sweep; }
+ var start = new Point2D(center.U+radius*Math.Cos(angles[0]),center.V+radius*Math.Sin(angles[0]));
+ var end = new Point2D(center.U+radius*Math.Cos(angles[0]+sweep),center.V+radius*Math.Sin(angles[0]+sweep));
+ notes.Add($"section-fragment:cone:face={face.Id.Value}:center=({center.U:R},{center.V:R}):radius={radius:R}:sweep={sweep:R}");
+ return [RawSectionSegment.Arc(start,end,center,radius,"ccw",sweep) with { SourceFace=face.Id.Value, SurfaceFamily="Cone" }];
+ }
+ if (angles.Count > 2) { notes.Add($"UnsupportedSectionCurve:cone-trim-ambiguous:face={face.Id.Value}:angularVertices={angles.Count}"); return []; }
+ var fullStart = new Point2D(center.U+radius,center.V);
+ return [RawSectionSegment.Arc(fullStart,fullStart,center,radius,"ccw",2*Math.PI) with { SourceFace=face.Id.Value, SurfaceFamily="Cone" }];
+ }
+
+ private static RawSectionSegment OrientForMaterialLeft(RawSectionSegment segment, SectionFrame frame, Vector3D outwardNormal)
+ {
+ // For a section plane with normal N, T = N x outward has solid material
+ // on its left (the left in-plane normal is -outward's in-plane component).
+ var desired = frame.Normal.Cross(outwardNormal);
+ var du = desired.Dot(frame.UAxis); var dv = desired.Dot(frame.VAxis);
+ var tangent = segment.Kind == RawSectionSegmentKind.Arc && segment.Center is not null && segment.Radius is not null && segment.SweepRadians is not null
+ ? new Point2D(-Math.Sin(Math.Atan2(segment.Start.V-segment.Center.V, segment.Start.U-segment.Center.U) + segment.SweepRadians.Value*.5d) * Math.Sign(segment.SweepRadians.Value), Math.Cos(Math.Atan2(segment.Start.V-segment.Center.V, segment.Start.U-segment.Center.U) + segment.SweepRadians.Value*.5d) * Math.Sign(segment.SweepRadians.Value))
+ : new Point2D(segment.End.U-segment.Start.U, segment.End.V-segment.Start.V);
+ return tangent.U * du + tangent.V * dv < 0d ? segment.Reversed() : segment;
}
private static IReadOnlyList<Point3D> IntersectEdgeWithSectionPlane(BrepBody body, EdgeId edgeId, SectionFrame frame, double epsilon)
@@ -2069,45 +2187,6 @@ public sealed record VolumeAnalysisResult(
return [circle.Evaluate(trim.Start), circle.Evaluate(trim.End)];
}
- private static List<SectionLoop> BuildLoops(IReadOnlyList<RawSectionSegment> rawSegments, double epsilon)
- {
- var unused = rawSegments.ToList();
- var loops = new List<SectionLoop>();
- var nextId = 1;
- while (unused.Count > 0)
- {
- var chain = new List<RawSectionSegment>();
- var first = unused[0];
- unused.RemoveAt(0);
- chain.Add(first);
- var cursor = first.End;
-
- while (!first.IsClosed && !PointsClose(cursor, first.Start, epsilon))
- {
- var index = FindConnectingSegment(unused, cursor, epsilon, out var reverse);
- if (index < 0)
- {
- break;
- }
-
- var segment = unused[index];
- unused.RemoveAt(index);
- if (reverse)
- {
- segment = segment.Reversed();
- }
-
- chain.Add(segment);
- cursor = segment.End;
- }
-
- var closed = first.IsClosed || PointsClose(chain[0].Start, chain[^1].End, epsilon);
- loops.Add(new SectionLoop(nextId++, closed, closed ? ComputeWinding(chain) : null, ComputeBoundingBox2D(chain.SelectMany(segment => segment.Points()).ToArray()), chain.Select(ToSectionSegment).ToArray()));
- }
-
- return loops.OrderByDescending(loop => loop.BoundingBox2D is null ? 0d : Area(loop.BoundingBox2D)).ToList();
- }
-
private static SectionAnalysisSummary BuildSectionSummary(IReadOnlyList<SectionLoop> loops)
{
var segments = loops.SelectMany(loop => loop.Segments).ToArray();
@@ -2134,61 +2213,24 @@ public sealed record VolumeAnalysisResult(
private static SectionSegment ToSectionSegment(RawSectionSegment raw) =>
raw.Kind switch
{
- RawSectionSegmentKind.Line => new SectionSegment("line", raw.Start, raw.End, null, null, null, null, null),
- RawSectionSegmentKind.Arc => new SectionSegment("arc", raw.Start, raw.End, raw.Center, raw.Radius, raw.Direction, raw.SweepRadians, null),
- _ => new SectionSegment("unsupported", raw.Start, raw.End, null, null, null, null, raw.UnsupportedReason ?? "unsupported")
+ RawSectionSegmentKind.Line => new SectionSegment("line", raw.Start, raw.End, null, null, null, null, null, raw.SourceFace, raw.SourceEntity, raw.SurfaceFamily, "NormalizedLinear", 0d, 1d, raw.MaterialSideEvidence),
+ RawSectionSegmentKind.Arc => new SectionSegment("arc", raw.Start, raw.End, raw.Center, raw.Radius, raw.Direction, raw.SweepRadians, null, raw.SourceFace, raw.SourceEntity, raw.SurfaceFamily, "AngularRadians", 0d, raw.SweepRadians, raw.MaterialSideEvidence),
+ _ => new SectionSegment("unsupported", raw.Start, raw.End, null, null, null, null, raw.UnsupportedReason ?? "unsupported", raw.SourceFace, raw.SourceEntity, raw.SurfaceFamily, null, null, null, raw.MaterialSideEvidence)
};
- private static int FindConnectingSegment(IReadOnlyList<RawSectionSegment> segments, Point2D cursor, double epsilon, out bool reverse)
- {
- for (var i = 0; i < segments.Count; i++)
- {
- if (PointsClose(segments[i].Start, cursor, epsilon))
- {
- reverse = false;
- return i;
- }
-
- if (PointsClose(segments[i].End, cursor, epsilon))
- {
- reverse = true;
- return i;
- }
- }
-
- reverse = false;
- return -1;
- }
-
- private static bool PointsClose(Point2D a, Point2D b, double epsilon)
+ private static SectionSegment ToSectionSegment(ArrangementFragment2D fragment) => fragment.Geometry switch
{
- var du = a.U - b.U;
- var dv = a.V - b.V;
- return (du * du) + (dv * dv) <= (epsilon * epsilon * 16d);
- }
+ LineArcLineSegment2D line => new("line", new(line.Start.X, line.Start.Y), new(line.End.X, line.End.Y), null, null, null, null, null),
+ LineArcCircularArc2D arc => new("arc", new(arc.Center.X + arc.Radius * Math.Cos(arc.StartAngleRadians), arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngleRadians)), new(arc.Center.X + arc.Radius * Math.Cos(arc.StartAngleRadians + arc.SweepAngleRadians), arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngleRadians + arc.SweepAngleRadians)), new(arc.Center.X, arc.Center.Y), arc.Radius, arc.SweepAngleRadians >= 0d ? "ccw" : "cw", arc.SweepAngleRadians, null),
+ _ => new("unsupported", new(0, 0), new(0, 0), null, null, null, null, "UnsupportedSectionCurve")
+ };
- private static string? ComputeWinding(IReadOnlyList<RawSectionSegment> segments)
+ private static SectionLoop FullCircleLoop(int id, RawSectionSegment segment)
{
- var points = segments.Select(segment => segment.Start).ToArray();
- if (points.Length < 3)
- {
- return null;
- }
-
- var signedArea2 = 0d;
- for (var i = 0; i < points.Length; i++)
- {
- var a = points[i];
- var b = points[(i + 1) % points.Length];
- signedArea2 += (a.U * b.V) - (b.U * a.V);
- }
-
- if (double.Abs(signedArea2) <= 1e-12d)
- {
- return null;
- }
-
- return signedArea2 > 0d ? "ccw" : "cw";
+ var center = segment.Center ?? throw new InvalidOperationException("Full circle is missing a center.");
+ var radius = segment.Radius ?? throw new InvalidOperationException("Full circle is missing a radius.");
+ var role = segment.MaterialSideEvidence?.Contains("False", StringComparison.Ordinal) == true ? "Inner" : "Outer";
+ return new(id, true, "ccw", new BoundingBox2D(new(center.U - radius, center.V - radius), new(center.U + radius, center.V + radius)), [ToSectionSegment(segment)], role);
}
private static BoundingBox2D? ComputeBoundingBox2D(IReadOnlyList<Point2D> points)
@@ -2852,7 +2894,11 @@ public sealed record VolumeAnalysisResult(
double? Radius,
string? Direction,
double? SweepRadians,
- string? UnsupportedReason)
+ string? UnsupportedReason,
+ int SourceFace = -1,
+ string? SurfaceFamily = null,
+ string? SourceEntity = null,
+ string? MaterialSideEvidence = null)
{
public bool IsClosed =>
Kind == RawSectionSegmentKind.Arc
diff --git a/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs b/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs
index de007fb3..4378e46a 100644
--- a/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs
+++ b/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs
@@ -22,9 +22,12 @@ public sealed record BrepMassPropertiesOptions(
double AngularToleranceRadians,
double ConvergenceTolerance,
int MinimumSegments = 12,
- int MaximumSegments = 512)
+ int MaximumSegments = 16)
{
- public static BrepMassPropertiesOptions Default { get; } = new(1e-4d, double.Pi / 48d, 1e-5d);
+ // M8 is a bounded independent estimate, not the primary mass analyzer. Keep
+ // its mesh deliberately coarse enough for interactive verification and make
+ // the resulting conservative bound explicit to callers.
+ public static BrepMassPropertiesOptions Default { get; } = new(0.1d, double.Pi / 12d, 1d, MaximumSegments: 16);
}
public sealed record BrepMassPropertiesFaceContribution(
diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs
index 91ee07b4..4ee9748e 100644
--- a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs
@@ -28,7 +28,8 @@ 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);
+ PrismaticProfileCompositionFeature? Feature, IReadOnlyDictionary<string, ResolvedProfile2D> Profiles, IReadOnlyList<string> Diagnostics,
+ StaticGeometryExpansionEvidence? Expansion = null);
/// <summary>
/// Bounded parser for the composition source form. It intentionally reuses the
@@ -50,6 +51,9 @@ public static class PrismaticProfileCompositionParser
public static PrismaticProfileCompositionParseResult Parse(string source)
{
+ var expansion = StaticGeometryExpansion.Expand(source);
+ if (expansion.Diagnostics.Count > 0) return new(null, new Dictionary<string, ResolvedProfile2D>(), expansion.Diagnostics, expansion.Evidence);
+ source = expansion.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))
@@ -137,7 +141,7 @@ public static class PrismaticProfileCompositionParser
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", placement, operations, levels, "parser-backed-scaffold-profile-composition") : null;
- return new(feature, profiles, diagnostics.Distinct().ToArray());
+ return new(feature, profiles, diagnostics.Distinct().ToArray(), expansion.Evidence);
}
private static double N(Match match, string name) => double.Parse(match.Groups[name].Value, CultureInfo.InvariantCulture);
diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs
index 8cc5b995..34d453d5 100644
--- a/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs
@@ -36,6 +36,10 @@ public sealed record ProfileArrangementResult(
public static class ProfileArrangementBuilder
{
private const double Tol = 1e-7;
+ // Imported STEP trimming commonly carries a few microns of endpoint residual;
+ // support geometry remains unmodified while graph vertices use this explicit
+ // topology bucket. Profile intersections still use the stricter analytic Tol.
+ private const double VertexTol = 1e-5;
private const double SideSample = 1e-5;
public static ProfileArrangementResult Compose(
@@ -73,6 +77,71 @@ public static class ProfileArrangementBuilder
return PointInLoop(loop.Segments.Select(x => x.Geometry).ToArray(), point);
}
+ /// <summary>
+ /// Normalizes an unoriented analytic boundary supplied by an importer. This is the
+ /// section counterpart of <see cref="Compose"/>: it reuses the same bounded
+ /// line/arc intersection and parameter-splitting rules, but deliberately does
+ /// not invent a material side. Callers must classify winding/nesting afterwards.
+ /// A rejected graph never returns provisional loops.
+ /// </summary>
+ public static ProfileArrangement2D NormalizeBoundary(string frame, IReadOnlyList<ArrangementSourceCurve2D> sources, 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 hits = Intersections(sources[i].Geometry, sources[j].Geometry, out var coincident, out _);
+ if (coincident)
+ {
+ foreach (var p in new[] { Ends(sources[i].Geometry).Start, Ends(sources[i].Geometry).End }) if (OnCurve(sources[j].Geometry, p, out var t)) { parameters[sources[j].StableId].Add(t); vertices.Add(p); }
+ foreach (var p in new[] { Ends(sources[j].Geometry).Start, Ends(sources[j].Geometry).End }) if (OnCurve(sources[i].Geometry, p, out var t)) { parameters[sources[i].StableId].Add(t); vertices.Add(p); }
+ }
+ foreach (var p in hits)
+ if (OnCurve(sources[i].Geometry, p, out var a) && OnCurve(sources[j].Geometry, p, out var b)) { parameters[sources[i].StableId].Add(a); parameters[sources[j].StableId].Add(b); vertices.Add(p); }
+ }
+ intersectionClock.Stop();
+ var splitClock = Stopwatch.StartNew();
+ var atomic = new List<ArrangementFragment2D>();
+ foreach (var source in sources.OrderBy(x => x.StableId, StringComparer.Ordinal))
+ {
+ if (source.Geometry is LineArcFullCircle2D)
+ {
+ diagnostics.Add($"UnsupportedSectionCurve:full-circle-source-must-be-adapted:{source.StableId}:context={context}");
+ continue;
+ }
+ var ordered = parameters[source.StableId].Order().Aggregate(new List<double>(), (a, x) => { if (a.Count == 0 || Math.Abs(a[^1] - x) > Tol) a.Add(Math.Clamp(x, 0d, 1d)); return a; });
+ for (var i = 0; i < ordered.Count - 1; i++)
+ {
+ if (ordered[i + 1] - ordered[i] <= Tol) { diagnostics.Add($"DegenerateLoop:zero-length-parameter:{source.StableId}:context={context}"); continue; }
+ atomic.Add(new($"{source.StableId}.part{i}", source, ordered[i], ordered[i + 1], Trim(source.Geometry, ordered[i], ordered[i + 1]), false, true));
+ }
+ }
+ splitClock.Stop();
+ // Coincident source ownership is retained in source provenance but one geometric atom is sufficient for topology.
+ var retained = new List<ArrangementFragment2D>();
+ foreach (var group in atomic.GroupBy(x => UndirectedGeometryKey(x.Geometry), StringComparer.Ordinal).OrderBy(x => x.Key, StringComparer.Ordinal))
+ {
+ var ordered = group.OrderBy(x => x.StableId, StringComparer.Ordinal).ToArray();
+ // Imported section sources are directed material-left. Coincident atoms
+ // with opposite direction therefore disagree about material ownership.
+ if (ordered.Skip(1).Any(x => !SameDirection(ordered[0].Geometry, x.Geometry)) )
+ diagnostics.Add($"DuplicateCoincidentFragmentConflict:fragments={string.Join(',', ordered.Select(x => x.StableId))}:context={context}");
+ retained.Add(ordered[0]);
+ }
+ var collapsed = atomic.Count - retained.Count;
+ var graphClock = Stopwatch.StartNew();
+ var incident = retained.SelectMany(x => new[] { (Key: VertexKey(Ends(x.Geometry).Start), Fragment: x), (Key: VertexKey(Ends(x.Geometry).End), Fragment: x) })
+ .GroupBy(x => x.Key, StringComparer.Ordinal).ToDictionary(x => x.Key, x => x.Select(y => y.Fragment).DistinctBy(y => y.StableId).OrderBy(y => y.StableId, StringComparer.Ordinal).ToArray(), StringComparer.Ordinal);
+ ValidateBoundaryVertexIncidence(retained, diagnostics, context);
+ graphClock.Stop();
+ var walkClock = Stopwatch.StartNew();
+ var loops = diagnostics.Any(x => x.StartsWith("DuplicateCoincidentFragmentConflict", StringComparison.Ordinal)) ? [] : Reconstruct(retained, diagnostics, context).ToList();
+ walkClock.Stop();
+ return new(frame, sources, vertices.Concat(retained.SelectMany(x => new[] { Ends(x.Geometry).Start, Ends(x.Geometry).End })).DistinctBy(VertexKey).OrderBy(VertexKey).Select((p,i) => new ArrangementVertex2D($"vertex:{i}",p)).ToArray(), atomic, loops, collapsed, diagnostics.Distinct().Order().ToArray(), intersectionClock.Elapsed, splitClock.Elapsed, graphClock.Elapsed, walkClock.Elapsed);
+ }
+
private static ProfileArrangementResult Empty(string frame, string context) =>
new(new(frame, [], [], [], [], 0, [], TimeSpan.Zero, TimeSpan.Zero, TimeSpan.Zero, TimeSpan.Zero), null);
@@ -445,7 +514,29 @@ public static class ProfileArrangementBuilder
_ => 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 string UndirectedGeometryKey(LineArcProfileCurve2D curve)
+ {
+ var (a, b) = Ends(curve); var ka = VertexKey(a); var kb = VertexKey(b);
+ if (string.CompareOrdinal(ka, kb) > 0) (ka, kb) = (kb, ka);
+ return curve switch
+ {
+ LineArcLineSegment2D => $"L:{ka}:{kb}",
+ LineArcCircularArc2D arc => $"A:{VertexKey(arc.Center)}:{Math.Round(arc.Radius / Tol):F0}:{ka}:{kb}",
+ _ => throw new NotSupportedException()
+ };
+ }
+ private static bool SameDirection(LineArcProfileCurve2D a, LineArcProfileCurve2D b)
+ {
+ var (as_, ae) = Ends(a); var (bs, be) = Ends(b);
+ return VertexKey(as_) == VertexKey(bs) && VertexKey(ae) == VertexKey(be)
+ && (a, b) switch
+ {
+ (LineArcLineSegment2D, LineArcLineSegment2D) => true,
+ (LineArcCircularArc2D aa, LineArcCircularArc2D bb) => Math.Sign(aa.SweepAngleRadians) == Math.Sign(bb.SweepAngleRadians),
+ _ => false
+ };
+ }
+ private static string VertexKey((double X, double Y) p) => $"{Math.Round(p.X / VertexTol):F0},{Math.Round(p.Y / VertexTol):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));
}
diff --git a/Aetheris.Kernel.Firmament/Materializer/StaticGeometryExpansion.cs b/Aetheris.Kernel.Firmament/Materializer/StaticGeometryExpansion.cs
new file mode 100644
index 00000000..cc497102
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Materializer/StaticGeometryExpansion.cs
@@ -0,0 +1,112 @@
+using System.Globalization;
+using System.Text;
+using System.Text.RegularExpressions;
+
+namespace Aetheris.Kernel.Firmament.Materializer;
+
+/// <summary>
+/// The intentionally small data/template front end for scaffold-backed profile
+/// composition. It is a compiler convenience only: its output is ordinary
+/// Point2/Circle2/Line2/Profile/Compose source consumed by the existing route.
+/// </summary>
+public sealed record StaticGeometryExpansionEvidence(
+ IReadOnlyList<string> Records, IReadOnlyList<string> GeneratedProfiles,
+ IReadOnlyList<string> GeneratedMembers, IReadOnlyList<string> GeneratedOperations,
+ string Template, string Group);
+
+internal static class StaticGeometryExpansion
+{
+ private const string RecordName = "LobeSpec";
+ private static readonly string[] Required = ["Key", "Path", "InnerCenter", "OuterCenter", "Radius", "InnerStart", "InnerEnd", "OuterStart", "OuterEnd", "Sweep", "Role"];
+ private static readonly Regex RecordHeader = new(@"\bRecord\s+LobeSpec\s*\{", RegexOptions.CultureInvariant);
+ private static readonly Regex ArrayHeader = new(@"\bLet\s+Lobes\s*:\s*LobeSpec\[\]\s*=\s*\[", RegexOptions.CultureInvariant);
+ private static readonly Regex TemplateHeader = new(@"\bTemplate\s+RoundedLobe\s*<\s*Spec\s*:\s*LobeSpec\s*>", RegexOptions.CultureInvariant);
+ private static readonly Regex ExpandHeader = new(@"\bExpand\s+Lobes\s+With\s+RoundedLobe\b", RegexOptions.CultureInvariant);
+ private static readonly Regex Point = new(@"^\[\s*(?<x>[-+.\d]+)mm\s*,\s*(?<y>[-+.\d]+)mm\s*\]$", RegexOptions.CultureInvariant);
+
+ public static (string Source, StaticGeometryExpansionEvidence? Evidence, IReadOnlyList<string> Diagnostics) Expand(string source)
+ {
+ if (!source.Contains("LobeSpec", StringComparison.Ordinal)) return (source, null, []);
+ var d = new List<string>();
+ if (!RecordHeader.IsMatch(source)) d.Add("static-record-missing:LobeSpec");
+ if (!TemplateHeader.IsMatch(source)) d.Add("static-template-argument-type-mismatch:RoundedLobe");
+ if (!ExpandHeader.IsMatch(source)) d.Add("static-expansion-source-missing:Expand Lobes With RoundedLobe");
+ var array = ArrayHeader.Match(source);
+ if (!array.Success) d.Add("static-array-missing-or-non-static:Lobes");
+ if (d.Count > 0) return (source, null, d);
+ var close = Matching(source, source.IndexOf('[', array.Index + array.Length - 1));
+ if (close < 0) return (source, null, ["static-array-unclosed:Lobes"]);
+ var rows = Regex.Matches(source[(array.Index + array.Length)..close], @"\bLobeSpec\s*\{(?<body>[\s\S]*?)\}", RegexOptions.CultureInvariant).Cast<Match>().ToArray();
+ if (rows.Length == 0 || rows.Length > 1024) return (source, null, ["static-array-empty-or-unbounded:Lobes"]);
+ var specs = new List<Spec>(); var keys = new HashSet<string>(StringComparer.Ordinal);
+ foreach (var row in rows)
+ {
+ var fields = Fields(row.Groups["body"].Value);
+ foreach (var required in Required) if (!fields.ContainsKey(required)) d.Add($"static-record-missing-field:LobeSpec.{required}");
+ if (d.Count > 0) continue;
+ var key = fields["Key"];
+ if (!Regex.IsMatch(key, "^[A-Za-z_][A-Za-z0-9_]*$", RegexOptions.CultureInvariant) || !keys.Add(key)) { d.Add($"static-record-duplicate-key:LobeSpec.{key}"); continue; }
+ if (!TryPoint(fields["InnerCenter"], out var inner) || !TryPoint(fields["OuterCenter"], out var outer) || !TryPoint(fields["InnerStart"], out var innerStart) || !TryPoint(fields["InnerEnd"], out var innerEnd) || !TryPoint(fields["OuterStart"], out var outerStart) || !TryPoint(fields["OuterEnd"], out var outerEnd) || !TryPath(fields["Path"], out var path) || path.Count != 6 || !TryLength(fields["Radius"], out var radius) || radius <= 0 || fields["Sweep"] is not ("Clockwise" or "CounterClockwise")) { d.Add($"static-record-field-type-mismatch:LobeSpec.{key}"); continue; }
+ specs.Add(new(key, path, inner, outer, radius, innerStart, innerEnd, outerStart, outerEnd, fields["Sweep"], fields["Role"]));
+ }
+ if (d.Count > 0) return (source, null, d.Distinct().ToArray());
+ var generated = Generate(source, specs);
+ var evidence = new StaticGeometryExpansionEvidence(specs.Select(s => $"record:Lobes[{s.Key}]").ToArray(), specs.Select(s => $"profile:Lobes[{s.Key}].Shape").ToArray(), specs.SelectMany(s => new[] { $"template:RoundedLobe[{s.Key}].Layout.InnerArcGuide", $"template:RoundedLobe[{s.Key}].Layout.OuterArcGuide" }).ToArray(), specs.Select(s => $"compose:Ctc01.Lobes[{s.Key}]").ToArray(), "RoundedLobe", "Lobes");
+ return (generated, evidence, []);
+ }
+
+ private static string Generate(string source, IReadOnlyList<Spec> specs)
+ {
+ var scaffold = new StringBuilder("Concept Struct Ctc01BlockoutScaffold On XY {\n Rect2 PrimaryWebGuide { Center: [0mm, 0mm]; Size: [800mm, 250mm]; Role: ProfileGuide }\n Rect2 MidLevelGuide { Center: [0mm, 0mm]; Size: [500mm, 300mm]; Role: ProfileGuide }\n");
+ var profiles = new StringBuilder();
+ foreach (var s in specs)
+ {
+ for (var i = 0; i < 6; i++) scaffold.Append($" Point2 {s.Key}P{i} {{ Position: {P(s.Path[i])} }}\n");
+ scaffold.Append($" Point2 {s.Key}InnerCenter {{ Position: {P(s.InnerCenter)} }}\n Point2 {s.Key}OuterCenter {{ Position: {P(s.OuterCenter)} }}\n Circle2 {s.Key}InnerArcGuide {{ Center: {s.Key}InnerCenter; Radius: {s.Radius:R}mm }}\n Circle2 {s.Key}OuterArcGuide {{ Center: {s.Key}OuterCenter; Radius: {s.Radius:R}mm }}\n");
+ for (var i = 0; i < 6; i++) if (!Arc(s.Path[i], s.Path[(i + 1) % 6], s.InnerStart, s.InnerEnd) && !Arc(s.Path[i], s.Path[(i + 1) % 6], s.OuterStart, s.OuterEnd)) scaffold.Append($" Line2 {s.Key}Line{i} {{ From: {s.Key}P{i}; To: {s.Key}P{(i + 1) % 6} }}\n");
+ profiles.Append($"Profile {s.Key}Ear Using Ctc01BlockoutScaffold {{ Loop Outer {{\n");
+ for (var i = 0; i < 6; i++) { var a = s.Path[i]; var b = s.Path[(i + 1) % 6]; var inner = Arc(a,b,s.InnerStart,s.InnerEnd); var outer = Arc(a,b,s.OuterStart,s.OuterEnd); var label = inner ? "InnerArc" : outer ? "OuterArc" : $"Line{i}"; var trace = inner ? $"{s.Key}InnerArcGuide" : outer ? $"{s.Key}OuterArcGuide" : $"{s.Key}Line{i}"; profiles.Append($" Segment {label} {{ Trace: {trace}; From: {s.Key}P{i}; To: {s.Key}P{(i + 1) % 6}" + ((inner || outer) ? $"; Sweep: {s.Sweep}" : "") + " }\n"); }
+ profiles.Append("} }\n");
+ }
+ scaffold.Append("}\n");
+ // Keep the non-repetitive primary/mid/hex declarations authored in the source.
+ var suffixStart = source.IndexOf("// X3 static expansion keeps", StringComparison.Ordinal);
+ var suffix = suffixStart >= 0 ? source[suffixStart..] : string.Empty;
+ var result = scaffold + profiles.ToString() + suffix;
+ // A group is source-only. Its members retain the data key in the lowered
+ // operation name, so the section compiler still sees individual Adds.
+ var group = Regex.Match(result, @"\bAdd\s+Lobes\s*\{\s*Profiles\s*:\s*\[(?<profiles>[\w\s,]+)\]\s*;?\s*From\s*:\s*(?<from>[-+.\d]+)mm\s*;?\s*To\s*:\s*(?<to>[-+.\d]+)mm\s*;?\s*Role\s*:\s*(?<role>\w+)\s*\}", RegexOptions.Singleline | RegexOptions.CultureInvariant);
+ if (group.Success)
+ {
+ var adds = string.Join("\n", group.Groups["profiles"].Value.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries).Select(profile =>
+ {
+ var key = profile.EndsWith("Ear", StringComparison.Ordinal) ? profile[..^3] : profile;
+ return $"Add {key}Lobe {{ Profile: {profile}; From: {group.Groups["from"].Value}mm; To: {group.Groups["to"].Value}mm; Role: {group.Groups["role"].Value} }}";
+ }));
+ result = result.Remove(group.Index, group.Length).Insert(group.Index, adds);
+ }
+ return result;
+ }
+ private static bool Arc((double X,double Y) a, (double X,double Y) b, (double X,double Y) x, (double X,double Y) y) => Same(a,x) && Same(b,y);
+ private static bool Same((double X,double Y) a, (double X,double Y) b) => Math.Abs(a.X-b.X)<1e-9 && Math.Abs(a.Y-b.Y)<1e-9;
+ private static string P((double X,double Y) p) => $"[{p.X:R}mm, {p.Y:R}mm]";
+ private static Dictionary<string,string> Fields(string body)
+ {
+ var result = new Dictionary<string, string>(StringComparer.Ordinal); var start = 0; var depth = 0;
+ for (var i = 0; i <= body.Length; i++)
+ {
+ if (i < body.Length && body[i] == '[') depth++;
+ else if (i < body.Length && body[i] == ']') depth--;
+ if (i != body.Length && (body[i] != ';' || depth != 0)) continue;
+ var part = body[start..i].Trim(); start = i + 1;
+ var colon = part.IndexOf(':'); if (colon <= 0) continue;
+ result[part[..colon].Trim()] = part[(colon + 1)..].Trim();
+ }
+ return result;
+ }
+ private static bool TryLength(string s,out double v) => double.TryParse(s.Replace("mm", "", StringComparison.Ordinal).Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out v) && s.Contains("mm", StringComparison.Ordinal);
+ private static bool TryPoint(string s,out (double X,double Y) p) { var m=Point.Match(s); p=m.Success?(double.Parse(m.Groups["x"].Value,CultureInfo.InvariantCulture),double.Parse(m.Groups["y"].Value,CultureInfo.InvariantCulture)):default; return m.Success; }
+ private static bool TryPath(string s,out List<(double X,double Y)> p) { p=[]; foreach(Match m in Regex.Matches(s,@"\[\s*(?<x>[-+.\d]+)mm\s*,\s*(?<y>[-+.\d]+)mm\s*\]",RegexOptions.CultureInvariant))p.Add((double.Parse(m.Groups["x"].Value,CultureInfo.InvariantCulture),double.Parse(m.Groups["y"].Value,CultureInfo.InvariantCulture))); return p.Count>0; }
+ private static int Matching(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 i;} return -1; }
+ private sealed record Spec(string Key,List<(double X,double Y)> Path,(double X,double Y) InnerCenter,(double X,double Y) OuterCenter,double Radius,(double X,double Y) InnerStart,(double X,double Y) InnerEnd,(double X,double Y) OuterStart,(double X,double Y) OuterEnd,string Sweep,string Role);
+}
diff --git a/docs/firmament/data-driven-geometry-x1.md b/docs/firmament/data-driven-geometry-x1.md
new file mode 100644
index 00000000..498017cb
--- /dev/null
+++ b/docs/firmament/data-driven-geometry-x1.md
@@ -0,0 +1,23 @@
+# Data-driven geometry X1
+
+> A reconstruction model may be a typed database compiled into geometry.
+
+> Compress repetition in source, not evidence in the compiler.
+
+X1 adds a deliberately bounded front end for scaffold-backed prismatic Profiles:
+
+```firmament
+Record LobeSpec { Key: Symbol; Path: Point2[]; InnerCenter: Point2; OuterCenter: Point2; Radius: Length; InnerStart: Point2; InnerEnd: Point2; OuterStart: Point2; OuterEnd: Point2; Sweep: ArcSweep; Role: ConceptRole }
+Let Lobes: LobeSpec[] = [ LobeSpec { Key: LeftTop; /* static typed values */ } ]
+Template RoundedLobe<Spec: LobeSpec> { Concept Struct Layout { } Profile Shape { } }
+Expand Lobes With RoundedLobe
+Add Lobes { Profiles: [LeftTopEar, RightTopEar]; From: -100mm; To: 0mm; Role: StrongInferenceR50Lobe }
+```
+
+`LobeSpec[]` is finite and literal-only (maximum 1024 rows). Keys are required, symbolic, and unique. Required fields, units, path shape, sweep, and template argument type are checked before Profile or Feature AIR construction. There are no runtime loops, dynamic collections, macro execution, or array-valued BRep operations.
+
+Expansion emits ordinary `Point2`, `Circle2`, `Line2`, and Profile segments. A grouped `Add` is then erased to individual same-interval/same-role Adds. Inspection retains the record key, template name, generated profile/member paths, and grouped-operation paths. In particular, template evidence uses paths such as `template:RoundedLobe[LeftTop].Layout.InnerArcGuide`, profiles use `profile:Lobes[LeftTop].Shape`, and group lowering uses `compose:Ctc01.Lobes[LeftTop]`.
+
+This is intentionally not a general table language. Record declarations, static arrays, one named template argument, and finite expansion are the whole capability. General polygon generators, CSV/dataframe import, symmetry, recursive templates, and runtime loops remain deferred.
+
+Default inspection consumes the expanded compiler result only; use `inspect-compose --materialize`, `build`, or `verify` for BRep and artifact evidence. See [inspect performance X1](../tooling/inspect-performance-x1.md).
diff --git a/docs/reconstruction/ctc01-compose-x1.md b/docs/reconstruction/ctc01-compose-x1.md
index 88c6c7fd..476df2e3 100644
--- a/docs/reconstruction/ctc01-compose-x1.md
+++ b/docs/reconstruction/ctc01-compose-x1.md
@@ -1,4 +1,16 @@
-# CTC-01 Profile + Compose blockout X2
+# CTC-01 Profile + Compose blockout X2/X3
+
+CTC-DATA-TEMPLATES-X1 adds `ctc01_prismatic_blockout_x3.firmament`. X2 is the preserved evidence baseline; X3 makes the four R50 lobes table-shaped: four `LobeSpec` rows, one `RoundedLobe` template, one bounded `Expand Lobes With RoundedLobe`, and one grouped `Add Lobes`. The compiler resolves those to the same four individually named Profiles and Adds before the section-stack compiler. The central hex remains a six-line Profile rather than introducing a polygon-solid shortcut.
+
+| Measure | X2 | X3 source |
+|---|---:|---:|
+| Lobe data rows | 0 | 4 |
+| Lobe templates | 0 | 1 |
+| Expanded lobe Profiles | 4 | 4 |
+| Expanded lobe Adds | 4 | 4 |
+| Source lines | 148 | 39 |
+
+`inspect-profile --json` and `inspect-compose --json` include `expansion` evidence for X3: source record keys, template-produced concept members, generated profiles, and the individual operations erased from `Add Lobes`. This preserves reviewability while eliminating repeated declaration trees.
## Verdict
diff --git a/docs/reconstruction/ctc01-sections-x1.md b/docs/reconstruction/ctc01-sections-x1.md
new file mode 100644
index 00000000..83d52082
--- /dev/null
+++ b/docs/reconstruction/ctc01-sections-x1.md
@@ -0,0 +1,28 @@
+# CTC-01 sections
+
+The X2 normalization probe uses `aetheris sections` with `Z ± 0.001 mm`.
+The X3 Firmament composition continues to provide normalized slab-region IR;
+the STEP route is being brought to the same loop contract.
+
+Current evidence: the raised central hexagon at Z=5 and Z=50 normalizes to one
+closed exact loop. Lower levels emit typed topology diagnostics rather than
+provisional chains because face partitions and cylindrical seams create
+high-valence/coincident boundary supports. Those diagnostics are the required
+input to the next normalization increment; no loop correspondence or boundary
+deviation is asserted from them.
+
+## X2 stabilization status
+
+`aetheris sections` now reports raw fragment provenance, canonical/atomic
+counts, collapsed duplicates, phase timings, and typed diagnostics per
+Below/At/Above sample. The lower CTC sections remain intentionally rejected:
+the trace identifies coincident fragments with conflicting material-left
+orientation (for example faces 90 and 91 at Z=-100), while four non-axis-normal
+conical faces are typed unsupported because their horizontal intersections are
+general conics. Neither case is converted into a provisional loop or region.
+
+Deferred before correspondence: resolve face/coedge ownership for coincident
+fragments, finish nesting/material-region construction for conflict-free STEP
+graphs, and decide whether general conics remain permanently rejected or gain
+their own exact section route. Sections diagnose construction; whole-body
+deviation audits final fidelity.
diff --git a/docs/tooling/inspect-performance-x1.md b/docs/tooling/inspect-performance-x1.md
new file mode 100644
index 00000000..27cf7c6e
--- /dev/null
+++ b/docs/tooling/inspect-performance-x1.md
@@ -0,0 +1,9 @@
+# Inspect performance X1
+
+`inspect-profile` and default `inspect-compose` are compiler-introspection commands. They parse, expand static data, resolve Profiles, normalize arrangements and transitions, and report analytic evidence. They do not emit BRep, export/reimport STEP, run M8 mass properties, CIR sampling, or CAD-assistant work.
+
+> Inspection reads compiler intent before it is erased. It does not independently simulate or verify the finished artifact.
+
+`inspect-compose --json --materialize` is the explicit opt-in diagnostic path for BRep plan/body and mass-properties evidence. `build`, `analyze`, and `verify` remain the artifact-producing and independently expensive routes.
+
+The original CTC slowdown was accidental: `inspect-compose` always called `PrismaticSectionStackEmitter.Emit` and `BrepMassProperties.Evaluate` after normalization. The default now stops at the immutable normalized stack. Report timings distinguish parse, normalize, optional materialize, and total work; arrangement timings remain per slab. Semantic SHA-256 signatures cover Profiles, operations, slab regions, and the composition, using resolved line/arc values and deterministic order.
diff --git a/docs/tooling/step-sections-normalize-x2.md b/docs/tooling/step-sections-normalize-x2.md
new file mode 100644
index 00000000..48210486
--- /dev/null
+++ b/docs/tooling/step-sections-normalize-x2.md
@@ -0,0 +1,26 @@
+# STEP section normalization X2
+
+Normalize section topology before comparing geometry.
+
+`aetheris sections part.step --axis Z --levels -100,-60,-50,0,5,50 --json`
+reports Below, At, and Above samples. Below/Above are `Z ± epsilon` (default
+`0.001 mm`); At is the requested plane and is diagnostic only.
+
+The active STEP route converts bounded line and circular-arc intersections to
+`ArrangementSourceCurve2D`, transfers endpoint and intersection parameters,
+splits them through `ProfileArrangementBuilder.NormalizeBoundary`, collapses
+identical atomic supports while retaining source IDs, then validates a
+deterministic incidence graph. It does not use the former first-neighbour
+chain walker.
+
+The current CTC evidence deliberately rejects rather than fabricates loops at
+the lower levels. The trace isolates four conical faces whose horizontal cuts
+are non-circular conics because their axes are not normal to Z. That family is
+outside X2 and is now reported as `UnsupportedSectionCurve` rather than
+silently lost. Cylinder trims are derived from the actual trim-edge/plane
+intersections, not from projected face vertices. At Z=5 and Z=50 the six-sided
+raised region normalizes as one exact loop. This is an evidence-backed
+normalization checkpoint, not yet a completed material-region implementation:
+material-side classification, conflict ownership, containment roles, and
+richer fragment provenance remain required before section correspondence can
+begin.
diff --git a/testdata/firmament/reconstructions/nist_ctc_01/ctc01_prismatic_blockout_x3.firmament b/testdata/firmament/reconstructions/nist_ctc_01/ctc01_prismatic_blockout_x3.firmament
new file mode 100644
index 00000000..56193730
--- /dev/null
+++ b/testdata/firmament/reconstructions/nist_ctc_01/ctc01_prismatic_blockout_x3.firmament
@@ -0,0 +1,39 @@
+// CTC-DATA-TEMPLATES-X1: data, bounded template, then ordinary resolved geometry.
+Record LobeSpec { Key: Symbol; Path: Point2[]; InnerCenter: Point2; OuterCenter: Point2; Radius: Length; InnerStart: Point2; InnerEnd: Point2; OuterStart: Point2; OuterEnd: Point2; Sweep: ArcSweep; Role: ConceptRole }
+Let Lobes: LobeSpec[] = [
+ LobeSpec { Key: LeftTop; Path: [[-400mm,125mm],[-250mm,125mm],[-250mm,175mm],[-300mm,225mm],[-350mm,225mm],[-400mm,175mm]]; InnerCenter: [-300mm,175mm]; OuterCenter: [-350mm,175mm]; Radius: 50mm; InnerStart: [-250mm,175mm]; InnerEnd: [-300mm,225mm]; OuterStart: [-350mm,225mm]; OuterEnd: [-400mm,175mm]; Sweep: CounterClockwise; Role: StrongInferenceR50Lobe }
+ LobeSpec { Key: RightTop; Path: [[250mm,125mm],[400mm,125mm],[400mm,175mm],[350mm,225mm],[300mm,225mm],[250mm,175mm]]; InnerCenter: [300mm,175mm]; OuterCenter: [350mm,175mm]; Radius: 50mm; InnerStart: [300mm,225mm]; InnerEnd: [250mm,175mm]; OuterStart: [400mm,175mm]; OuterEnd: [350mm,225mm]; Sweep: CounterClockwise; Role: StrongInferenceR50Lobe }
+ LobeSpec { Key: LeftBottom; Path: [[-350mm,-225mm],[-300mm,-225mm],[-250mm,-175mm],[-250mm,-125mm],[-400mm,-125mm],[-400mm,-175mm]]; InnerCenter: [-300mm,-175mm]; OuterCenter: [-350mm,-175mm]; Radius: 50mm; InnerStart: [-300mm,-225mm]; InnerEnd: [-250mm,-175mm]; OuterStart: [-400mm,-175mm]; OuterEnd: [-350mm,-225mm]; Sweep: CounterClockwise; Role: StrongInferenceR50Lobe }
+ LobeSpec { Key: RightBottom; Path: [[300mm,-225mm],[350mm,-225mm],[400mm,-175mm],[400mm,-125mm],[250mm,-125mm],[250mm,-175mm]]; InnerCenter: [300mm,-175mm]; OuterCenter: [350mm,-175mm]; Radius: 50mm; InnerStart: [250mm,-175mm]; InnerEnd: [300mm,-225mm]; OuterStart: [350mm,-225mm]; OuterEnd: [400mm,-175mm]; Sweep: CounterClockwise; Role: StrongInferenceR50Lobe }
+]
+Template RoundedLobe<Spec: LobeSpec> { Concept Struct Layout { } Profile Shape { } }
+Expand Lobes With RoundedLobe
+
+// X3 static expansion keeps this non-repeated scaffold/profile material explicit.
+Profile PrimaryWeb Using Ctc01BlockoutScaffold { Loop Outer {
+ Segment South { Trace: PrimaryWebGuide.Bottom; From: PrimaryWebGuide.BottomLeft; To: PrimaryWebGuide.BottomRight }
+ Segment East { Trace: PrimaryWebGuide.Right; From: PrimaryWebGuide.BottomRight; To: PrimaryWebGuide.TopRight }
+ Segment North { Trace: PrimaryWebGuide.Top; From: PrimaryWebGuide.TopRight; To: PrimaryWebGuide.TopLeft }
+ Segment West { Trace: PrimaryWebGuide.Left; From: PrimaryWebGuide.TopLeft; To: PrimaryWebGuide.BottomLeft }
+} }
+Profile MidLevelWeb Using Ctc01BlockoutScaffold { Loop Outer {
+ Segment South { Trace: MidLevelGuide.Bottom; From: MidLevelGuide.BottomLeft; To: MidLevelGuide.BottomRight }
+ Segment East { Trace: MidLevelGuide.Right; From: MidLevelGuide.BottomRight; To: MidLevelGuide.TopRight }
+ Segment North { Trace: MidLevelGuide.Top; From: MidLevelGuide.TopRight; To: MidLevelGuide.TopLeft }
+ Segment West { Trace: MidLevelGuide.Left; From: MidLevelGuide.TopLeft; To: MidLevelGuide.BottomLeft }
+} }
+// Central hex stays Profile-backed; its six measured vertices are not a new polygon feature.
+Concept Struct Ctc01HexGuide On XY {
+ Point2 HexSouth { Position: [0mm,-57.7350538379252mm] } Point2 HexSouthEast { Position: [50mm,-28.8675403784439mm] } Point2 HexNorthEast { Position: [50mm,28.8674865405187mm] } Point2 HexNorth { Position: [0mm,57.735mm] } Point2 HexNorthWest { Position: [-50mm,28.8674865405186mm] } Point2 HexSouthWest { Position: [-50mm,-28.8675403784438mm] }
+ Line2 HexSE { From: HexSouth; To: HexSouthEast } Line2 HexE { From: HexSouthEast; To: HexNorthEast } Line2 HexNE { From: HexNorthEast; To: HexNorth } Line2 HexNW { From: HexNorth; To: HexNorthWest } Line2 HexW { From: HexNorthWest; To: HexSouthWest } Line2 HexSW { From: HexSouthWest; To: HexSouth }
+}
+Profile CentralHex Using Ctc01HexGuide { Loop Outer {
+ Segment SouthEast { Trace: HexSE; From: HexSouth; To: HexSouthEast } Segment East { Trace: HexE; From: HexSouthEast; To: HexNorthEast } Segment NorthEast { Trace: HexNE; From: HexNorthEast; To: HexNorth } Segment NorthWest { Trace: HexNW; From: HexNorth; To: HexNorthWest } Segment West { Trace: HexW; From: HexNorthWest; To: HexSouthWest } Segment SouthWest { Trace: HexSW; From: HexSouthWest; To: HexSouth }
+} }
+Struct Composition { Compose Ctc01PrismaticBlockoutX3 {
+ Placement ReferenceWorld { Anchor: [0mm,0mm,0mm]; ProfilePlane: XY; Axis: +Z; ReferenceDirection: +X }
+ Base PrimaryPlate { Profile: PrimaryWeb; From: -100mm; To: 0mm; Role: ObservedPrimaryWeb }
+ Add Lobes { Profiles: [LeftTopEar, RightTopEar, LeftBottomEar, RightBottomEar]; From: -100mm; To: 0mm; Role: StrongInferenceR50Lobe }
+ Add MidLevelPlate { Profile: MidLevelWeb; From: -60mm; To: 0mm; Role: StrongInferenceMidLevel }
+ Add CentralRaisedRegion { Profile: CentralHex; From: 0mm; To: 50mm; Role: StrongInferenceCentralRaisedRegion }
+} }