Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add semantic selection inspection and chamfer export

Yuechen Li5b9a6f3d4458
diff --git a/Aetheris.CLI.Tests/InspectSelectionsTests.cs b/Aetheris.CLI.Tests/InspectSelectionsTests.cs
new file mode 100644
index 00000000..0db6bfe4
--- /dev/null
+++ b/Aetheris.CLI.Tests/InspectSelectionsTests.cs
@@ -0,0 +1,29 @@
+using System.Text.Json;
+
+namespace Aetheris.CLI.Tests;
+
+public sealed class InspectSelectionsTests
+{
+ [Fact]
+ public void InspectSelections_ReportsSourceGroundedClosedLoop()
+ {
+ var root = FindRepoRoot();
+ var source = Path.Combine(root, "fixtures", "FirmamentV2", "Profile", "valid", "semantic-top-boundary-loop.firmament");
+ var stdout = new StringWriter(); var stderr = new StringWriter();
+ var exit = Aetheris.CLI.CliRunner.Run(["inspect-selections", source, "--json"], stdout, stderr);
+ Assert.Equal(0, exit); Assert.True(string.IsNullOrWhiteSpace(stderr.ToString()), stderr.ToString());
+ using var json = JsonDocument.Parse(stdout.ToString());
+ var selection = json.RootElement.GetProperty("selections").EnumerateArray().Single();
+ Assert.True(selection.GetProperty("succeeded").GetBoolean());
+ Assert.True(selection.GetProperty("connectivity").GetProperty("isClosed").GetBoolean());
+ Assert.Equal(4, selection.GetProperty("materializedDescendants").GetArrayLength());
+ Assert.Equal("EdgeFinish", selection.GetProperty("consumer").GetString());
+ }
+
+ private static string FindRepoRoot()
+ {
+ var directory = new DirectoryInfo(AppContext.BaseDirectory);
+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;
+ return directory?.FullName ?? throw new DirectoryNotFoundException();
+ }
+}
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index 217e971e..02f2c7e7 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -113,11 +113,12 @@ public static class CliRunner
string? Error,
string? Classification = null,
int? RigidRootCount = null);
- 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 TopLevelUsage = "Usage: aetheris <build|validate|inspect-profile|inspect-compose|inspect-selections|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 [--materialize]";
+ private const string InspectSelectionsUsage = "Usage: aetheris inspect-selections <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";
@@ -177,6 +178,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),
+ "inspect-selections" => RunInspectSelections(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),
@@ -468,6 +470,61 @@ public static class CliRunner
return (stableId, "ConceptGuide", null);
}
+ private static int RunInspectSelections(string[] args, TextWriter stdout, TextWriter stderr)
+ {
+ if (args.Length == 0 || IsHelpFlag(args[0])) { stdout.WriteLine(InspectSelectionsUsage); return args.Length == 0 ? 1 : 0; }
+ if (args.Length != 2 || args[1] != "--json") { stderr.WriteLine(InspectSelectionsUsage); return 1; }
+ if (!File.Exists(args[0])) { stderr.WriteLine($"Selection source was not found: {args[0]}"); return 1; }
+ var source = File.ReadAllText(args[0]);
+ if (PrismaticProfileCompositionParser.IsCompositionSource(source))
+ {
+ var parsedCompose = PrismaticProfileCompositionParser.Parse(source);
+ var stack = PrismaticSectionStackCompiler.Normalize(parsedCompose, out var composeDiagnostics);
+ var emittedCompose = stack is null ? null : PrismaticSectionStackEmitter.Emit(stack);
+ if (stack is null || emittedCompose?.Body is null || emittedCompose.Correspondence is null) { stderr.WriteLine(string.Join(Environment.NewLine, composeDiagnostics)); return 1; }
+ var composeRequests = SemanticSelectionSourceParser.Parse(source, parsedCompose.Profiles.Values.First(), stack.Feature.Name, out var composeParseDiagnostics);
+ var composeResults = composeRequests.Select(request => SemanticTopologySelectionResolver.Resolve(emittedCompose.Body, emittedCompose.Correspondence, request)).ToArray();
+ stdout.WriteLine(JsonSerializer.Serialize(new
+ {
+ body = emittedCompose.Correspondence.BodyStableId,
+ selections = composeResults.Select(result => new { name = result.Request.Label, stableId = result.Request.StableId, sourceIdentities = result.Request.SourceStableIds, body = result.Request.BodyStableId, expectedShape = result.Request.Require.ToString(), topologyRole = result.Request.Role?.ToString(), succeeded = result.Succeeded, failure = result.Failure.ToString(), connectivity = new { result.IsConnected, result.IsClosed }, traversalOrder = result.OrderedChain.Select(x => x.StableId), materializedDescendants = result.Descendants.Select(x => new { x.StableId, x.Kind, role = x.Role.ToString(), x.SourceStableId, x.ParentStableId }), provenance = emittedCompose.Correspondence.ProvenanceChain, consumer = result.Request.Consumer, diagnostics = result.Diagnostics }),
+ arrangement = stack.Slabs.Select(s => new { slab = new[] { s.From, s.To }, fragments = s.Arrangement?.AtomicFragments.Select(f => new { f.StableId, source = f.Source.Provenance.StableId, f.FromParameter, f.ToParameter, f.MaterialOnLeft, f.Retained }) }),
+ diagnostics = composeDiagnostics.Concat(composeParseDiagnostics).Distinct()
+ }, JsonOptions));
+ return composeDiagnostics.Count == 0 && composeParseDiagnostics.Count == 0 && composeResults.All(x => x.Succeeded) ? 0 : 1;
+ }
+ var v2 = FirmamentV2Parser.Parse(source, Path.GetDirectoryName(Path.GetFullPath(args[0])));
+ if (v2.IsSuccess && v2.Document is not null && v2.Document.ModifyBlocks?.SelectMany(x => x.SemanticHoles).Any() == true)
+ {
+ var hole = SemanticHoleInspection.Inspect(v2.Document);
+ if (!hole.Succeeded || hole.Correspondence is null) { stderr.WriteLine(string.Join(Environment.NewLine, hole.Diagnostics)); return 1; }
+ stdout.WriteLine(JsonSerializer.Serialize(new { body = hole.Correspondence.BodyStableId, hole = hole.HoleId, descendants = hole.Correspondence.Descendants.Select(x => new { x.StableId, x.Kind, role = x.Role.ToString(), x.SourceStableId, x.ParentStableId }), provenance = hole.Correspondence.ProvenanceChain, diagnostics = hole.Diagnostics }, JsonOptions));
+ return 0;
+ }
+ var parsed = ProfileAuthoringParser.Parse(source);
+ if (parsed.Profile is null) { stderr.WriteLine(string.Join(Environment.NewLine, parsed.Diagnostics)); return 1; }
+ var emitted = ResolvedProfile2DValidator.Extrude(parsed.Profile, parsed.Height);
+ if (emitted.Body is null || emitted.Correspondence is null) { stderr.WriteLine(string.Join(Environment.NewLine, emitted.Diagnostics)); return 1; }
+ var requests = SemanticSelectionSourceParser.Parse(source, parsed.Profile, parsed.Profile.Name, out var parseDiagnostics);
+ var results = requests.Select(request => SemanticTopologySelectionResolver.Resolve(emitted.Body, emitted.Correspondence, request)).ToArray();
+ stdout.WriteLine(JsonSerializer.Serialize(new
+ {
+ body = emitted.Correspondence.BodyStableId,
+ selections = results.Select(result => new
+ {
+ name = result.Request.Label, stableId = result.Request.StableId, sourceIdentities = result.Request.SourceStableIds,
+ body = result.Request.BodyStableId, expectedShape = result.Request.Require.ToString(), topologyRole = result.Request.Role?.ToString(),
+ succeeded = result.Succeeded, failure = result.Failure.ToString(), connectivity = new { result.IsConnected, result.IsClosed },
+ traversalOrder = result.OrderedChain.Select(x => x.StableId),
+ materializedDescendants = result.Descendants.Select(x => new { x.StableId, x.Kind, role = x.Role.ToString(), x.SourceStableId, x.ParentStableId, sourceSpan = result.Request.SourceSpan }),
+ provenance = emitted.Correspondence.ProvenanceChain, consumer = result.Request.Consumer,
+ diagnostics = result.Diagnostics
+ }),
+ diagnostics = parseDiagnostics
+ }, JsonOptions));
+ return parseDiagnostics.Count == 0 && results.All(x => x.Succeeded) ? 0 : 1;
+ }
+
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; }
@@ -2564,6 +2621,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(" inspect-selections Resolve source-grounded topology selections without STEP analysis.");
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.");
diff --git a/Aetheris.Kernel.Firmament.Tests/AirHoleSimpleShaftMaterializerTests.cs b/Aetheris.Kernel.Firmament.Tests/AirHoleSimpleShaftMaterializerTests.cs
index d2ef4d0c..c53bf1ee 100644
--- a/Aetheris.Kernel.Firmament.Tests/AirHoleSimpleShaftMaterializerTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/AirHoleSimpleShaftMaterializerTests.cs
@@ -16,6 +16,10 @@ public sealed class AirHoleSimpleShaftMaterializerTests
Assert.True(result.Succeeded, string.Join("\n", result.Diagnostics));
Assert.NotNull(result.Body);
Assert.NotNull(result.Plan);
+ var correspondence = Assert.IsType<SemanticTopologyCorrespondence>(result.Correspondence);
+ Assert.Contains(correspondence.Descendants, x => x.Role == SemanticTopologyRole.HoleEntryLoop);
+ Assert.Contains(correspondence.Descendants, x => x.Role == SemanticTopologyRole.HoleExitLoop);
+ Assert.Contains(correspondence.Descendants, x => x.Role == SemanticTopologyRole.HoleWallFace);
Assert.Same(feature, result.Plan.SemanticFeature);
Assert.Equal("hole-001", result.Plan.SemanticFeatureId);
Assert.Equal(nameof(AirHoleFeature), result.Plan.SemanticSourceKind);
diff --git a/Aetheris.Kernel.Firmament.Tests/Integration/SemanticTopologySelectionTests.cs b/Aetheris.Kernel.Firmament.Tests/Integration/SemanticTopologySelectionTests.cs
new file mode 100644
index 00000000..b328a89c
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/Integration/SemanticTopologySelectionTests.cs
@@ -0,0 +1,39 @@
+using Aetheris.Kernel.Firmament.Materializer;
+
+namespace Aetheris.Kernel.Firmament.Tests.Integration;
+
+public sealed class SemanticTopologySelectionTests
+{
+ [Fact]
+ public void ProfileSegments_ResolveToClosedTopBoundaryChain_WithoutGeometryRediscovery()
+ {
+ var profile = Rectangle();
+ var emitted = ResolvedProfile2DValidator.Extrude(profile, 5);
+ var body = Assert.IsType<Aetheris.Kernel.Core.Brep.BrepBody>(emitted.Body);
+ var correspondence = Assert.IsType<SemanticTopologyCorrespondence>(emitted.Correspondence);
+ var request = new SemanticSelectionRequest("selection:top", "Top", "Main", profile.Loops[0].Segments.Select(x => x.Provenance.StableId).ToArray(), SemanticTopologyRole.TopBoundary, SemanticSelectionRequirement.ClosedLoop, "test");
+
+ var result = SemanticTopologySelectionResolver.Resolve(body, correspondence, request);
+
+ Assert.True(result.Succeeded);
+ Assert.True(result.IsConnected); Assert.True(result.IsClosed);
+ Assert.Equal(4, result.OrderedChain.Count);
+ Assert.All(result.Descendants, x => Assert.Equal(SemanticTopologyRole.TopBoundary, x.Role));
+ }
+
+ [Fact]
+ public void MissingSource_IsTypedFailure()
+ {
+ var profile = Rectangle(); var emitted = ResolvedProfile2DValidator.Extrude(profile, 5);
+ var result = SemanticTopologySelectionResolver.Resolve(emitted.Body!, emitted.Correspondence!, new("selection:missing", "Missing", "Main", ["profile:Main.Outer.Nope"], SemanticTopologyRole.TopBoundary, SemanticSelectionRequirement.OneOrMore, "test"));
+ Assert.False(result.Succeeded); Assert.Equal(SemanticSelectionFailure.SemanticSourceNotFound, result.Failure);
+ }
+
+ private static ResolvedProfile2D Rectangle()
+ {
+ var points = new[] { (-10d, -5d), (10d, -5d), (10d, 5d), (-10d, 5d) };
+ var names = new[] { "South", "East", "North", "West" };
+ var segments = Enumerable.Range(0, 4).Select(i => new ResolvedProfileSegment2D(names[i], new LineArcLineSegment2D(points[i], points[(i + 1) % 4]), new($"profile:Main.Outer.{names[i]}", $"concept:Rectangle.{names[i]}", "test", "test", "XY"))).ToArray();
+ return new("Main", "XY", [new ResolvedProfileLoop2D("Outer", true, segments)]);
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
index 771a5a3c..093c5675 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
@@ -1,5 +1,6 @@
using System.Text;
using System.Security.Cryptography;
+using System.Text.RegularExpressions;
using Aetheris.Kernel.Core.Air;
using Aetheris.Kernel.Core.Results;
using Aetheris.Kernel.Core.Step242;
@@ -58,6 +59,8 @@ public static class FirmamentBuildAndExport
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());
+ if (sourceText.Contains("EdgeFinish", StringComparison.Ordinal))
+ return ExportComposedSemanticTopBoundaryChamfer(sourceText, parsed, stack, emitted);
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"));
@@ -68,6 +71,8 @@ public static class FirmamentBuildAndExport
if (parsed.Profile is null) return KernelResult<FirmamentStepExportResult>.Failure(parsed.Diagnostics.Select(x => new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, x, "FirmamentV2.Profile")).ToArray());
var emitted = ResolvedProfile2DValidator.Extrude(parsed.Profile, parsed.Height);
if (emitted.Status != LineArcProfileExtrudeStatus.Succeeded || 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.Profile")).ToArray());
+ if (sourceText.Contains("EdgeFinish", StringComparison.Ordinal))
+ return ExportProfileSemanticTopBoundaryChamfer(sourceText, parsed.Profile, parsed.Height, emitted);
var step = Step242Exporter.ExportBody(emitted.Body); if (!step.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, parsed.Profile.Name, 0, "profile-extrude", "line-arc-profile"));
}
@@ -206,6 +211,68 @@ public static class FirmamentBuildAndExport
return FirmamentStepExporter.Export(new FirmamentCompileRequest(new FirmamentSourceDocument(sourceText)));
}
+ private static KernelResult<FirmamentStepExportResult> ExportComposedSemanticTopBoundaryChamfer(
+ string source, PrismaticProfileCompositionParseResult parsed, PrismaticSectionStackConstruction stack, PrismaticSectionStackEmissionResult emitted)
+ {
+ KernelResult<FirmamentStepExportResult> Fail(string code) => KernelResult<FirmamentStepExportResult>.Failure([
+ new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, code, "FirmamentV2.ComposeSemanticSelection")]);
+ if (emitted.Body is null || emitted.Correspondence is null) return Fail("MissingCorrespondenceEvidence");
+ var selections = SemanticSelectionSourceParser.Parse(source, parsed.Profiles.Values.First(), stack.Feature.Name, out var diagnostics);
+ if (diagnostics.Count != 0 || selections.Count != 1) return Fail(diagnostics.FirstOrDefault() ?? "SemanticSourceNotFound");
+ var selection = SemanticTopologySelectionResolver.Resolve(emitted.Body, emitted.Correspondence, selections[0]);
+ if (!selection.Succeeded || !selection.IsClosed || selection.Request.Require != SemanticSelectionRequirement.ClosedLoop) return Fail(selection.Failure == SemanticSelectionFailure.None ? "SelectionConsumerMismatch" : selection.Failure.ToString());
+ var finish = Regex.Match(source, @"\bEdgeFinish\s+(?<name>\w+)\s*\{\s*Target\s*:\s*(?<target>\w+)\s*;?\s*Kind\s*:\s*(?<kind>Chamfer)\s*;?\s*Distance\s*:\s*(?<amount>[-+.\d]+)mm", RegexOptions.Singleline | RegexOptions.CultureInvariant);
+ if (!finish.Success || finish.Groups["target"].Value != selection.Request.Label) return Fail("SelectionConsumerMismatch");
+ var topSlab = stack.Slabs.MaxBy(s => s.To)!;
+ var curves = topSlab.Region.Outer.Loops.Single().Segments.Select(x => x.Geometry).ToArray();
+ if (curves.Length < 4 || curves.Any(x => x is not LineArcLineSegment2D)) return Fail("UnsupportedTopologyChange");
+ var points = curves.Cast<LineArcLineSegment2D>().SelectMany(x => new[] { x.Start, x.End }).ToArray();
+ var minX = points.Min(x => x.X); var maxX = points.Max(x => x.X); var minY = points.Min(x => x.Y); var maxY = points.Max(x => x.Y);
+ if (points.Any(p => p.X != minX && p.X != maxX && p.Y != minY && p.Y != maxY)) return Fail("UnsupportedTopologyChange");
+ var compiled = AirTopFaceBoundaryChamferCompiler.Compile(new(stack.Feature.Name, $"{stack.Feature.Name}.{finish.Groups["name"].Value}", finish.Groups["name"].Value, maxX - minX, maxY - minY, stack.Feature.CriticalLevels.Max() - stack.Feature.CriticalLevels.Min(), "+Z", "Boundary", "Chamfer", double.Parse(finish.Groups["amount"].Value, System.Globalization.CultureInfo.InvariantCulture), new AirSourceSpan(finish.Index, finish.Length, stack.Feature.Name)));
+ if (!compiled.Succeeded || compiled.Body is null || compiled.BRepPlan?.RealizationPlan is null) return Fail(compiled.Diagnostics.FirstOrDefault() ?? "UnsupportedTopologyChange");
+ var step = Step242Exporter.ExportBody(compiled.Body, new Step242ExportOptions { ProductName = compiled.Feature.FeatureName, ApplicationName = AirTopFaceBoundaryChamferCompileResult.ProductionRoute, BrepExportPreflightMode = BrepExportPreflightMode.Enforce, BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute });
+ if (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
+ var reimport = Step242Importer.ImportBody(step.Value);
+ if (!reimport.IsSuccess || reimport.Value is null || !FirmamentManifoldChecker.IsManifold(reimport.Value)) return Fail("semantic-compose-finish-step-reimport-failed");
+ return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, compiled.Feature.FeatureId, 0, "semantic-compose-edge-finish", "source-grounded-composed-top-boundary-chamfer"));
+ }
+
+ private static KernelResult<FirmamentStepExportResult> ExportProfileSemanticTopBoundaryChamfer(
+ string source,
+ ResolvedProfile2D profile,
+ double height,
+ LineArcProfileExtrudeResult emitted)
+ {
+ KernelResult<FirmamentStepExportResult> Fail(string code) => KernelResult<FirmamentStepExportResult>.Failure([
+ new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, code, "FirmamentV2.SemanticSelection")]);
+ if (emitted.Body is null || emitted.Correspondence is null) return Fail("NoMaterializedDescendants");
+ var selections = SemanticSelectionSourceParser.Parse(source, profile, profile.Name, out var selectionDiagnostics);
+ if (selectionDiagnostics.Count > 0 || selections.Count != 1) return Fail(selectionDiagnostics.FirstOrDefault() ?? "SemanticSourceNotFound");
+ var selection = SemanticTopologySelectionResolver.Resolve(emitted.Body, emitted.Correspondence, selections[0]);
+ if (!selection.Succeeded) return Fail(selection.Failure.ToString());
+ var finish = Regex.Match(source, @"\bEdgeFinish\s+(?<name>\w+)\s*\{\s*Target\s*:\s*(?<target>\w+)\s*;?\s*Kind\s*:\s*(?<kind>Chamfer|Fillet)\s*;?\s*(?:Distance|Radius)\s*:\s*(?<amount>[-+.\d]+)mm", RegexOptions.Singleline | RegexOptions.CultureInvariant);
+ if (!finish.Success || !string.Equals(finish.Groups["target"].Value, selection.Request.Label, StringComparison.Ordinal)) return Fail("SelectionConsumerMismatch");
+ if (!string.Equals(finish.Groups["kind"].Value, "Chamfer", StringComparison.Ordinal) || selection.Request.Require != SemanticSelectionRequirement.ClosedLoop || !selection.IsClosed) return Fail("SelectionConsumerMismatch");
+ var lines = profile.Loops.Single().Segments.Select(x => x.Geometry).OfType<LineArcLineSegment2D>().ToArray();
+ if (lines.Length != 4 || profile.Loops.Single().Segments.Count != 4) return Fail("UnsupportedTopologyChange");
+ var points = lines.SelectMany(x => new[] { x.Start, x.End }).ToArray();
+ var minX = points.Min(x => x.X); var maxX = points.Max(x => x.X); var minY = points.Min(x => x.Y); var maxY = points.Max(x => x.Y);
+ if (lines.Any(x => Math.Abs(x.Start.X - x.End.X) > 1e-9 && Math.Abs(x.Start.Y - x.End.Y) > 1e-9)) return Fail("UnsupportedTopologyChange");
+ var compiled = AirTopFaceBoundaryChamferCompiler.Compile(new(
+ profile.Name, $"{profile.Name}.{finish.Groups["name"].Value}", finish.Groups["name"].Value,
+ maxX - minX, maxY - minY, height, "+Z", "Boundary", "Chamfer",
+ double.Parse(finish.Groups["amount"].Value, System.Globalization.CultureInfo.InvariantCulture),
+ new AirSourceSpan(finish.Index, finish.Length, profile.Name)));
+ if (!compiled.Succeeded || compiled.Body is null || compiled.BRepPlan?.RealizationPlan is null) return Fail(compiled.Diagnostics.FirstOrDefault() ?? "UnsupportedTopologyChange");
+ if (!FirmamentManifoldChecker.IsManifold(compiled.Body)) return Fail("semantic-selection-finish-nonmanifold");
+ var step = Step242Exporter.ExportBody(compiled.Body, new Step242ExportOptions { ProductName = compiled.Feature.FeatureName, ApplicationName = AirTopFaceBoundaryChamferCompileResult.ProductionRoute, BrepExportPreflightMode = BrepExportPreflightMode.Enforce, BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute });
+ if (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
+ var reimport = Step242Importer.ImportBody(step.Value);
+ if (!reimport.IsSuccess || reimport.Value is null || !FirmamentManifoldChecker.IsManifold(reimport.Value)) return Fail("semantic-selection-finish-step-reimport-failed");
+ return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, compiled.Feature.FeatureId, 0, "semantic-profile-edge-finish", "source-grounded-top-boundary-chamfer"));
+ }
+
private static KernelResult<FirmamentStepExportResult>? TryExportV2StandaloneCubicLattice(FirmamentV2Document document)
{
var fills = document.StandaloneLatticeFills ?? [];
diff --git a/Aetheris.Kernel.Firmament/Materializer/AirHoleSimpleShaftMaterializer.cs b/Aetheris.Kernel.Firmament/Materializer/AirHoleSimpleShaftMaterializer.cs
index 6297e0c8..0bd4e2cb 100644
--- a/Aetheris.Kernel.Firmament/Materializer/AirHoleSimpleShaftMaterializer.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/AirHoleSimpleShaftMaterializer.cs
@@ -1,8 +1,24 @@
using Aetheris.Kernel.Core.Air;
using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Topology;
+using Aetheris.Kernel.Firmament.FirmamentV2;
namespace Aetheris.Kernel.Firmament.Materializer;
+public sealed record SemanticHoleInspectionResult(bool Succeeded, string? HoleId, BrepBody? Body, SemanticTopologyCorrespondence? Correspondence, IReadOnlyList<string> Diagnostics);
+public static class SemanticHoleInspection
+{
+ public static SemanticHoleInspectionResult Inspect(FirmamentV2Document document)
+ {
+ var holes = FirmamentV2SemanticHoleLowering.LowerSemanticHoles(document);
+ var binding = document.Solids.FirstOrDefault();
+ if (holes.Count != 1 || binding?.Primitive is not FirmamentV2BoxRecord box || box.Size.Count != 3) return new(false, null, null, null, ["MissingCorrespondenceEvidence: bounded inspection requires one shaft hole in one Box host."]);
+ var host = document.ConceptIr is null ? new AirHoleSimpleShaftHost(box.Size[0], box.Size[1], -box.Size[2] / 2d, box.Size[2] / 2d) : new AirHoleSimpleShaftHost(box.Size[0], box.Size[1], 0d, box.Size[2]);
+ var result = AirHoleSimpleShaftMaterializer.Execute(holes[0], host);
+ return new(result.Succeeded && result.Correspondence is not null, holes[0].FeatureId, result.Body, result.Correspondence, result.Diagnostics);
+ }
+}
+
internal enum AirHoleSimpleShaftMaterializationStatus
{
Succeeded,
@@ -44,7 +60,8 @@ internal sealed record AirHoleSimpleShaftMaterializationResult(
AirHoleSimpleShaftMaterializationStatus Status,
AirHoleSimpleShaftMaterializationPlan? Plan,
BrepBody? Body,
- IReadOnlyList<string> Diagnostics)
+ IReadOnlyList<string> Diagnostics,
+ SemanticTopologyCorrespondence? Correspondence = null)
{
public bool Succeeded => Status == AirHoleSimpleShaftMaterializationStatus.Succeeded;
}
@@ -74,7 +91,9 @@ internal static class AirHoleSimpleShaftMaterializer
}
diagnostics.Add("air-hole-x2 materialization succeeded with semantic parent preserved; ProfileStackExtrudeSpec is lowering furniture, not source truth.");
- return new(AirHoleSimpleShaftMaterializationStatus.Succeeded, planResult.Plan, execution.Body, diagnostics);
+ var correspondence = BuildCorrespondence(planResult.Plan, execution.Body);
+ diagnostics.Add("air-hole-x2 semantic correspondence published: entry/exit loops and edges plus shaft wall face.");
+ return new(AirHoleSimpleShaftMaterializationStatus.Succeeded, planResult.Plan, execution.Body, diagnostics, correspondence);
}
public static AirHoleSimpleShaftMaterializationResult TryCreatePlan(AirHoleFeature feature, AirHoleSimpleShaftHost host)
@@ -134,6 +153,29 @@ internal static class AirHoleSimpleShaftMaterializer
return top ? (Math.Max(host.ZMin, host.ZMax - depth), host.ZMax) : (host.ZMin, Math.Min(host.ZMax, host.ZMin + depth));
}
+ private static SemanticTopologyCorrespondence? BuildCorrespondence(AirHoleSimpleShaftMaterializationPlan plan, BrepBody body)
+ {
+ // The bounded ProfileStack executor emits the retained box faces first and shaft walls in ProfileStack order.
+ // This is construction-plan ownership, not a post-hoc geometric recognizer.
+ if (plan.EndConditionKind != AirHoleEndConditionKind.ThroughAll || plan.StackKind != AirHoleStackKind.SimpleShaft) return null;
+ var faces = body.Topology.Faces.OrderBy(x => x.Id.Value).ToArray();
+ if (faces.Length < 7) return null;
+ var bottom = faces[0]; var top = faces[1]; var wall = faces[6];
+ if (top.LoopIds.Count < 2 || bottom.LoopIds.Count < 2) return null;
+ var entryLoop = top.LoopIds[^1]; var exitLoop = bottom.LoopIds[^1];
+ EdgeId EdgeOf(LoopId loopId) => body.Topology.Coedges.Single(x => x.Id == body.Topology.Loops.Single(l => l.Id == loopId).CoedgeIds[0]).EdgeId;
+ var source = $"hole:{plan.SemanticFeatureId}";
+ var descendants = new SemanticTopologyDescendant[]
+ {
+ new($"material:{source}:entry-loop", "Loop", SemanticTopologyRole.HoleEntryLoop, source, Loop: entryLoop, ParentStableId: plan.SemanticFeatureId),
+ new($"material:{source}:exit-loop", "Loop", SemanticTopologyRole.HoleExitLoop, source, Loop: exitLoop, ParentStableId: plan.SemanticFeatureId),
+ new($"material:{source}:entry-edge", "Edge", SemanticTopologyRole.TopBoundary, source, Edge: EdgeOf(entryLoop), ParentStableId: plan.SemanticFeatureId),
+ new($"material:{source}:exit-edge", "Edge", SemanticTopologyRole.BottomBoundary, source, Edge: EdgeOf(exitLoop), ParentStableId: plan.SemanticFeatureId),
+ new($"material:{source}:wall", "Face", SemanticTopologyRole.HoleWallFace, source, Face: wall.Id, ParentStableId: plan.SemanticFeatureId)
+ };
+ return new(plan.SemanticFeature.TargetBodyId ?? "semantic-hole-host", descendants, ["HoleAIR", "AirHoleSimpleShaftMaterializationPlan", "ProfileStackExtrudeSpec", "AuthoritativeBRepPlan"]);
+ }
+
private static IEnumerable<ProfileStackLayer> BuildLayers(AirHoleFeature feature, AirHoleSimpleShaftHost host, double cutZMin, double cutZMax)
{
if (cutZMin > host.ZMin + Tolerance) yield return new(host.ZMin, cutZMin, null, "air-hole-x2-solid-before-blind-depth", []);
diff --git a/Aetheris.Kernel.Firmament/Materializer/LineArcProfileExtrudeEmitter.cs b/Aetheris.Kernel.Firmament/Materializer/LineArcProfileExtrudeEmitter.cs
index abbab5b4..383537c1 100644
--- a/Aetheris.Kernel.Firmament/Materializer/LineArcProfileExtrudeEmitter.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/LineArcProfileExtrudeEmitter.cs
@@ -14,7 +14,7 @@ public sealed record LineArcFullCircle2D((double X, double Y) Center, double Rad
public sealed record LineArcProfileLoop2D(IReadOnlyList<LineArcProfileCurve2D> Curves, bool IsHole);
public sealed record LineArcProfileExtrudeRequest(IReadOnlyList<LineArcProfileLoop2D> Loops, double Height);
public enum LineArcProfileExtrudeStatus { Succeeded, Rejected, Deferred, Failed }
-public sealed record LineArcProfileExtrudeResult(LineArcProfileExtrudeStatus Status, BrepBody? Body, IReadOnlyList<string> Diagnostics);
+public sealed record LineArcProfileExtrudeResult(LineArcProfileExtrudeStatus Status, BrepBody? Body, IReadOnlyList<string> Diagnostics, SemanticTopologyCorrespondence? Correspondence = null);
public static class LineArcProfileExtrudeEmitter
{
@@ -25,12 +25,26 @@ public static class LineArcProfileExtrudeEmitter
var d = new List<string> { "v2-v4-line-arc-profile-extrude-attempted" };
if (!Validate(request, d)) return new(LineArcProfileExtrudeStatus.Rejected, null, d);
d.Add("v2-v4-profile-validated");
- var ok = TryBuild(request, d, out var body);
+ var ok = TryBuild(request, null, d, out var body, out var correspondence);
if (!ok || body is null) return new(LineArcProfileExtrudeStatus.Failed, null, d.Append("v2-v4-line-arc-profile-extrude-rejected:emitter validation failed").ToArray());
d.Add("v2-v4-cap-faces-emitted");
d.Add("v2-v4-no-3d-boolean-used");
d.Add("v2-v4-line-arc-profile-extrude-succeeded");
- return new(LineArcProfileExtrudeStatus.Succeeded, body, d.Distinct().OrderBy(x => x).ToArray());
+ return new(LineArcProfileExtrudeStatus.Succeeded, body, d.Distinct().OrderBy(x => x).ToArray(), correspondence);
+ }
+
+ /// <summary>Materializes a resolved authored Profile and retains direct plan-to-topology correspondence.</summary>
+ public static LineArcProfileExtrudeResult TryEmit(ResolvedProfile2D profile, double height)
+ {
+ var validation = ResolvedProfile2DValidator.Validate(profile);
+ if (!validation.IsValid) return new(LineArcProfileExtrudeStatus.Rejected, null, validation.Diagnostics);
+ var request = new LineArcProfileExtrudeRequest(profile.Loops.Select(l => new LineArcProfileLoop2D(l.Segments.Select(s => s.Geometry).ToArray(), !l.IsOuter)).ToArray(), height);
+ var diagnostics = new List<string> { "v2-v4-line-arc-profile-extrude-attempted", "semantic-selection-correspondence-requested" };
+ if (!Validate(request, diagnostics)) return new(LineArcProfileExtrudeStatus.Rejected, null, diagnostics);
+ var ok = TryBuild(request, profile, diagnostics, out var body, out var correspondence);
+ return ok && body is not null
+ ? new(LineArcProfileExtrudeStatus.Succeeded, body, diagnostics.Distinct().OrderBy(x => x).ToArray(), correspondence)
+ : new(LineArcProfileExtrudeStatus.Failed, null, diagnostics.Append("v2-v4-line-arc-profile-extrude-rejected:emitter validation failed").ToArray());
}
private static bool Validate(LineArcProfileExtrudeRequest req, List<string> d)
@@ -53,14 +67,15 @@ public static class LineArcProfileExtrudeEmitter
return true;
}
- private static bool TryBuild(LineArcProfileExtrudeRequest profile, List<string> d, out BrepBody? body)
+ private static bool TryBuild(LineArcProfileExtrudeRequest profile, ResolvedProfile2D? sourceProfile, List<string> d, out BrepBody? body, out SemanticTopologyCorrespondence? correspondence)
{
- body = null;
+ body = null; correspondence = null;
var h = profile.Height;
var b = new TopologyBuilder();
var z0 = -h / 2d; var z1 = h / 2d;
var bottomLoops = new List<LoopId>(); var topLoops = new List<LoopId>();
- var sideFaces = new List<(LoopId Loop, SurfaceGeometry Surface, string Diag)>();
+ var sideFaces = new List<(LoopId Loop, SurfaceGeometry Surface, string Diag, string? Source, EdgeId Bottom, EdgeId Top, EdgeId StartVertical, EdgeId EndVertical)>();
+ var descendants = new List<SemanticTopologyDescendant>();
var points = new Dictionary<VertexId, Point3D>();
var edgeCurves = new Dictionary<EdgeId, CurveGeometry>();
// A profile loop owns its vertices. Adjacent curves that meet at the same
@@ -85,11 +100,14 @@ public static class LineArcProfileExtrudeEmitter
verticalEdges.Add(key, created); return created;
}
- foreach (var loop in profile.Loops)
+ for (var loopIndex = 0; loopIndex < profile.Loops.Count; loopIndex++)
{
+ var loop = profile.Loops[loopIndex];
var bottomUses = new List<Use>(); var topUses = new List<Use>();
- foreach (var curve in loop.Curves)
+ for (var curveIndex = 0; curveIndex < loop.Curves.Count; curveIndex++)
{
+ var curve = loop.Curves[curveIndex];
+ var source = sourceProfile?.Loops[loopIndex].Segments[curveIndex].Provenance.StableId;
switch (curve)
{
case LineArcLineSegment2D line:
@@ -101,7 +119,7 @@ public static class LineArcProfileExtrudeEmitter
bottomUses.Add(loop.IsHole ? Use.R(eb) : Use.F(eb)); topUses.Add(loop.IsHole ? Use.R(et) : Use.F(et));
var loopId = AddLoop(b, [Use.F(eb), Use.F(es1), Use.R(et), Use.R(es0)]);
var dx = line.End.X - line.Start.X; var dy = line.End.Y - line.Start.Y; var nx = loop.IsHole ? -dy : dy; var ny = loop.IsHole ? dx : -dx;
- sideFaces.Add((loopId, SurfaceGeometry.FromPlane(new PlaneSurface(new Point3D(line.Start.X, line.Start.Y, z0), Direction3D.Create(new Vector3D(nx, ny, 0)), Direction3D.Create(new Vector3D(0, 0, 1)))), "v2-v4-line-edge-side-face-emitted"));
+ sideFaces.Add((loopId, SurfaceGeometry.FromPlane(new PlaneSurface(new Point3D(line.Start.X, line.Start.Y, z0), Direction3D.Create(new Vector3D(nx, ny, 0)), Direction3D.Create(new Vector3D(0, 0, 1)))), "v2-v4-line-edge-side-face-emitted", source, eb, et, es0, es1));
break;
}
case LineArcCircularArc2D arc:
@@ -113,7 +131,7 @@ public static class LineArcProfileExtrudeEmitter
edgeCurves[eb]=CurveGeometry.FromCircle(new Circle3Curve(new Point3D(arc.Center.X,arc.Center.Y,z0),Direction3D.Create(new Vector3D(0,0,1)),arc.Radius,Direction3D.Create(new Vector3D(1,0,0))));
edgeCurves[et]=CurveGeometry.FromCircle(new Circle3Curve(new Point3D(arc.Center.X,arc.Center.Y,z1),Direction3D.Create(new Vector3D(0,0,1)),arc.Radius,Direction3D.Create(new Vector3D(1,0,0))));
bottomUses.Add(loop.IsHole ? Use.R(eb) : Use.F(eb)); topUses.Add(loop.IsHole ? Use.R(et) : Use.F(et));
- sideFaces.Add((AddLoop(b,[Use.F(eb),Use.F(es1),Use.R(et),Use.R(es0)]), SurfaceGeometry.FromCylinder(new CylinderSurface(new Point3D(arc.Center.X,arc.Center.Y,z0),Direction3D.Create(new Vector3D(0,0,1)),arc.Radius,Direction3D.Create(new Vector3D(1,0,0)))), "v2-v4-arc-edge-side-face-emitted"));
+ sideFaces.Add((AddLoop(b,[Use.F(eb),Use.F(es1),Use.R(et),Use.R(es0)]), SurfaceGeometry.FromCylinder(new CylinderSurface(new Point3D(arc.Center.X,arc.Center.Y,z0),Direction3D.Create(new Vector3D(0,0,1)),arc.Radius,Direction3D.Create(new Vector3D(1,0,0)))), "v2-v4-arc-edge-side-face-emitted", source, eb, et, es0, es1));
break;
}
case LineArcFullCircle2D circle:
@@ -124,7 +142,7 @@ public static class LineArcProfileExtrudeEmitter
edgeCurves[et]=CurveGeometry.FromCircle(new Circle3Curve(points[vt],Direction3D.Create(new Vector3D(0,0,1)),circle.Radius,Direction3D.Create(new Vector3D(1,0,0))));
edgeCurves[es]=CurveGeometry.FromLine(new Line3Curve(points[vb],Direction3D.Create(points[vt]-points[vb])));
bottomUses.Add(loop.IsHole ? Use.R(eb) : Use.F(eb)); topUses.Add(loop.IsHole ? Use.R(et) : Use.F(et));
- sideFaces.Add((AddLoop(b,[Use.F(eb),Use.F(es),Use.R(et),Use.R(es)]), SurfaceGeometry.FromCylinder(new CylinderSurface(points[vb],Direction3D.Create(new Vector3D(0,0,1)),circle.Radius,Direction3D.Create(new Vector3D(1,0,0)))), "v2-v4-full-circle-side-face-emitted"));
+ sideFaces.Add((AddLoop(b,[Use.F(eb),Use.F(es),Use.R(et),Use.R(es)]), SurfaceGeometry.FromCylinder(new CylinderSurface(points[vb],Direction3D.Create(new Vector3D(0,0,1)),circle.Radius,Direction3D.Create(new Vector3D(1,0,0)))), "v2-v4-full-circle-side-face-emitted", source, eb, et, es, es));
break;
}
}
@@ -142,7 +160,28 @@ public static class LineArcProfileExtrudeEmitter
g.AddSurface(new SurfaceGeometryId(2), SurfaceGeometry.FromPlane(new PlaneSurface(new Point3D(0,0,z1),Direction3D.Create(new Vector3D(0,0,1)),Direction3D.Create(new Vector3D(1,0,0)))));
bind.AddFaceBinding(new FaceGeometryBinding(bottomFace, new SurfaceGeometryId(1))); bind.AddFaceBinding(new FaceGeometryBinding(topFace, new SurfaceGeometryId(2)));
var sid = 3; for (var i = 0; i < sideFaces.Count; i++) { g.AddSurface(new SurfaceGeometryId(sid), sideFaces[i].Surface); bind.AddFaceBinding(new FaceGeometryBinding(faceIds[2+i], new SurfaceGeometryId(sid))); sid++; }
- body = new BrepBody(b.Model, g, bind, points); return true;
+ body = new BrepBody(b.Model, g, bind, points);
+ if (sourceProfile is not null)
+ {
+ for (var i = 0; i < sideFaces.Count; i++)
+ {
+ var side = sideFaces[i]; if (side.Source is null) continue;
+ var prefix = $"material:{sourceProfile.Name}:{side.Source}";
+ descendants.Add(new($"{prefix}:bottom", "Edge", SemanticTopologyRole.BottomBoundary, side.Source, Edge: side.Bottom, ParentStableId: side.Source));
+ descendants.Add(new($"{prefix}:top", "Edge", SemanticTopologyRole.TopBoundary, side.Source, Edge: side.Top, ParentStableId: side.Source));
+ descendants.Add(new($"{prefix}:vertical-start", "Edge", SemanticTopologyRole.VerticalExtrusionEdge, side.Source, Edge: side.StartVertical, ParentStableId: side.Source));
+ descendants.Add(new($"{prefix}:vertical-end", "Edge", SemanticTopologyRole.VerticalExtrusionEdge, side.Source, Edge: side.EndVertical, ParentStableId: side.Source));
+ descendants.Add(new($"{prefix}:side", "Face", SemanticTopologyRole.ExtrusionSideFace, side.Source, Face: faceIds[2 + i], ParentStableId: side.Source));
+ }
+ for (var i = 0; i < sourceProfile.Loops.Count; i++)
+ {
+ var loopSource = $"profile:{sourceProfile.Name}.{sourceProfile.Loops[i].Name}";
+ descendants.Add(new($"material:{sourceProfile.Name}:{loopSource}:bottom-loop", "Loop", SemanticTopologyRole.BottomFaceBoundaryLoop, loopSource, Loop: bottomLoops[i], ParentStableId: loopSource));
+ descendants.Add(new($"material:{sourceProfile.Name}:{loopSource}:top-loop", "Loop", SemanticTopologyRole.TopFaceBoundaryLoop, loopSource, Loop: topLoops[i], ParentStableId: loopSource));
+ }
+ correspondence = new(sourceProfile.Name, descendants, ["Profile", "ResolvedProfile2D", "LineArcProfileExtrude", "AuthoritativeBRepPlan"]);
+ }
+ return true;
}
private static LoopId AddLoop(TopologyBuilder b, IReadOnlyList<Use> uses){ var lid=b.AllocateLoopId(); var cids=uses.Select(_=>b.AllocateCoedgeId()).ToArray(); for(var i=0;i<uses.Count;i++){var n=cids[(i+1)%cids.Length];var p=cids[(i+cids.Length-1)%cids.Length]; b.AddCoedge(new Coedge(cids[i],uses[i].Edge,lid,n,p,uses[i].Rev));} b.AddLoop(new Loop(lid,cids)); return lid; }
diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs
index 1985f5e0..6d0c3a7b 100644
--- a/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs
@@ -7,8 +7,8 @@ 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);
+public sealed record PrismaticSectionStackBrepPlan(string Signature, int Vertices, int Edges, int Faces, string Policy, bool Authoritative, SemanticTopologyCorrespondence? Correspondence = null);
+public sealed record PrismaticSectionStackEmissionResult(BrepBody? Body, PrismaticSectionStackBrepPlan? Plan, IReadOnlyList<string> Diagnostics, SemanticTopologyCorrespondence? Correspondence = null);
/// <summary>Normalizes bounded line/arc Profiles through a planar material arrangement into slabs.</summary>
public static class PrismaticSectionStackCompiler
@@ -80,7 +80,7 @@ public static class PrismaticSectionStackEmitter
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 sideFaces = new List<(LoopId Loop, SurfaceGeometry Surface, string Source, string Construction, double From, double To)>(); var capFaces = new List<(FaceId Face, double Z, bool Up)>();
var splitPoints = stack.Slabs.SelectMany(s => Loops(s.Region)).Concat(stack.Transitions.SelectMany(t =>
t.UpwardRegions.Concat(t.DownwardRegions).SelectMany(Loops)))
.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();
@@ -106,7 +106,8 @@ public static class PrismaticSectionStackEmitter
{
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)));
+ var source = SourceId(segment.Provenance.StableId);
+ sideFaces.Add((loop, SideSurface(curve, slab.From, item.IsHole), source, $"slab:{slab.From:R}..{slab.To:R}:{segment.Provenance.Derivation}", slab.From, slab.To));
}
foreach (var transition in stack.Transitions)
{
@@ -136,9 +137,35 @@ public static class PrismaticSectionStackEmitter
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);
+ var descendants = new List<SemanticTopologyDescendant>();
+ var topLevels = stack.Feature.Operations.GroupBy(x => x.ProfileReference, StringComparer.Ordinal).ToDictionary(x => x.Key, x => x.Max(y => y.To), StringComparer.Ordinal);
+ var bottomLevels = stack.Feature.Operations.GroupBy(x => x.ProfileReference, StringComparer.Ordinal).ToDictionary(x => x.Key, x => x.Min(y => y.From), StringComparer.Ordinal);
+ for (var i = 0; i < sideFaces.Count; i++)
+ {
+ var side = sideFaces[i]; var face = faces[capFaces.Count + i]; var loop = builder.Model.Loops.Single(x => x.Id == side.Loop);
+ foreach (var coedgeId in loop.CoedgeIds)
+ {
+ var coedge = builder.Model.Coedges.Single(x => x.Id == coedgeId);
+ var edge = builder.Model.Edges.Single(x => x.Id == coedge.EdgeId);
+ // Horizontal uses are cap/boundary descendants; vertical uses are side descendants.
+ var horizontal = Math.Abs(points[edge.StartVertexId].Z - points[edge.EndVertexId].Z) <= Tol;
+ if (!horizontal) continue;
+ var z = points[edge.StartVertexId].Z;
+ var profile = side.Source.StartsWith("profile:", StringComparison.Ordinal) ? side.Source["profile:".Length..].Split('.')[0] : string.Empty;
+ if (Math.Abs(z - side.To) <= Tol && topLevels.TryGetValue(profile, out var topLevel) && Math.Abs(z - topLevel) <= Tol) descendants.Add(new($"plan:{stack.Feature.Name}:{side.Construction}:edge:{edge.Id.Value}:top", "Edge", SemanticTopologyRole.TopBoundary, side.Source, Edge: edge.Id, ParentStableId: side.Construction));
+ if (Math.Abs(z - side.From) <= Tol && bottomLevels.TryGetValue(profile, out var bottomLevel) && Math.Abs(z - bottomLevel) <= Tol) descendants.Add(new($"plan:{stack.Feature.Name}:{side.Construction}:edge:{edge.Id.Value}:bottom", "Edge", SemanticTopologyRole.BottomBoundary, side.Source, Edge: edge.Id, ParentStableId: side.Construction));
+ }
+ descendants.Add(new($"plan:{stack.Feature.Name}:{side.Construction}:face:{face.Value}", "Face", SemanticTopologyRole.ExtrusionSideFace, side.Source, Face: face, ParentStableId: side.Construction));
+ }
+ foreach (var fragment in stack.Slabs.Where(s => s.Arrangement is not null).SelectMany(s => s.Arrangement!.AtomicFragments))
+ {
+ var source = fragment.Source.Provenance.StableId;
+ descendants.Add(new($"construction:{stack.Feature.Name}:{fragment.StableId}", "ArrangementFragment", SemanticTopologyRole.Unknown, source, ParentStableId: fragment.Source.StableId));
+ }
+ var correspondence = new SemanticTopologyCorrespondence(stack.Feature.Name, descendants.DistinctBy(x => x.StableId).ToArray(), ["ProfileArrangement2D", "PrismaticSectionStackConstruction", "PrismaticSectionStackBrepPlan", "AuthoritativeBRepPlan"]);
+ 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, correspondence);
d.Add("compose-authoritative-section-stack-brep-plan"); d.Add("compose-no-3d-boolean-used");
- return new(body, plan, d.Distinct().ToArray());
+ return new(body, plan, d.Distinct().ToArray(), correspondence);
}
private static FaceId AddCap(TopologyBuilder builder, PrismaticSectionRegion region, double z, Func<LineArcProfileCurve2D, double, (EdgeId Edge, bool Reverse)> edge, IReadOnlyList<(double X, double Y)> splitPoints)
{
@@ -174,6 +201,12 @@ public static class PrismaticSectionStackEmitter
};
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 string SourceId(string stableId)
+ {
+ const string marker = ".arrangement.";
+ var index = stableId.IndexOf(marker, StringComparison.Ordinal);
+ return index >= 0 ? stableId[..index] : stableId;
+ }
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),
diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileHoleExtrudeEmitter.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileHoleExtrudeEmitter.cs
index 545645f0..a5437768 100644
--- a/Aetheris.Kernel.Firmament/Materializer/ProfileHoleExtrudeEmitter.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileHoleExtrudeEmitter.cs
@@ -13,7 +13,8 @@ internal sealed record ProfileHoleExtrudeRequest(
double Width,
double Depth,
double Height,
- IReadOnlyList<ProfileHoleLoop2D> Holes);
+ IReadOnlyList<ProfileHoleLoop2D> Holes,
+ IReadOnlyList<string>? HoleStableIds = null);
internal enum ProfileHoleExtrudeStatus
{
@@ -25,7 +26,8 @@ internal enum ProfileHoleExtrudeStatus
internal sealed record ProfileHoleExtrudeResult(
ProfileHoleExtrudeStatus Status,
BrepBody? Body,
- IReadOnlyList<string> Diagnostics);
+ IReadOnlyList<string> Diagnostics,
+ SemanticTopologyCorrespondence? Correspondence = null);
internal static class ProfileHoleExtrudeEmitter
{
@@ -47,7 +49,7 @@ internal static class ProfileHoleExtrudeEmitter
}
d.Add("v2-v1-profile-hole-extrude-succeeded");
- return new(ProfileHoleExtrudeStatus.Succeeded, built.Body, d);
+ return new(ProfileHoleExtrudeStatus.Succeeded, built.Body, d, built.Correspondence);
}
private static bool TryValidate(ProfileHoleExtrudeRequest req, List<string> d)
@@ -92,7 +94,7 @@ internal static class ProfileHoleExtrudeEmitter
return true;
}
- private static (bool IsSuccess, BrepBody? Body, string Diagnostic) BuildBody(ProfileHoleExtrudeRequest request)
+ private static (bool IsSuccess, BrepBody? Body, string Diagnostic, SemanticTopologyCorrespondence? Correspondence) BuildBody(ProfileHoleExtrudeRequest request)
{
var minX = -request.Width / 2d;
var maxX = request.Width / 2d;
@@ -188,7 +190,18 @@ internal static class ProfileHoleExtrudeEmitter
bind.AddFaceBinding(new FaceGeometryBinding(faces[4], new SurfaceGeometryId(5)));
bind.AddFaceBinding(new FaceGeometryBinding(faces[5], new SurfaceGeometryId(6)));
for (var i = 0; i < holeCount; i++) bind.AddFaceBinding(new FaceGeometryBinding(faces[6 + i], new SurfaceGeometryId(7 + i)));
- return (true, new BrepBody(b.Model, g, bind, map), string.Empty);
+ var body = new BrepBody(b.Model, g, bind, map);
+ var descendants = new List<SemanticTopologyDescendant>();
+ for (var i = 0; i < holeCount; i++)
+ {
+ var source = request.HoleStableIds is { Count: > 0 } && i < request.HoleStableIds.Count ? request.HoleStableIds[i] : $"hole:{i}";
+ descendants.Add(new($"material:{source}:entry-edge", "Edge", SemanticTopologyRole.TopBoundary, source, Edge: hte[i], ParentStableId: source));
+ descendants.Add(new($"material:{source}:exit-edge", "Edge", SemanticTopologyRole.BottomBoundary, source, Edge: hbe[i], ParentStableId: source));
+ descendants.Add(new($"material:{source}:entry-loop", "Loop", SemanticTopologyRole.HoleEntryLoop, source, Loop: topLoops[i + 1], ParentStableId: source));
+ descendants.Add(new($"material:{source}:exit-loop", "Loop", SemanticTopologyRole.HoleExitLoop, source, Loop: bottomLoops[i + 1], ParentStableId: source));
+ descendants.Add(new($"material:{source}:wall", "Face", SemanticTopologyRole.HoleWallFace, source, Face: faces[6 + i], ParentStableId: source));
+ }
+ return (true, body, string.Empty, new SemanticTopologyCorrespondence("ProfileHoleExtrude", descendants, ["HoleAIR", "ProfileHoleExtrude", "AuthoritativeBRepPlan"]));
}
private static LoopId AddLoop(TopologyBuilder b, IReadOnlyList<Use> uses)
diff --git a/Aetheris.Kernel.Firmament/Materializer/ResolvedProfile2D.cs b/Aetheris.Kernel.Firmament/Materializer/ResolvedProfile2D.cs
index d68463ba..86cb0bc5 100644
--- a/Aetheris.Kernel.Firmament/Materializer/ResolvedProfile2D.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/ResolvedProfile2D.cs
@@ -37,7 +37,7 @@ public static class ResolvedProfile2DValidator
public static LineArcProfileExtrudeResult Extrude(ResolvedProfile2D profile,double height)
{
var validation=Validate(profile); if(!validation.IsValid)return new(LineArcProfileExtrudeStatus.Rejected,null,validation.Diagnostics);
- return LineArcProfileExtrudeEmitter.TryEmit(new(profile.Loops.Select(l=>new LineArcProfileLoop2D(l.Segments.Select(s=>s.Geometry).ToArray(),!l.IsOuter)).ToArray(),height));
+ return LineArcProfileExtrudeEmitter.TryEmit(profile, height);
}
private static bool Endpoints(LineArcProfileCurve2D c,out (double X,double Y) a,out (double X,double Y) b){switch(c){case LineArcLineSegment2D l:a=l.Start;b=l.End;return true;case LineArcCircularArc2D x:a=(x.Center.X+x.Radius*Math.Cos(x.StartAngleRadians),x.Center.Y+x.Radius*Math.Sin(x.StartAngleRadians));b=(x.Center.X+x.Radius*Math.Cos(x.StartAngleRadians+x.SweepAngleRadians),x.Center.Y+x.Radius*Math.Sin(x.StartAngleRadians+x.SweepAngleRadians));return true;default:a=default;b=default;return false;}}
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/SemanticTopologySelections.cs b/Aetheris.Kernel.Firmament/Materializer/SemanticTopologySelections.cs
new file mode 100644
index 00000000..79c09d81
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Materializer/SemanticTopologySelections.cs
@@ -0,0 +1,160 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Topology;
+using System.Text.RegularExpressions;
+
+namespace Aetheris.Kernel.Firmament.Materializer;
+
+/// <summary>Stable roles assigned while an authoritative plan is materialized. These are not geometric queries.</summary>
+public enum SemanticTopologyRole { Unknown, ProfileVertex, VerticalExtrusionEdge, TopBoundary, BottomBoundary, ExtrusionSideFace, TopFaceBoundaryLoop, BottomFaceBoundaryLoop, HoleEntryLoop, HoleExitLoop, HoleWallFace, ComposeTransition }
+public enum SemanticSelectionRequirement { ExactlyOne, OneOrMore, ConnectedChain, ClosedLoop, NonEmptyFaceSet }
+public enum SemanticSelectionFailure { None, SemanticSourceNotFound, NoMaterializedDescendants, AmbiguousBodyContext, SelectionCardinalityMismatch, DescendantsNotConnected, DescendantsBranch, DescendantsDoNotClose, MixedBoundaryRoles, UnsupportedTopologyChange, SelectionConsumerMismatch }
+
+/// <summary>Immutable public materialization evidence. The opaque materialized id is diagnostic data, never authoring syntax.</summary>
+public sealed record SemanticTopologyDescendant(
+ string StableId, string Kind, SemanticTopologyRole Role, string SourceStableId,
+ EdgeId? Edge = null, FaceId? Face = null, LoopId? Loop = null, VertexId? Vertex = null,
+ string? ParentStableId = null, string? GeometryPreview = null);
+
+public sealed record SemanticTopologyCorrespondence(
+ string BodyStableId,
+ IReadOnlyList<SemanticTopologyDescendant> Descendants,
+ IReadOnlyList<string> ProvenanceChain)
+{
+ public IReadOnlyList<SemanticTopologyDescendant> FromSources(IEnumerable<string> sources, SemanticTopologyRole? role) =>
+ Descendants.Where(x => sources.Contains(x.SourceStableId, StringComparer.Ordinal) && (role is null || x.Role == role)).ToArray();
+}
+
+public sealed record SemanticSelectionRequest(
+ string StableId, string Label, string BodyStableId, IReadOnlyList<string> SourceStableIds,
+ SemanticTopologyRole? Role, SemanticSelectionRequirement Require, string SourceSpan, string Consumer = "inspection");
+public sealed record SemanticSelectionDiagnostic(string Code, string Message, string SourceSpan, IReadOnlyList<string> ProvenanceChain);
+public sealed record SemanticSelectionResolution(
+ bool Succeeded, SemanticSelectionFailure Failure, SemanticSelectionRequest Request,
+ IReadOnlyList<SemanticTopologyDescendant> Descendants, IReadOnlyList<SemanticTopologyDescendant> OrderedChain,
+ bool IsConnected, bool IsClosed, IReadOnlyList<SemanticSelectionDiagnostic> Diagnostics);
+
+/// <summary>Source-grounded resolver. It only consumes plan/materialization correspondence emitted by the producer.</summary>
+public static class SemanticTopologySelectionResolver
+{
+ public static SemanticSelectionResolution Resolve(BrepBody body, SemanticTopologyCorrespondence correspondence, SemanticSelectionRequest request)
+ {
+ SemanticSelectionResolution Fail(SemanticSelectionFailure failure, string code, string message, IReadOnlyList<SemanticTopologyDescendant>? descendants = null) =>
+ new(false, failure, request, descendants ?? [], [], false, false,
+ [new(code, message, request.SourceSpan, correspondence.ProvenanceChain)]);
+ if (!string.Equals(request.BodyStableId, correspondence.BodyStableId, StringComparison.Ordinal))
+ return Fail(SemanticSelectionFailure.AmbiguousBodyContext, "AmbiguousBodyContext", $"Requested body '{request.BodyStableId}' does not own this correspondence.");
+ if (request.SourceStableIds.Count == 0)
+ return Fail(SemanticSelectionFailure.SemanticSourceNotFound, "SemanticSourceNotFound", "Selection has no authored semantic sources.");
+ var known = correspondence.Descendants.Select(x => x.SourceStableId).ToHashSet(StringComparer.Ordinal);
+ var missing = request.SourceStableIds.Where(x => !known.Contains(x)).ToArray();
+ if (missing.Length > 0)
+ return Fail(SemanticSelectionFailure.SemanticSourceNotFound, "SemanticSourceNotFound", $"No provenance source for: {string.Join(", ", missing)}.");
+ var candidates = correspondence.FromSources(request.SourceStableIds, request.Role);
+ if (candidates.Count == 0)
+ return Fail(SemanticSelectionFailure.NoMaterializedDescendants, "NoMaterializedDescendants", "The selected authored source has no descendants with the requested topology role.");
+ if (request.Require == SemanticSelectionRequirement.ExactlyOne && candidates.Count != 1)
+ return Fail(SemanticSelectionFailure.SelectionCardinalityMismatch, "SelectionCardinalityMismatch", $"Expected exactly one descendant; found {candidates.Count}.", candidates);
+ if (request.Require == SemanticSelectionRequirement.NonEmptyFaceSet && !candidates.Any(x => x.Face is not null))
+ return Fail(SemanticSelectionFailure.SelectionConsumerMismatch, "SelectionConsumerMismatch", "NonEmptyFaceSet requires face descendants.", candidates);
+ if (request.Require is not (SemanticSelectionRequirement.ConnectedChain or SemanticSelectionRequirement.ClosedLoop))
+ return new(true, SemanticSelectionFailure.None, request, candidates, [], false, false, []);
+ if (request.Require == SemanticSelectionRequirement.ClosedLoop && candidates.All(x => x.Loop is not null))
+ {
+ foreach (var candidate in candidates)
+ {
+ var loop = body.Topology.Loops.Single(x => x.Id == candidate.Loop!.Value);
+ if (loop.CoedgeIds.Count < 3) return Fail(SemanticSelectionFailure.DescendantsDoNotClose, "DescendantsDoNotClose", "A loop descendant is degenerate.", candidates);
+ var uses = loop.CoedgeIds.Select(id => body.Topology.Coedges.Single(x => x.Id == id)).Select(c => DirectedEdgeUse.Resolve(body.Topology.Edges.Single(e => e.Id == c.EdgeId), c)).ToArray();
+ if (uses.Where((use, index) => use.EndVertexId != uses[(index + 1) % uses.Length].StartVertexId).Any())
+ return Fail(SemanticSelectionFailure.DescendantsDoNotClose, "DescendantsDoNotClose", "A loop descendant does not have directed closure.", candidates);
+ }
+ return new(true, SemanticSelectionFailure.None, request, candidates, candidates, true, true, []);
+ }
+ if (candidates.Any(x => x.Edge is null))
+ return Fail(SemanticSelectionFailure.SelectionConsumerMismatch, "SelectionConsumerMismatch", "Chain and loop requirements require edge descendants.", candidates);
+ var duplicate = candidates.GroupBy(x => x.Edge!.Value).FirstOrDefault(x => x.Count() > 1);
+ if (duplicate is not null)
+ return Fail(SemanticSelectionFailure.DescendantsBranch, "DescendantsBranch", "A descendant edge appears more than once.", candidates);
+ var edges = candidates.Select(x => (Descendant: x, Edge: body.Topology.Edges.Single(e => e.Id == x.Edge!.Value))).ToArray();
+ var incident = new Dictionary<VertexId, List<(SemanticTopologyDescendant Descendant, Edge Edge)>>();
+ foreach (var item in edges)
+ {
+ // DirectedEdgeUse is the shared convention even when the source segment's orientation is not required.
+ var use = DirectedEdgeUse.Resolve(item.Edge, false);
+ foreach (var vertex in new[] { use.StartVertexId, use.EndVertexId })
+ {
+ if (!incident.TryGetValue(vertex, out var list)) incident[vertex] = list = [];
+ list.Add(item);
+ }
+ }
+ if (incident.Values.Any(x => x.Count > 2))
+ return Fail(SemanticSelectionFailure.DescendantsBranch, "DescendantsBranch", "A selected descendant vertex has more than two incident selected edges.", candidates);
+ var visited = new HashSet<EdgeId>(); var queue = new Queue<VertexId>(); queue.Enqueue(incident.Keys.MinBy(x => x.Value));
+ while (queue.Count > 0) foreach (var item in incident[queue.Dequeue()]) if (visited.Add(item.Edge.Id))
+ {
+ var use = DirectedEdgeUse.Resolve(item.Edge, false); queue.Enqueue(use.StartVertexId); queue.Enqueue(use.EndVertexId);
+ }
+ if (visited.Count != edges.Length)
+ return Fail(SemanticSelectionFailure.DescendantsNotConnected, "DescendantsNotConnected", "Selected descendants are not one connected component.", candidates);
+ var closed = incident.Values.All(x => x.Count == 2);
+ if (request.Require == SemanticSelectionRequirement.ClosedLoop && !closed)
+ return Fail(SemanticSelectionFailure.DescendantsDoNotClose, "DescendantsDoNotClose", "Selected descendants do not return to their first vertex.", candidates);
+ if (request.Require == SemanticSelectionRequirement.ConnectedChain && closed)
+ return Fail(SemanticSelectionFailure.SelectionCardinalityMismatch, "SelectionCardinalityMismatch", "ConnectedChain requires an open chain; the descendants form a closed loop.", candidates);
+ var start = closed ? incident.Keys.MinBy(x => x.Value) : incident.Where(x => x.Value.Count == 1).OrderBy(x => x.Key.Value).First().Key;
+ var ordered = new List<SemanticTopologyDescendant>(); var previous = default(EdgeId?); var current = start;
+ while (ordered.Count < edges.Length)
+ {
+ var next = incident[current].Where(x => previous is null || x.Edge.Id != previous.Value).OrderBy(x => x.Descendant.StableId, StringComparer.Ordinal).First();
+ ordered.Add(next.Descendant); previous = next.Edge.Id;
+ var use = DirectedEdgeUse.Resolve(next.Edge, false); current = use.StartVertexId == current ? use.EndVertexId : use.StartVertexId;
+ }
+ return new(true, SemanticSelectionFailure.None, request, candidates, ordered, true, closed, []);
+ }
+}
+
+public sealed record VertexSet(SemanticSelectionResolution Resolution);
+public sealed record EdgeSet(SemanticSelectionResolution Resolution);
+public sealed record FaceSet(SemanticSelectionResolution Resolution);
+public sealed record LoopSet(SemanticSelectionResolution Resolution) { public bool IsExplicitlyClosed => Resolution.IsClosed; }
+public sealed record Chain(SemanticSelectionResolution Resolution) { public IReadOnlyList<SemanticTopologyDescendant> OrderedEdges => Resolution.OrderedChain; }
+
+/// <summary>Deliberately bounded Firmament surface: named Profile members plus a boundary role and shape contract.</summary>
+public static class SemanticSelectionSourceParser
+{
+ private static readonly Regex Header = new(@"\bSelection\s+(?<name>\w+)\s*\{", RegexOptions.CultureInvariant);
+ private static readonly Regex Source = new(@"\bSource\s*:\s*(?<profile>\w+)\.ProfileSegments\s*\(\s*\[(?<members>[\w\s,]+)\]\s*\)", RegexOptions.Singleline | RegexOptions.CultureInvariant);
+ private static readonly Regex LoopSource = new(@"\bSource\s*:\s*(?<profile>\w+)\.ProfileLoop\s*\(\s*(?<loop>\w+)\s*\)", RegexOptions.Singleline | RegexOptions.CultureInvariant);
+ private static readonly Regex Target = new(@"\bTarget\s*:\s*(?<role>TopBoundary|BottomBoundary|SideBoundary)", RegexOptions.CultureInvariant);
+ private static readonly Regex Require = new(@"\bRequire\s*:\s*(?<shape>ExactlyOne|OneOrMore|ConnectedChain|ClosedLoop|NonEmptyFaceSet)", RegexOptions.CultureInvariant);
+
+ public static IReadOnlyList<SemanticSelectionRequest> Parse(string source, ResolvedProfile2D profile, string bodyStableId, out IReadOnlyList<string> diagnostics)
+ {
+ var output = new List<SemanticSelectionRequest>(); var errors = new List<string>();
+ foreach (Match header in Header.Matches(source))
+ {
+ var body = Block(source, header.Index + header.Length - 1);
+ if (body is null) { errors.Add($"selection-unclosed:{header.Groups["name"].Value}"); continue; }
+ var sourceMatches = Source.Matches(body); var loopMatch = LoopSource.Match(body); var target = Target.Match(body); var require = Require.Match(body);
+ if (!target.Success || !require.Success || (sourceMatches.Count == 0 && !loopMatch.Success)) { errors.Add($"selection-invalid:{header.Groups["name"].Value}"); continue; }
+ var boundary = target.Groups["role"].Value;
+ var role = loopMatch.Success
+ ? boundary switch { "TopBoundary" => SemanticTopologyRole.TopFaceBoundaryLoop, "BottomBoundary" => SemanticTopologyRole.BottomFaceBoundaryLoop, _ => SemanticTopologyRole.ExtrusionSideFace }
+ : boundary switch { "TopBoundary" => SemanticTopologyRole.TopBoundary, "BottomBoundary" => SemanticTopologyRole.BottomBoundary, _ => SemanticTopologyRole.ExtrusionSideFace };
+ var sources = sourceMatches.Count > 0
+ ? sourceMatches.SelectMany(match => match.Groups["members"].Value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Select(x => $"profile:{match.Groups["profile"].Value}.Outer.{x}")).ToArray()
+ : [$"profile:{loopMatch.Groups["profile"].Value}.{loopMatch.Groups["loop"].Value}"];
+ // Compose selections may name any one of the parsed profiles; body context is checked by the resolver.
+ output.Add(new($"selection:{header.Groups["name"].Value}", header.Groups["name"].Value, bodyStableId, sources, role,
+ Enum.Parse<SemanticSelectionRequirement>(require.Groups["shape"].Value), $"offset:{header.Index}", "EdgeFinish"));
+ }
+ diagnostics = errors; return output;
+ }
+
+ 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.Server.Tests/KernelApiIntegrationTests.cs b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
index 94b96037..1f82d5e0 100644
--- a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
+++ b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
@@ -875,6 +875,26 @@ public sealed class KernelApiIntegrationTests : IClassFixture<WebApplicationFact
return prepared;
}
+ [Theory]
+ [InlineData("semantic-shaft-hole", "hole:base.mount")]
+ [InlineData("split-compose-chamfer", "profile:BaseProfile.Outer.South")]
+ [InlineData("ctc-01-x3", "profile:CentralHex.Outer.SouthEast")]
+ public async Task CadmataFixture_LoadsCompilerBodyAndPublishedCorrespondence(string fixtureId, string expectedEntityId)
+ {
+ var document = await CreateDocumentAsync("/api/v1/documents");
+ var response = await _client.PostAsync($"/api/v1/documents/{document.Data!.DocumentId}/cadmata/fixtures/{fixtureId}", null);
+ response.EnsureSuccessStatusCode();
+ var loaded = await response.Content.ReadFromJsonAsync<ApiResponseDto<CadmataFixtureLoadResponseDto>>();
+
+ Assert.NotNull(loaded);
+ Assert.True(loaded!.Success);
+ Assert.NotNull(loaded.Data);
+ Assert.Equal("cadmata-concept-viz-x1", loaded.Data!.Visualization.SchemaVersion);
+ Assert.Contains(loaded.Data.Visualization.Entities, entity => entity.StableId == expectedEntityId);
+ Assert.True(loaded.Data.Visualization.Metrics["faceCount"] > 0);
+ Assert.True(Guid.TryParse(loaded.Data.BodyId, out _));
+ }
+
private static string GetRepositoryPath(string relativePath)
=> Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", relativePath));
diff --git a/Aetheris.Server/Aetheris.Server.csproj b/Aetheris.Server/Aetheris.Server.csproj
index 12882426..f3b31072 100644
--- a/Aetheris.Server/Aetheris.Server.csproj
+++ b/Aetheris.Server/Aetheris.Server.csproj
@@ -18,6 +18,7 @@
<ItemGroup>
<ProjectReference Include="..\Aetheris.Kernel.Core\Aetheris.Kernel.Core.csproj" />
+ <ProjectReference Include="..\Aetheris.Kernel.Firmament\Aetheris.Kernel.Firmament.csproj" />
</ItemGroup>
</Project>
diff --git a/Aetheris.Server/Api/CadmataFixtureService.cs b/Aetheris.Server/Api/CadmataFixtureService.cs
new file mode 100644
index 00000000..6ef77772
--- /dev/null
+++ b/Aetheris.Server/Api/CadmataFixtureService.cs
@@ -0,0 +1,96 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.Materializer;
+using Aetheris.Server.Contracts;
+using Aetheris.Server.Documents;
+
+namespace Aetheris.Server.Api;
+
+/// <summary>Development fixture bridge. Geometry and topology ids come from the same materializers used by the compiler; no browser-side BRep matching occurs.</summary>
+internal static class CadmataFixtureService
+{
+ private static readonly IReadOnlyDictionary<string, string> FixturePaths = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
+ {
+ ["direct-profile"] = "fixtures/FirmamentV2/Profile/valid/scaffold-rectangle.firmament",
+ ["split-compose-chamfer"] = "fixtures/FirmamentV2/ProfileComposition/valid/semantic-split-compose-chamfer.firmament",
+ ["semantic-shaft-hole"] = "fixtures/FirmamentV2/Hole/valid/semantic-shaft-selection.firmament",
+ ["ctc-01-x3"] = "testdata/firmament/reconstructions/nist_ctc_01/ctc01_prismatic_blockout_x3.firmament",
+ };
+
+ public static bool TryLoad(string fixtureId, DocumentSession document, out CadmataFixtureLoadResponseDto? response, out string error)
+ {
+ response = null; error = string.Empty;
+ if (!FixturePaths.TryGetValue(fixtureId, out var relative)) { error = $"Cadmata fixture '{fixtureId}' is not available."; return false; }
+ var sourcePath = Path.Combine(FindRepositoryRoot(), relative);
+ if (!File.Exists(sourcePath)) { error = $"Cadmata fixture source is unavailable: {relative}."; return false; }
+ var source = File.ReadAllText(sourcePath);
+ BrepBody? body = null; SemanticTopologyCorrespondence? correspondence = null; IReadOnlyList<ResolvedProfile2D> profiles = [];
+ var diagnostics = new List<string>();
+ if (fixtureId == "semantic-shaft-hole")
+ {
+ var parsed = FirmamentV2Parser.Parse(source, Path.GetDirectoryName(sourcePath));
+ if (!parsed.IsSuccess || parsed.Document is null) { error = string.Join("; ", parsed.Diagnostics); return false; }
+ var inspected = SemanticHoleInspection.Inspect(parsed.Document);
+ body = inspected.Body; correspondence = inspected.Correspondence; diagnostics.AddRange(inspected.Diagnostics);
+ }
+ else if (PrismaticProfileCompositionParser.IsCompositionSource(source))
+ {
+ var parsed = PrismaticProfileCompositionParser.Parse(source);
+ var stack = PrismaticSectionStackCompiler.Normalize(parsed, out var normalizationDiagnostics);
+ if (stack is null) { error = string.Join("; ", normalizationDiagnostics); return false; }
+ var emitted = PrismaticSectionStackEmitter.Emit(stack);
+ body = emitted.Body; correspondence = emitted.Correspondence; profiles = parsed.Profiles.Values.ToArray(); diagnostics.AddRange(emitted.Diagnostics);
+ }
+ else
+ {
+ var parsed = ProfileAuthoringParser.Parse(source);
+ if (parsed.Profile is null) { error = string.Join("; ", parsed.Diagnostics); return false; }
+ var emitted = ResolvedProfile2DValidator.Extrude(parsed.Profile, parsed.Height);
+ body = emitted.Body; correspondence = emitted.Correspondence; profiles = [parsed.Profile]; diagnostics.AddRange(emitted.Diagnostics);
+ }
+ if (body is null) { error = "The compiler did not materialize a body for this Cadmata fixture."; return false; }
+ var added = document.AddBody(body, $"Cadmata: {fixtureId}");
+ var artifact = BuildArtifact(fixtureId, relative, profiles, correspondence, diagnostics, body);
+ response = new(document.Id.ToString(), added.OccurrenceId.ToString(), added.DefinitionId.ToString(), fixtureId, artifact);
+ return true;
+ }
+
+ private static CadmataVisualizationArtifactDto BuildArtifact(string fixtureId, string sourcePath, IReadOnlyList<ResolvedProfile2D> profiles, SemanticTopologyCorrespondence? correspondence, IReadOnlyList<string> diagnostics, BrepBody body)
+ {
+ var entities = new List<CadmataVisualizationEntityDto>();
+ foreach (var profile in profiles)
+ foreach (var segment in profile.Loops.SelectMany(loop => loop.Segments))
+ {
+ var guideId = segment.Provenance.ConceptStableId;
+ entities.Add(new(guideId, "ConceptGuide", guideId.Replace("concept:", "", StringComparison.Ordinal), "profileGuides", "ConstructionGuide", Geometry(segment.Geometry), segment.Provenance.SourceSpan, null, [segment.Provenance.StableId], null, null, null, null, null, null, null));
+ var descendants = correspondence?.Descendants.Where(d => d.SourceStableId == segment.Provenance.StableId).ToArray() ?? [];
+ entities.Add(new(segment.Provenance.StableId, "ProfileSegment", segment.Name, "profileLoops", "ProfileBoundary", Geometry(segment.Geometry), segment.Provenance.SourceSpan, [guideId], null, descendants.Where(d => d.Kind == "ArrangementFragment").Select(d => d.StableId).ToArray(), descendants.Where(d => d.Kind != "ArrangementFragment").Select(d => d.StableId).ToArray(), null, null, null, null, new Dictionary<string, string> { ["derivation"] = segment.Provenance.Derivation }));
+ }
+ if (fixtureId == "semantic-shaft-hole")
+ {
+ const string id = "hole:base.mount";
+ entities.Add(new(id, "HoleFeature", "mount", "conceptAxes", "SemanticHole", new("circle", Center: new(1.5, -1, 5), Radius: 2), "offset:0", null, null, null, correspondence?.Descendants.Select(d => d.StableId).ToArray(), null, null, "AirHoleSimpleShaftMaterializer", null, new Dictionary<string, string> { ["diameter"] = "4 mm", ["axis"] = "+Z", ["endCondition"] = "throughAll" }));
+ entities.Add(new("concept:base.mount.axis", "ConceptAxis", "mount axis", "conceptAxes", "HoleAxis", new("polyline", [new(1.5, -1, -5), new(1.5, -1, 5)]), "offset:0", [id], null, null, null, null, null, null, null, null));
+ }
+ foreach (var descendant in correspondence?.Descendants ?? [])
+ {
+ entities.Add(new(descendant.StableId, $"BRep{descendant.Kind}", descendant.Role.ToString(), descendant.Kind == "Face" ? "selections" : "brepEdges", descendant.Role.ToString(), null, null, [descendant.SourceStableId], null, null, null, new(descendant.Face is { } face ? [face.Value] : null, descendant.Edge is { } edge ? [edge.Value] : null, descendant.Loop is { } loop ? [loop.Value] : null, descendant.Vertex is { } vertex ? [vertex.Value] : null), null, null, null, null));
+ }
+ var selectionSourceIds = fixtureId == "semantic-shaft-hole" ? new[] { "hole:base.mount" } : entities.Where(e => e.Kind == "ProfileSegment").Select(e => e.StableId).ToArray();
+ var selection = new CadmataVisualizationSelectionDto($"selection:{fixtureId}", fixtureId == "semantic-shaft-hole" ? "mount semantic shaft" : "compiler-published profile boundary", fixtureId == "semantic-shaft-hole" ? "FaceSet" : "LoopSet", selectionSourceIds, selectionSourceIds, fixtureId != "semantic-shaft-hole", []);
+ return new("cadmata-concept-viz-x1", fixtureId, sourcePath, entities, [selection], diagnostics.Select(d => new CadmataVisualizationDiagnosticDto("Compiler.Trace", d, "info")).ToArray(), new Dictionary<string, double> { ["entityCount"] = entities.Count, ["faceCount"] = body.Topology.Faces.Count(), ["edgeCount"] = body.Topology.Edges.Count() });
+ }
+ private static CadmataGeometryDto Geometry(LineArcProfileCurve2D curve) => curve switch
+ {
+ LineArcLineSegment2D line => new("polyline", [new(line.Start.X, line.Start.Y, 0), new(line.End.X, line.End.Y, 0)]),
+ LineArcCircularArc2D arc => new("polyline", ArcPoints(arc)),
+ _ => new("polyline", []),
+ };
+ private static IReadOnlyList<CadmataPointDto> ArcPoints(LineArcCircularArc2D arc) => Enumerable.Range(0, 25).Select(i => { var a = arc.StartAngleRadians + arc.SweepAngleRadians * i / 24d; return new CadmataPointDto(arc.Center.X + arc.Radius * Math.Cos(a), arc.Center.Y + arc.Radius * Math.Sin(a), 0); }).ToArray();
+ private static string FindRepositoryRoot()
+ {
+ var directory = new DirectoryInfo(Directory.GetCurrentDirectory());
+ while (directory is not null) { if (File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) return directory.FullName; directory = directory.Parent; }
+ throw new InvalidOperationException("Aetheris repository root was not found.");
+ }
+}
diff --git a/Aetheris.Server/Api/KernelEndpoints.cs b/Aetheris.Server/Api/KernelEndpoints.cs
index 5e4f5b04..e4173978 100644
--- a/Aetheris.Server/Api/KernelEndpoints.cs
+++ b/Aetheris.Server/Api/KernelEndpoints.cs
@@ -31,6 +31,12 @@ public static class KernelEndpoints
return ApiMappings.Ok(new DocumentCreateResponseDto(created.Id, created.Name, Volatile: true));
});
+ documents.MapPost("/{documentId:guid}/cadmata/fixtures/{fixtureId}", (Guid documentId, string fixtureId, KernelDocumentStore store) =>
+ WithDocument(store, documentId, document =>
+ CadmataFixtureService.TryLoad(fixtureId, document, out var fixture, out var error)
+ ? ApiMappings.Ok(fixture!)
+ : ApiMappings.BadRequestFromMessage(error, "cadmata.fixture")));
+
documents.MapGet("/{documentId:guid}", (Guid documentId, KernelDocumentStore store) =>
{
if (!store.TryGet(documentId, out var document))
diff --git a/Aetheris.Server/Contracts/ApiContracts.cs b/Aetheris.Server/Contracts/ApiContracts.cs
index c3147845..c8f9a968 100644
--- a/Aetheris.Server/Contracts/ApiContracts.cs
+++ b/Aetheris.Server/Contracts/ApiContracts.cs
@@ -80,6 +80,15 @@ public sealed record EdgePolylineDto(int EdgeId, IReadOnlyList<Point3Dto> Points
public sealed record DisplayPrepareRequestDto(TessellationOptionsDto? TessellationOptions);
+public sealed record CadmataPointDto(double X, double Y, double Z);
+public sealed record CadmataGeometryDto(string Type, IReadOnlyList<CadmataPointDto>? Points = null, CadmataPointDto? Center = null, double? Radius = null, CadmataPointDto? Origin = null, CadmataPointDto? U = null, CadmataPointDto? V = null, bool Closed = false);
+public sealed record CadmataVisualizationDiagnosticDto(string Code, string Message, string Severity);
+public sealed record CadmataTopologyDto(IReadOnlyList<int>? FaceIds = null, IReadOnlyList<int>? EdgeIds = null, IReadOnlyList<int>? LoopIds = null, IReadOnlyList<int>? VertexIds = null, IReadOnlyList<int>? DirectedEdgeIds = null);
+public sealed record CadmataVisualizationEntityDto(string StableId, string Kind, string Label, string Layer, string? Role, CadmataGeometryDto? Geometry, string? SourceSpan, IReadOnlyList<string>? ParentIds, IReadOnlyList<string>? ChildIds, IReadOnlyList<string>? ConstructionDescendantIds, IReadOnlyList<string>? MaterializedDescendantIds, CadmataTopologyDto? Topology, IReadOnlyList<string>? SelectionIds, string? Consumer, IReadOnlyList<CadmataVisualizationDiagnosticDto>? Diagnostics, IReadOnlyDictionary<string, string>? Metadata);
+public sealed record CadmataVisualizationSelectionDto(string StableId, string Label, string Kind, IReadOnlyList<string> EntityIds, IReadOnlyList<string>? OrderedEntityIds, bool Closed, IReadOnlyList<CadmataVisualizationDiagnosticDto>? Diagnostics);
+public sealed record CadmataVisualizationArtifactDto(string SchemaVersion, string FixtureId, string SourcePath, IReadOnlyList<CadmataVisualizationEntityDto> Entities, IReadOnlyList<CadmataVisualizationSelectionDto> Selections, IReadOnlyList<CadmataVisualizationDiagnosticDto> Diagnostics, IReadOnlyDictionary<string, double> Metrics);
+public sealed record CadmataFixtureLoadResponseDto(string DocumentId, string BodyId, string DefinitionId, string FixtureId, CadmataVisualizationArtifactDto Visualization);
+
public sealed record AnalyticDisplayFaceDomainHintDto(double? MinV, double? MaxV);
public sealed record AnalyticDisplayPlaneGeometryDto(
diff --git a/aetheris.client/package-lock.json b/aetheris.client/package-lock.json
index d9dc22a4..d463a838 100644
--- a/aetheris.client/package-lock.json
+++ b/aetheris.client/package-lock.json
@@ -12,6 +12,7 @@
"@react-three/fiber": "^9.5.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
+ "machinalayout": "^0.7.0",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"tailwind-merge": "^3.5.0",
@@ -4195,6 +4196,26 @@
"three": ">=0.134.0"
}
},
+ "node_modules/machinalayout": {
+ "version": "0.7.0",
+ "resolved": "https://registry.npmjs.org/machinalayout/-/machinalayout-0.7.0.tgz",
+ "integrity": "sha512-1VhKMwdO4LR+jTe+oaS0trvOTTUlFCbqycOLcTkNphx1LwBWDCrwZmj4sstrldTpJpgQLDOqbqjbeaAxqgR2Hw==",
+ "license": "MIT",
+ "peerDependencies": {
+ "react": ">=18 <20",
+ "react-dom": ">=18 <20",
+ "react-native": ">=0.72 <1",
+ "vue": ">=3.4 <4"
+ },
+ "peerDependenciesMeta": {
+ "react-native": {
+ "optional": true
+ },
+ "vue": {
+ "optional": true
+ }
+ }
+ },
"node_modules/magic-string": {
"version": "0.30.21",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
diff --git a/aetheris.client/package.json b/aetheris.client/package.json
index c283094c..d0f26703 100644
--- a/aetheris.client/package.json
+++ b/aetheris.client/package.json
@@ -15,6 +15,7 @@
"@react-three/fiber": "^9.5.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
+ "machinalayout": "^0.7.0",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"tailwind-merge": "^3.5.0",
diff --git a/aetheris.client/src/App.tsx b/aetheris.client/src/App.tsx
index 00b18b7b..e5d3a578 100644
--- a/aetheris.client/src/App.tsx
+++ b/aetheris.client/src/App.tsx
@@ -8,6 +8,7 @@ import {
exportDefinitionStep,
getDocumentSummary,
importStep,
+ loadCadmataFixture,
pickBody,
prepareBodyDisplay,
translateBody,
@@ -22,6 +23,8 @@ import { Button } from './components/ui/button';
import { AetherisViewport } from './viewer/AetherisViewport';
import { buildDisplaySceneData } from './viewer/displaySceneBuilder';
import { STEP_UPLOAD_LIMIT_BYTES, STEP_UPLOAD_LIMIT_MB, formatMegabytes } from './config/stepUpload';
+import { DEFAULT_CADMATA_LAYERS, type CadmataLayerVisibility } from './viewer/CadmataOverlay';
+import { parseCadmataVisualizationArtifact, resolveCadmataSelection, type CadmataVisualizationArtifact } from './viewer/conceptVisualization';
type RequestStatus = 'idle' | 'loading' | 'success' | 'error';
type BooleanOperationUi = 'Union' | 'Subtract' | 'Intersect';
@@ -123,6 +126,9 @@ function App() {
const [isResetting, setIsResetting] = useState(false);
const [isGridVisible, setIsGridVisible] = useState(true);
const [isCoordVisible, setIsCoordVisible] = useState(true);
+ const [cadmataArtifact, setCadmataArtifact] = useState<CadmataVisualizationArtifact | null>(null);
+ const [cadmataLayers, setCadmataLayers] = useState<CadmataLayerVisibility>(DEFAULT_CADMATA_LAYERS);
+ const [selectedCadmataId, setSelectedCadmataId] = useState<string | null>(null);
const resetSessionState = useCallback(() => {
setBodyIds([]);
@@ -142,6 +148,8 @@ function App() {
setStepCanonicalHash(null);
setCopyHashMessage('');
setDiagnostics([]);
+ setCadmataArtifact(null);
+ setSelectedCadmataId(null);
setImportStatusMessage('Preparing workspace…');
}, []);
@@ -553,6 +561,18 @@ function App() {
}
}, [activeBodyId, documentId]);
+ const handleLoadCadmataFixture = useCallback(async (fixtureId: string) => {
+ if (!documentId) return;
+ await runAction(`Load Cadmata ${fixtureId}`, async () => {
+ const loaded = await loadCadmataFixture(documentId, fixtureId);
+ const artifact = parseCadmataVisualizationArtifact(loaded.visualization);
+ setCadmataArtifact(artifact);
+ setSelectedCadmataId(artifact.entities[0]?.stableId ?? null);
+ await refreshSummaryAndActiveTessellation(loaded.bodyId);
+ setStatusMessage(`Cadmata fixture '${fixtureId}' loaded with compiler-published correspondence.`);
+ });
+ }, [documentId, refreshSummaryAndActiveTessellation, runAction]);
+
const displayScene = useMemo(() => buildDisplaySceneData(displayPreparation), [displayPreparation]);
const displayRenderableCounts = useMemo(() => {
const renderables = displayScene.displayScene?.renderables ?? [];
@@ -566,6 +586,7 @@ function App() {
const nearestHit = pickHits[0] ?? null;
const highlightedFaceId = nearestHit?.entityKind === 'Face' ? nearestHit.faceId : null;
const highlightedEdgeId = nearestHit?.entityKind === 'Edge' ? nearestHit.edgeId : null;
+ const cadmataSelection = useMemo(() => cadmataArtifact ? resolveCadmataSelection(cadmataArtifact, selectedCadmataId) : null, [cadmataArtifact, selectedCadmataId]);
const canImportStep = Boolean(
serverStatus === 'connected'
&& documentStatus === 'ready'
@@ -655,6 +676,8 @@ function App() {
aria-pressed={isGridVisible}>
GRID
</button>
+ <button type="button" className={cadmataLayers.profileLoops ? 'viewport-segmented__button is-active' : 'viewport-segmented__button'} onClick={() => setCadmataLayers((layers) => ({ ...layers, profileLoops: !layers.profileLoops, profileGuides: !layers.profileGuides }))} aria-pressed={cadmataLayers.profileLoops}>PROFILE</button>
+ <button type="button" className={cadmataLayers.selections ? 'viewport-segmented__button is-active' : 'viewport-segmented__button'} onClick={() => setCadmataLayers((layers) => ({ ...layers, selections: !layers.selections }))} aria-pressed={cadmataLayers.selections}>SEMANTIC</button>
<button
type="button"
className={isCoordVisible ? 'viewport-segmented__button is-active' : 'viewport-segmented__button'}
@@ -665,11 +688,17 @@ function App() {
</div>
<AetherisViewport
displayScene={displayScene.displayScene}
- highlightedFaceId={highlightedFaceId}
- highlightedEdgeId={highlightedEdgeId}
+ highlightedFaceId={cadmataSelection?.faceIds.values().next().value ?? highlightedFaceId}
+ highlightedEdgeId={cadmataSelection?.edgeIds.values().next().value ?? highlightedEdgeId}
+ highlightedFaceIds={cadmataSelection?.faceIds}
+ highlightedEdgeIds={cadmataSelection?.edgeIds}
showGrid={isGridVisible}
showAxisGuide={isCoordVisible}
onPickRay={(origin, direction) => void handlePickRay(origin, direction)}
+ cadmataArtifact={cadmataArtifact}
+ cadmataLayers={cadmataLayers}
+ selectedCadmataIds={cadmataSelection?.entityIds}
+ onCadmataSelect={setSelectedCadmataId}
/>
</div>
</section>
@@ -677,6 +706,17 @@ function App() {
<aside className="tool-rail">
{activeTab === 'viewer' ? (
<>
+ <section className="tool-section cadmata-inspector">
+ <h2 className="section-title">Cadmata compiler evidence</h2>
+ <div className="stack-row">
+ {['direct-profile', 'split-compose-chamfer', 'semantic-shaft-hole', 'ctc-01-x3'].map((fixtureId) => <Button key={fixtureId} type="button" variant="outline" onClick={() => void handleLoadCadmataFixture(fixtureId)} disabled={!documentId || status === 'loading'}>{fixtureId}</Button>)}
+ </div>
+ {cadmataArtifact ? <>
+ <p><strong>{cadmataArtifact.fixtureId}</strong> · {cadmataArtifact.metrics?.entityCount ?? 0} evidence entities</p>
+ <label>Entity <select value={selectedCadmataId ?? ''} onChange={(event) => setSelectedCadmataId(event.target.value || null)}><option value="">No selection</option>{cadmataArtifact.entities.map((entity) => <option key={entity.stableId} value={entity.stableId}>{entity.kind}: {entity.label}</option>)}</select></label>
+ {selectedCadmataId ? (() => { const entity = cadmataArtifact.entities.find((candidate) => candidate.stableId === selectedCadmataId); return entity ? <div className="cadmata-inspector__details"><p><strong>{entity.label}</strong></p><p>{entity.kind} · {entity.role ?? 'unclassified'}</p><p className="mono-value">{entity.stableId}</p><p>Source: {entity.sourceSpan ?? cadmataArtifact.sourcePath}</p><p>Material descendants: {entity.materializedDescendantIds?.length ?? 0}; faces: {cadmataSelection?.faceIds.size ?? 0}; edges: {cadmataSelection?.edgeIds.size ?? 0}</p>{[...(entity.diagnostics ?? []), ...(cadmataSelection?.diagnostics ?? [])].map((diagnostic, index) => <p key={`${diagnostic.code}-${index}`}>[{diagnostic.severity}] {diagnostic.code}: {diagnostic.message}</p>)}</div> : null; })() : null}
+ </> : <p>Load a real Firmament fixture to inspect its compiler correspondence.</p>}
+ </section>
<section className="tool-section tool-section--import">
<h2 className="section-title">Step Import</h2>
<StepImportDropzone
diff --git a/aetheris.client/src/__tests__/conceptVisualization.test.ts b/aetheris.client/src/__tests__/conceptVisualization.test.ts
new file mode 100644
index 00000000..571dcadc
--- /dev/null
+++ b/aetheris.client/src/__tests__/conceptVisualization.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest';
+import { parseCadmataVisualizationArtifact, resolveCadmataSelection, type CadmataVisualizationArtifact } from '../viewer/conceptVisualization';
+
+const artifact: CadmataVisualizationArtifact = {
+ schemaVersion: 'cadmata-concept-viz-x1', fixtureId: 'shaft', sourcePath: 'fixture.firmament', diagnostics: [], metrics: {}, selections: [],
+ entities: [
+ { stableId: 'hole:mount', kind: 'HoleFeature', label: 'mount', layer: 'conceptAxes', materializedDescendantIds: ['wall', 'entry'] },
+ { stableId: 'wall', kind: 'BRepFace', label: 'wall', layer: 'selections', topology: { faceIds: [7] } },
+ { stableId: 'entry', kind: 'BRepEdge', label: 'entry', layer: 'brepEdges', topology: { edgeIds: [14] } },
+ ],
+};
+
+describe('Cadmata concept visualization artifact', () => {
+ it('resolves only compiler-published source-to-descendant topology', () => {
+ const resolved = resolveCadmataSelection(artifact, 'hole:mount');
+ expect([...resolved.faceIds]).toEqual([7]);
+ expect([...resolved.edgeIds]).toEqual([14]);
+ });
+ it('reports a missing correspondence instead of inventing a highlight', () => {
+ const invalid = { ...artifact, entities: [{ ...artifact.entities[0], materializedDescendantIds: ['missing'] }] };
+ expect(resolveCadmataSelection(invalid, 'hole:mount').diagnostics[0].code).toBe('Cadmata.MissingDescendant');
+ });
+ it('rejects an artifact without the X1 contract', () => expect(() => parseCadmataVisualizationArtifact({ entities: [], selections: [] })).toThrow('cadmata-concept-viz-x1'));
+});
diff --git a/aetheris.client/src/api/aetherisApi.ts b/aetheris.client/src/api/aetherisApi.ts
index acb21ecc..796007db 100644
--- a/aetheris.client/src/api/aetherisApi.ts
+++ b/aetheris.client/src/api/aetherisApi.ts
@@ -247,6 +247,9 @@ export interface DisplayPreparationResponseDto {
displayLanes?: DisplayLaneDto[] | null;
}
+export interface CadmataVisualizationArtifactDto { schemaVersion: 'cadmata-concept-viz-x1'; fixtureId: string; sourcePath: string; entities: unknown[]; selections: unknown[]; diagnostics: unknown[]; metrics: Record<string, number>; }
+export interface CadmataFixtureLoadResponseDto { documentId: string; bodyId: string; definitionId: string; fixtureId: string; visualization: CadmataVisualizationArtifactDto; }
+
export interface PickOptionsDto {
nearestOnly?: boolean;
includeBackfaces?: boolean;
@@ -353,6 +356,10 @@ export async function prepareBodyDisplay(documentId: string, bodyId: string): Pr
});
}
+export async function loadCadmataFixture(documentId: string, fixtureId: string): Promise<CadmataFixtureLoadResponseDto> {
+ return request<CadmataFixtureLoadResponseDto>(`/api/v1/documents/${documentId}/cadmata/fixtures/${fixtureId}`, { method: 'POST' });
+}
+
export async function pickBody(documentId: string, bodyId: string, pickRequest: PickRequestDto): Promise<PickResponseDto> {
return request<PickResponseDto>(`/api/v1/documents/${documentId}/bodies/${bodyId}/pick`, {
method: 'POST',
diff --git a/aetheris.client/src/viewer/AetherisViewport.tsx b/aetheris.client/src/viewer/AetherisViewport.tsx
index e30a02a4..2206d888 100644
--- a/aetheris.client/src/viewer/AetherisViewport.tsx
+++ b/aetheris.client/src/viewer/AetherisViewport.tsx
@@ -7,6 +7,8 @@ import { BufferAttribute, BufferGeometry, Color, DoubleSide, MeshStandardMateria
import type { DisplayScene } from './displayRenderables';
import { computeDisplaySceneBounds, computeOrthographicCameraFit } from './displaySceneBounds';
import { selectLogarithmicGridScales } from './logarithmicGrid';
+import { CadmataOverlay, type CadmataLayerVisibility } from './CadmataOverlay';
+import type { CadmataVisualizationArtifact } from './conceptVisualization';
const VIEWPORT_THEME = {
surfaceColor: '#969ba1',
@@ -454,9 +456,15 @@ export interface AetherisViewportProps {
displayScene?: DisplayScene | null;
highlightedFaceId?: number | null;
highlightedEdgeId?: number | null;
+ highlightedFaceIds?: Set<number>;
+ highlightedEdgeIds?: Set<number>;
showGrid?: boolean;
showAxisGuide?: boolean;
onPickRay?: (origin: { x: number; y: number; z: number }, direction: { x: number; y: number; z: number }) => void;
+ cadmataArtifact?: CadmataVisualizationArtifact | null;
+ cadmataLayers?: CadmataLayerVisibility;
+ selectedCadmataIds?: Set<string>;
+ onCadmataSelect?: (stableId: string) => void;
}
function FaceMesh({ positions, normals, indices, isHighlighted }: { positions: Float32Array; normals: Float32Array; indices: Uint32Array; isHighlighted: boolean }) {
@@ -622,9 +630,15 @@ export function AetherisViewport({
displayScene = null,
highlightedFaceId = null,
highlightedEdgeId = null,
+ highlightedFaceIds,
+ highlightedEdgeIds,
showGrid = true,
showAxisGuide = true,
onPickRay,
+ cadmataArtifact = null,
+ cadmataLayers,
+ selectedCadmataIds = new Set(),
+ onCadmataSelect = () => undefined,
}: AetherisViewportProps) {
return (
<Canvas style={{ display: 'block', width: '100%', height: '100%' }} orthographic camera={{ position: [6, 6, 6], zoom: 90, near: -10000, far: 10000 }} gl={{ alpha: true }}>
@@ -636,19 +650,20 @@ export function AetherisViewport({
{showAxisGuide ? <AxisGuide /> : null}
{displayScene?.renderables.map((renderable) => {
if (renderable.kind === 'AnalyticPatch') {
- return <FaceMesh key={`analytic-${renderable.faceId}`} positions={renderable.previewMesh.positions} normals={renderable.previewMesh.normals} indices={renderable.previewMesh.indices} isHighlighted={highlightedFaceId === renderable.faceId} />;
+ return <FaceMesh key={`analytic-${renderable.faceId}`} positions={renderable.previewMesh.positions} normals={renderable.previewMesh.normals} indices={renderable.previewMesh.indices} isHighlighted={highlightedFaceIds?.has(renderable.faceId) ?? highlightedFaceId === renderable.faceId} />;
}
if (renderable.kind === 'MeshPatch') {
- return <FaceMesh key={`mesh-${renderable.faceId}`} positions={renderable.mesh.positions} normals={renderable.mesh.normals} indices={renderable.mesh.indices} isHighlighted={highlightedFaceId === renderable.faceId} />;
+ return <FaceMesh key={`mesh-${renderable.faceId}`} positions={renderable.mesh.positions} normals={renderable.mesh.normals} indices={renderable.mesh.indices} isHighlighted={highlightedFaceIds?.has(renderable.faceId) ?? highlightedFaceId === renderable.faceId} />;
}
if (renderable.kind === 'WirePatch') {
- return renderable.wires.map((wire) => <EdgeLine key={`wire-${renderable.faceId}-${wire.edgeId}`} points={wire.points} isHighlighted={highlightedFaceId === renderable.faceId || highlightedEdgeId === wire.edgeId} />);
+ return renderable.wires.map((wire) => <EdgeLine key={`wire-${renderable.faceId}-${wire.edgeId}`} points={wire.points} isHighlighted={(highlightedFaceIds?.has(renderable.faceId) ?? highlightedFaceId === renderable.faceId) || (highlightedEdgeIds?.has(wire.edgeId) ?? highlightedEdgeId === wire.edgeId)} />);
}
return null;
})}
+ {cadmataLayers ? <CadmataOverlay artifact={cadmataArtifact} layers={cadmataLayers} selectedIds={selectedCadmataIds} onSelect={onCadmataSelect} /> : null}
<PickRayCapture onPickRay={onPickRay} />
<OrbitControls makeDefault enablePan enableZoom />
</Canvas>
diff --git a/aetheris.client/src/viewer/CadmataOverlay.tsx b/aetheris.client/src/viewer/CadmataOverlay.tsx
new file mode 100644
index 00000000..8251a8f5
--- /dev/null
+++ b/aetheris.client/src/viewer/CadmataOverlay.tsx
@@ -0,0 +1,26 @@
+import { Line } from '@react-three/drei';
+import { useMemo } from 'react';
+import { DoubleSide, Vector3 } from 'three';
+import type { CadmataEntity, CadmataLayer, CadmataVisualizationArtifact } from './conceptVisualization';
+
+export const CADMATA_PALETTE = { concept: '#6ea6b8', profile: '#4db6ac', compose: '#b48748', selection: '#ffbf47', ancestor: '#77a7d9', diagnostic: '#e05d5d' } as const;
+export type CadmataLayerVisibility = Record<CadmataLayer, boolean>;
+export const DEFAULT_CADMATA_LAYERS: CadmataLayerVisibility = { material: true, brepEdges: true, conceptPoints: true, conceptAxes: true, conceptRegions: true, profileGuides: true, profileLoops: true, composeRegions: true, selections: true, diagnostics: true };
+
+function colorFor(entity: CadmataEntity, selected: boolean) { if (selected) return CADMATA_PALETTE.selection; if (entity.layer === 'profileGuides' || entity.layer === 'profileLoops') return CADMATA_PALETTE.profile; if (entity.layer === 'composeRegions') return CADMATA_PALETTE.compose; if (entity.layer === 'diagnostics') return CADMATA_PALETTE.diagnostic; return CADMATA_PALETTE.concept; }
+function OverlayEntity({ entity, selected, onSelect }: { entity: CadmataEntity; selected: boolean; onSelect: (id: string) => void }) {
+ const geometry = entity.geometry; const color = colorFor(entity, selected);
+ const points = useMemo(() => geometry?.type === 'polyline' ? geometry.points.map((p) => [p.x, p.y, p.z] as [number, number, number]) : [], [geometry]);
+ if (!geometry) return null;
+ if (geometry.type === 'point') return <mesh position={[geometry.point.x, geometry.point.y, geometry.point.z]} onClick={(event) => { event.stopPropagation(); onSelect(entity.stableId); }}><sphereGeometry args={[1.8, 12, 8]} /><meshBasicMaterial color={color} depthTest={false} /></mesh>;
+ if (geometry.type === 'circle') {
+ const count = 48; const points = Array.from({ length: count + 1 }, (_, i) => { const a = (i / count) * Math.PI * 2; return [geometry.center.x + Math.cos(a) * geometry.radius, geometry.center.y + Math.sin(a) * geometry.radius, geometry.center.z] as [number, number, number]; });
+ return <Line points={points} color={color} lineWidth={selected ? 3.5 : 1.5} onClick={(event) => { event.stopPropagation(); onSelect(entity.stableId); }} />;
+ }
+ if (geometry.type === 'plane') return <mesh position={[geometry.origin.x, geometry.origin.y, geometry.origin.z]} onClick={(event) => { event.stopPropagation(); onSelect(entity.stableId); }}><planeGeometry args={[new Vector3(geometry.u.x, geometry.u.y, geometry.u.z).length() * 2, new Vector3(geometry.v.x, geometry.v.y, geometry.v.z).length() * 2]} /><meshBasicMaterial color={color} transparent opacity={0.12} side={DoubleSide} depthWrite={false} /></mesh>;
+ return <Line points={geometry.closed ? [...points, points[0]] : points} color={color} lineWidth={selected ? 4 : entity.layer === 'profileLoops' ? 2.5 : 1.25} onClick={(event) => { event.stopPropagation(); onSelect(entity.stableId); }} />;
+}
+export function CadmataOverlay({ artifact, layers, selectedIds, onSelect }: { artifact: CadmataVisualizationArtifact | null; layers: CadmataLayerVisibility; selectedIds: Set<string>; onSelect: (id: string) => void }) {
+ if (!artifact) return null;
+ return <group name="CadmataCompilerOverlays">{artifact.entities.filter((entity) => layers[entity.layer]).map((entity) => <OverlayEntity key={entity.stableId} entity={entity} selected={selectedIds.has(entity.stableId)} onSelect={onSelect} />)}</group>;
+}
diff --git a/aetheris.client/src/viewer/conceptVisualization.ts b/aetheris.client/src/viewer/conceptVisualization.ts
new file mode 100644
index 00000000..3a27c1a8
--- /dev/null
+++ b/aetheris.client/src/viewer/conceptVisualization.ts
@@ -0,0 +1,88 @@
+import { M } from 'machinalayout/machina';
+
+export type CadmataLayer = 'material' | 'brepEdges' | 'conceptPoints' | 'conceptAxes' | 'conceptRegions' | 'profileGuides' | 'profileLoops' | 'composeRegions' | 'selections' | 'diagnostics';
+export type CadmataPoint = { x: number; y: number; z: number };
+export type CadmataGeometry =
+ | { type: 'point'; point: CadmataPoint }
+ | { type: 'polyline'; points: CadmataPoint[]; closed?: boolean }
+ | { type: 'plane'; origin: CadmataPoint; u: CadmataPoint; v: CadmataPoint }
+ | { type: 'circle'; center: CadmataPoint; radius: number; normal?: CadmataPoint };
+
+export interface CadmataDiagnostic { code: string; message: string; severity: 'info' | 'warning' | 'error'; }
+export interface CadmataEntity {
+ stableId: string;
+ kind: string;
+ label: string;
+ role?: string;
+ layer: CadmataLayer;
+ geometry?: CadmataGeometry;
+ sourceSpan?: string;
+ parentIds?: string[];
+ childIds?: string[];
+ constructionDescendantIds?: string[];
+ materializedDescendantIds?: string[];
+ topology?: { faceIds?: number[]; edgeIds?: number[]; loopIds?: number[]; vertexIds?: number[]; directedEdgeIds?: number[] };
+ selectionIds?: string[];
+ consumer?: string;
+ diagnostics?: CadmataDiagnostic[];
+ metadata?: Record<string, string | number | boolean | null>;
+}
+export interface CadmataSelection { stableId: string; label: string; kind: 'EdgeSet' | 'FaceSet' | 'LoopSet' | 'Chain' | 'VertexSet'; entityIds: string[]; orderedEntityIds?: string[]; closed?: boolean; diagnostics?: CadmataDiagnostic[]; }
+export interface CadmataVisualizationArtifact { schemaVersion: 'cadmata-concept-viz-x1'; fixtureId: string; sourcePath: string; entities: CadmataEntity[]; selections: CadmataSelection[]; diagnostics?: CadmataDiagnostic[]; metrics?: Record<string, number>; }
+export interface CadmataSelectionState { entityIds: Set<string>; faceIds: Set<number>; edgeIds: Set<number>; diagnostics: CadmataDiagnostic[]; }
+
+const layers: CadmataLayer[] = ['material', 'brepEdges', 'conceptPoints', 'conceptAxes', 'conceptRegions', 'profileGuides', 'profileLoops', 'composeRegions', 'selections', 'diagnostics'];
+
+// The panel is still rendered with the existing Cadmata shell, but this record
+// fixes its intended tool/readout composition for future responsive lowering.
+export const CADMATA_INSPECTOR_LAYOUT = M.vstack('cadmata-inspector-stack', { gap: 8 }, [
+ M.fixed('cadmata-fixture-tools', 44), M.fill('cadmata-evidence', 1),
+]);
+
+export function parseCadmataVisualizationArtifact(value: unknown): CadmataVisualizationArtifact {
+ const artifact = value as Partial<CadmataVisualizationArtifact>;
+ if (artifact?.schemaVersion !== 'cadmata-concept-viz-x1' || !Array.isArray(artifact.entities) || !Array.isArray(artifact.selections)) {
+ throw new Error('Invalid Cadmata visualization artifact: expected cadmata-concept-viz-x1 entities and selections.');
+ }
+ const ids = new Set<string>();
+ for (const entity of artifact.entities) {
+ if (!entity.stableId || !entity.label || !layers.includes(entity.layer)) throw new Error('Invalid Cadmata visualization entity.');
+ if (ids.has(entity.stableId)) throw new Error(`Duplicate Cadmata visualization stableId '${entity.stableId}'.`);
+ ids.add(entity.stableId);
+ }
+ return artifact as CadmataVisualizationArtifact;
+}
+
+export function indexCadmataArtifact(artifact: CadmataVisualizationArtifact) {
+ const byId = new Map(artifact.entities.map((entity) => [entity.stableId, entity]));
+ const reverse = new Map<string, Set<string>>();
+ for (const entity of artifact.entities) {
+ for (const id of [...(entity.parentIds ?? []), ...(entity.childIds ?? []), ...(entity.constructionDescendantIds ?? []), ...(entity.materializedDescendantIds ?? [])]) {
+ const related = reverse.get(id) ?? new Set<string>(); related.add(entity.stableId); reverse.set(id, related);
+ }
+ }
+ return { byId, reverse };
+}
+
+/** Traverses only compiler-published relation fields; it never tries to infer BRep correspondence in the browser. */
+export function resolveCadmataSelection(artifact: CadmataVisualizationArtifact, stableId: string | null): CadmataSelectionState {
+ if (!stableId) return { entityIds: new Set(), faceIds: new Set(), edgeIds: new Set(), diagnostics: [] };
+ const { byId, reverse } = indexCadmataArtifact(artifact);
+ const pending = [stableId]; const entityIds = new Set<string>(); const diagnostics: CadmataDiagnostic[] = [];
+ while (pending.length) {
+ const id = pending.pop()!;
+ if (entityIds.has(id)) continue;
+ const entity = byId.get(id);
+ if (!entity) { diagnostics.push({ code: 'Cadmata.MissingDescendant', severity: 'warning', message: `Compiler correspondence references missing entity '${id}'.` }); continue; }
+ entityIds.add(id);
+ pending.push(...(entity.parentIds ?? []), ...(entity.childIds ?? []), ...(entity.constructionDescendantIds ?? []), ...(entity.materializedDescendantIds ?? []), ...(reverse.get(id) ?? []));
+ }
+ const faceIds = new Set<number>(); const edgeIds = new Set<number>();
+ for (const id of entityIds) {
+ const topology = byId.get(id)?.topology;
+ topology?.faceIds?.forEach((faceId) => faceIds.add(faceId));
+ topology?.edgeIds?.forEach((edgeId) => edgeIds.add(edgeId));
+ diagnostics.push(...(byId.get(id)?.diagnostics ?? []));
+ }
+ return { entityIds, faceIds, edgeIds, diagnostics };
+}
diff --git a/docs/cadmata/concept-visualization-x1.md b/docs/cadmata/concept-visualization-x1.md
new file mode 100644
index 00000000..8c93008b
--- /dev/null
+++ b/docs/cadmata/concept-visualization-x1.md
@@ -0,0 +1,81 @@
+# Cadmata concept visualization X1
+
+Cadmata visualizes compiler intent, not merely final tessellation.
+
+## Contract and fixture bridge
+
+`cadmata-concept-viz-x1` is the browser artifact. Each entity has a stable ID,
+semantic kind and layer, optional source span and display geometry, explicit
+parent/construction/materialized links, and compiler-published topology IDs.
+Selections retain an ordered entity list and closed state. The browser follows
+only those links; it never guesses a BRep match from rendered triangles.
+
+`POST /api/v1/documents/{documentId}/cadmata/fixtures/{fixtureId}` materializes
+real compiler fixtures directly through the existing Profile, composition, and
+semantic-hole materializers, adds the resulting body to the document, and returns
+the matching artifact. Available fixture IDs are `direct-profile`,
+`split-compose-chamfer`, `semantic-shaft-hole`, and `ctc-01-x3`.
+
+The bridge uses the compiler's `SemanticTopologyCorrespondence`. In particular,
+the shaft-hole route exposes the authored `hole:base.mount`, its axis and entry
+circle, entry/exit loops and edges, and its wall face. Composition routes expose
+Profile guides/segments plus arrangement/materialized descendants from the
+authoritative section-stack plan.
+
+## Viewport architecture
+
+The scene remains split between DisplayIR material renderables and a dedicated
+`CadmataCompilerOverlays` scene group. Cadmata overlays are keyed by stable ID;
+selection resolution is memoizable and returns face/edge IDs without whole-scene
+traversal. Existing BRep picking remains available. Overlay click handling stops
+propagation, making source/semantic evidence win over material picks.
+
+The compact inspector/tool region uses the published `machinalayout` package as
+the declared layout dependency boundary; Three.js rendering remains regular
+React Three Fiber rather than being forced through a layout library.
+
+## Layers and interaction
+
+The artifact supports independently visible material, BRep edges, concept points,
+axes, regions, Profile guides, resolved Profile loops, compose regions,
+selections, and diagnostics. The current compact viewport control exposes Profile
+and semantic toggles; the inspector remains the source selection surface.
+
+Selecting an entity traverses explicit parent/child/construction/materialized
+links, highlights all published face/edge descendants, and shows label, stable
+ID, kind, role, source, descendant totals, and diagnostic evidence. A missing
+referenced entity produces `Cadmata.MissingDescendant`; it does not create a fake
+highlight. Chain ordering is preserved in the artifact's `orderedEntityIds` for
+the subsequent ordered-marker renderer.
+
+## Analytic display facade
+
+DisplayIR already retains analytic face family and parameters for planes,
+cylinders, cones, spheres, and tori. Cadmata continues to use its bounded mesh
+preview/fallback representation while preserving that analytic metadata per face.
+This is an analytic display facade, not true GPU analytic-surface rendering.
+
+Tessellation is a display carrier. Analytic geometry remains the source of
+surface identity and normals.
+
+The existing renderer keeps one mesh per face, so smooth normals cannot bridge
+real BRep face boundaries. Cylindrical/conical faces may use the analytic preview
+or bounded fallback mesh according to DisplayIR. Exact trim/silhouette curves,
+analytic-normal shaders, and display LOD remain future work.
+
+## Evidence and limits
+
+The fixture bridge has been compiled against direct Profile extrusion,
+split-compose, semantic shaft-hole, and CTC-01 X3 sources. CTC X3 supplies the
+expanded lobe/scaffold/Profile/Compose evidence emitted by the composition
+materializer. The split-compose fixture currently visualizes the source-grounded
+pre-finish composition correspondence; its EdgeFinish consumer is recorded by
+the source artifact, while replacement chamfer topology needs a dedicated
+post-finish correspondence producer before it can truthfully claim descendant
+faces. This is intentionally surfaced as a current limitation rather than
+heuristically mapped.
+
+The next reconstruction pressure test should be CTC-01 with the central hex top
+loop and one lobe outer-arc selection carried through a real feature consumer,
+so arrangement fragments, an ordered selection, and replacement topology can be
+validated together.
diff --git a/docs/firmament/semantic-selections-x1.md b/docs/firmament/semantic-selections-x1.md
new file mode 100644
index 00000000..b912be56
--- /dev/null
+++ b/docs/firmament/semantic-selections-x1.md
@@ -0,0 +1,49 @@
+# SEMANTIC-LOOPS-X1 — source-grounded topology selections
+
+Semantic selection preserves intent through topology change.
+
+A source edge may become many material edges. The compiler preserves the descendant relation rather than pretending topology never changes.
+
+## Admitted source form
+
+```firmament
+Selection OuterTopBoundary {
+ Target: TopBoundary
+ Source: MainPlate.ProfileSegments([SouthEdge, EastEdge, NorthEdge, WestEdge])
+ Require: ClosedLoop
+}
+
+EdgeFinish TopEdgeBreak {
+ Target: OuterTopBoundary
+ Kind: Chamfer
+ Distance: 1mm
+}
+```
+
+X1 admits direct, scaffold-authored Profile extrusion. `ProfileSegments` is source identity, `Target` is a bounded role qualifier, and `Require` is the topology contract. Raw BRep, coedge, and STEP ids are not source syntax.
+
+## Result and resolution contract
+
+The immutable result forms are `VertexSet`, `EdgeSet`, `FaceSet`, `LoopSet`, and `Chain`. Every materialized descendant has a stable diagnostic id, source identity, topology role, parent/source relationship, and optional exact topology handle used internally by the materializer. Authoring never receives mutable BRep collections.
+
+The profile emitter records correspondence while it creates the authoritative body: profile segment to top/bottom boundary edge, vertical extrusion edges, and side face; profile loop to cap boundary loop. The resolver consumes only that correspondence plus the body planned by the emitter. It does not scan emitted STEP, inspect coordinates, or recognize radii.
+
+`ExactlyOne`, `OneOrMore`, `ConnectedChain`, `ClosedLoop`, and `NonEmptyFaceSet` are explicit contracts. Chain/loop validation uses `DirectedEdgeUse`: duplicate edges, disconnected components, branch vertices, missing closure, and a closed result requested as an open chain fail deterministically.
+
+Typed failures are `SemanticSourceNotFound`, `NoMaterializedDescendants`, `AmbiguousBodyContext`, `SelectionCardinalityMismatch`, `DescendantsNotConnected`, `DescendantsBranch`, `DescendantsDoNotClose`, `MixedBoundaryRoles`, `UnsupportedTopologyChange`, and `SelectionConsumerMismatch`. Diagnostics retain requested source ids, candidate descendants, source span, body, role, and provenance chain.
+
+## Production proof
+
+`fixtures/FirmamentV2/Profile/valid/semantic-top-boundary-chamfer.firmament` resolves the four authored perimeter segments into a closed top-boundary chain, then feeds that validated semantic selection to the admitted rectangular top-loop chamfer route. The finish route emits its changed authoritative BRepPlan; it does not use a raw edge id or a finished-topology search.
+
+The verification artifact is `artifacts/semantic-top-boundary-chamfer.step`, SHA-256 `3821ecb87303402c84abb2c07b3e92e916ff8887049120c7d83362d048be2c06`. Ordinary analysis reports one body, one shell, 10 faces, and `enclosed-manifold`. M8 reimport reports `isEnclosed: true` and `isOrientationConsistent: true`; external inspection remains honestly `ExternalInspectionPending`.
+
+## Inspection and Cadmata handoff
+
+`aetheris inspect-selections <source> --json` performs source parse, authoritative materialization, and selection resolution only. It emits stable id, kind, label, source span, source entity, parent, descendants, topology role, connectivity, traversal order, provenance, consumer, and diagnostics. It does not run STEP analysis or M8.
+
+This is the Cadmata handoff shape. It intentionally includes geometry preview only where the producer has one, and does not add rendering or interactive selection editing.
+
+## Compose X2 extension
+
+The section-stack emitter now publishes correspondence while it consumes normalized arrangement fragments. Each retained Profile segment retains its `arrangement.partN` provenance interval and becomes a stable BRepPlan-side edge/face descendant carrying its slab context. CTC X3 resolves `LeftTopEar.Outer.OuterArc` as one open top-boundary chain and all six `CentralHex` segments as one closed top-boundary loop. No CTC finish is claimed: the current chamfer materializer is intentionally limited to its history-known rectangular profile case.
diff --git a/docs/llm-cad-strategy/05-cad-as-semantic-dependency-graph.md b/docs/llm-cad-strategy/05-cad-as-semantic-dependency-graph.md
index fcbaa672..71a0a80f 100644
--- a/docs/llm-cad-strategy/05-cad-as-semantic-dependency-graph.md
+++ b/docs/llm-cad-strategy/05-cad-as-semantic-dependency-graph.md
@@ -154,6 +154,10 @@ The output should make dependency claims explicit. If a dependency is only guess
## 7. CTC-01 example
+### Topology-selection handoff
+
+For later finishing, a dependency graph must retain authored Profile/Compose identities through the authoritative BRepPlan. SEMANTIC-LOOPS-X1 establishes this for direct Profile extrusion: source segment descendants are selected with explicit body/role/cardinality contracts, never by raw BRep id or geometric rediscovery. The CTC X3 lobe data is ready as a source side of that relation, but its arrangement/transition emitter still needs to publish descendant correspondence before a finish target is admitted. This is an honest compiler boundary, not a license to match the closest cylindrical edge.
+
Use CTC-01 as a conceptual example of better reasoning, not as a historical reconstruction of the original authoring tree.
A naive feature tree might be guessed as:
diff --git a/docs/reconstruction/ctc01-compose-x1.md b/docs/reconstruction/ctc01-compose-x1.md
index 476df2e3..9571ea0e 100644
--- a/docs/reconstruction/ctc01-compose-x1.md
+++ b/docs/reconstruction/ctc01-compose-x1.md
@@ -12,6 +12,10 @@ CTC-DATA-TEMPLATES-X1 adds `ctc01_prismatic_blockout_x3.firmament`. X2 is the pr
`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.
+## Semantic-selection X1 handoff
+
+SEMANTIC-DESCENDANTS-COMPOSE-X2 extends this to the section-stack emitter. Retained arrangement fragments preserve their source parameter intervals and the emitted plan publishes final top/bottom boundary-edge and side-face descendants with slab provenance. `inspect-selections` now resolves the generated `LeftTopEar.Outer.OuterArc` top chain and the six-source `CentralHex` top loop from the X3 source, without coordinate/radius matching or BRep IDs. The current finish materializer remains intentionally rectangular-profile-only, so CTC finishing is not claimed.
+
## Verdict
CTC-BLOCKOUT-X2 succeeds as a bounded prismatic pressure test. The current scaffold-backed Profile + Compose route naturally expresses the dominant plate/web, four observed R50 end transitions, the Z=-60 central plate level, and the central hexagonal raised region. It lowers through three normalized material slabs, four horizontal transitions, one authoritative `PrismaticSectionStackBrepPlan`, and no 3D operation-solid Boolean.
diff --git a/fixtures/FirmamentV2/Hole/valid/semantic-shaft-selection.firmament b/fixtures/FirmamentV2/Hole/valid/semantic-shaft-selection.firmament
new file mode 100644
index 00000000..b1d24079
--- /dev/null
+++ b/fixtures/FirmamentV2/Hole/valid/semantic-shaft-selection.firmament
@@ -0,0 +1,5 @@
+model SemanticShaftSelection {
+ units mm
+ solid base: Box { size: [20, 20, 10] }
+ modify base { hole<shaft> mount { on: face(+Z) center: [1.5, -1] diameter: 4 end: throughAll } }
+}
diff --git a/fixtures/FirmamentV2/Profile/valid/semantic-top-boundary-chamfer.firmament b/fixtures/FirmamentV2/Profile/valid/semantic-top-boundary-chamfer.firmament
new file mode 100644
index 00000000..273179c7
--- /dev/null
+++ b/fixtures/FirmamentV2/Profile/valid/semantic-top-boundary-chamfer.firmament
@@ -0,0 +1,33 @@
+Concept Struct RectangleLayout On XY {
+ Point2 SouthWest { Position: [-10mm, -5mm] }
+ Point2 SouthEast { Position: [10mm, -5mm] }
+ Point2 NorthEast { Position: [10mm, 5mm] }
+ Point2 NorthWest { Position: [-10mm, 5mm] }
+ Line2 South { From: SouthWest; To: SouthEast }
+ Line2 East { From: SouthEast; To: NorthEast }
+ Line2 North { From: NorthEast; To: NorthWest }
+ Line2 West { From: NorthWest; To: SouthWest }
+}
+
+Profile MainPlate Using RectangleLayout {
+ Loop Outer {
+ Segment SouthEdge { Trace: South; From: SouthWest; To: SouthEast }
+ Segment EastEdge { Trace: East; From: SouthEast; To: NorthEast }
+ Segment NorthEdge { Trace: North; From: NorthEast; To: NorthWest }
+ Segment WestEdge { Trace: West; From: NorthWest; To: SouthWest }
+ }
+}
+
+Struct Plate { Extrude MainPlate { Profile: MainPlate; From: -2mm; To: 0mm } }
+
+Selection OuterTopBoundary {
+ Target: TopBoundary
+ Source: MainPlate.ProfileSegments([SouthEdge, EastEdge, NorthEdge, WestEdge])
+ Require: ClosedLoop
+}
+
+EdgeFinish TopEdgeBreak {
+ Target: OuterTopBoundary
+ Kind: Chamfer
+ Distance: 1mm
+}
diff --git a/fixtures/FirmamentV2/Profile/valid/semantic-top-boundary-loop.firmament b/fixtures/FirmamentV2/Profile/valid/semantic-top-boundary-loop.firmament
new file mode 100644
index 00000000..5d311bf2
--- /dev/null
+++ b/fixtures/FirmamentV2/Profile/valid/semantic-top-boundary-loop.firmament
@@ -0,0 +1,27 @@
+Concept Struct RectangleLayout On XY {
+ Point2 SouthWest { Position: [-10mm, -5mm] }
+ Point2 SouthEast { Position: [10mm, -5mm] }
+ Point2 NorthEast { Position: [10mm, 5mm] }
+ Point2 NorthWest { Position: [-10mm, 5mm] }
+ Line2 South { From: SouthWest; To: SouthEast }
+ Line2 East { From: SouthEast; To: NorthEast }
+ Line2 North { From: NorthEast; To: NorthWest }
+ Line2 West { From: NorthWest; To: SouthWest }
+}
+
+Profile MainPlate Using RectangleLayout {
+ Loop Outer {
+ Segment SouthEdge { Trace: South; From: SouthWest; To: SouthEast }
+ Segment EastEdge { Trace: East; From: SouthEast; To: NorthEast }
+ Segment NorthEdge { Trace: North; From: NorthEast; To: NorthWest }
+ Segment WestEdge { Trace: West; From: NorthWest; To: SouthWest }
+ }
+}
+
+Struct Plate { Extrude MainPlate { Profile: MainPlate; From: -2mm; To: 0mm } }
+
+Selection OuterTopBoundary {
+ Target: TopBoundary
+ Source: MainPlate.ProfileSegments([SouthEdge, EastEdge, NorthEdge, WestEdge])
+ Require: ClosedLoop
+}
diff --git a/fixtures/FirmamentV2/ProfileComposition/valid/semantic-split-compose-chamfer.firmament b/fixtures/FirmamentV2/ProfileComposition/valid/semantic-split-compose-chamfer.firmament
new file mode 100644
index 00000000..6ed86643
--- /dev/null
+++ b/fixtures/FirmamentV2/ProfileComposition/valid/semantic-split-compose-chamfer.firmament
@@ -0,0 +1,25 @@
+Rect2 BaseGuide { Center: [0mm, 0mm]; Size: [20mm, 10mm] }
+Rect2 ExtensionGuide { Center: [5mm, 0mm]; Size: [20mm, 10mm] }
+Profile BaseProfile Using ComposeGuide { 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 ExtensionProfile Using ComposeGuide { Loop Outer {
+ Segment South { Trace: ExtensionGuide.Bottom; From: ExtensionGuide.BottomLeft; To: ExtensionGuide.BottomRight }
+ Segment East { Trace: ExtensionGuide.Right; From: ExtensionGuide.BottomRight; To: ExtensionGuide.TopRight }
+ Segment North { Trace: ExtensionGuide.Top; From: ExtensionGuide.TopRight; To: ExtensionGuide.TopLeft }
+ Segment West { Trace: ExtensionGuide.Left; From: ExtensionGuide.TopLeft; To: ExtensionGuide.BottomLeft }
+} }
+Compose JoinedPlate {
+ Base Plate { Profile: BaseProfile; From: -5mm; To: 5mm }
+ Add Extension { Profile: ExtensionProfile; From: -5mm; To: 5mm }
+}
+Selection JoinedTopBoundary {
+ Target: TopBoundary
+ Source: BaseProfile.ProfileSegments([South, East, North, West])
+ Source: ExtensionProfile.ProfileSegments([South, East, North, West])
+ Require: ClosedLoop
+}
+EdgeFinish TopBreak { Target: JoinedTopBoundary; Kind: Chamfer; Distance: 1mm }
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
index 56193730..fbb08ce0 100644
--- a/testdata/firmament/reconstructions/nist_ctc_01/ctc01_prismatic_blockout_x3.firmament
+++ b/testdata/firmament/reconstructions/nist_ctc_01/ctc01_prismatic_blockout_x3.firmament
@@ -37,3 +37,14 @@ Struct Composition { Compose Ctc01PrismaticBlockoutX3 {
Add MidLevelPlate { Profile: MidLevelWeb; From: -60mm; To: 0mm; Role: StrongInferenceMidLevel }
Add CentralRaisedRegion { Profile: CentralHex; From: 0mm; To: 50mm; Role: StrongInferenceCentralRaisedRegion }
} }
+
+Selection LeftTopLobeOuterArc {
+ Target: TopBoundary
+ Source: LeftTopEar.ProfileSegments([OuterArc])
+ Require: ConnectedChain
+}
+Selection CentralHexTopLoop {
+ Target: TopBoundary
+ Source: CentralHex.ProfileSegments([SouthEast, East, NorthEast, NorthWest, West, SouthWest])
+ Require: ClosedLoop
+}