Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Improve Firmament feature reporting and drawing policies

Yuechen Li81918d9c14a6
diff --git a/Aetheris.Kernel.Core.Tests/Step242/StepLegacyQualificationTests.cs b/Aetheris.Kernel.Core.Tests/Step242/StepLegacyQualificationTests.cs
index b87d6c47..d38322b3 100644
--- a/Aetheris.Kernel.Core.Tests/Step242/StepLegacyQualificationTests.cs
+++ b/Aetheris.Kernel.Core.Tests/Step242/StepLegacyQualificationTests.cs
@@ -55,8 +55,12 @@ public sealed class StepLegacyQualificationTests
Assert.Equal(ImportQualificationStatus.Qualified, body.ImportQualification.Status);
Assert.Equal(ImportDisplayStatus.NotAssessed, body.ImportQualification.DisplayStatus);
Assert.Null(body.ImportQualification.DisplayedFaces);
- var mesh = BrepDisplayTessellator.TessellateBoundedPartial(body);
- var report = BrepImportQualification.WithDisplay(body, mesh);
+ // This checks complete display qualification, not wall-clock budget
+ // admission. A partial API can legitimately return five faces on a busy
+ // host; that cannot establish a deterministic six-face expectation.
+ var mesh = BrepDisplayTessellator.Tessellate(body);
+ Assert.True(mesh.IsSuccess);
+ var report = BrepImportQualification.WithDisplay(body, mesh.Value);
Assert.Equal(ImportQualificationStatus.Qualified, report.Status);
Assert.Equal(6, report.DisplayedFaces);
Assert.Empty(report.Reasons);
diff --git a/Aetheris.Kernel.Firmament.Tests/Aetheris.Kernel.Firmament.Tests.csproj b/Aetheris.Kernel.Firmament.Tests/Aetheris.Kernel.Firmament.Tests.csproj
index 83e2c038..04e9c50c 100644
--- a/Aetheris.Kernel.Firmament.Tests/Aetheris.Kernel.Firmament.Tests.csproj
+++ b/Aetheris.Kernel.Firmament.Tests/Aetheris.Kernel.Firmament.Tests.csproj
@@ -46,6 +46,7 @@
</ItemGroup>
<ItemGroup>
+ <ProjectReference Include="..\demos\Aetheris.CodeNativeBracket\Aetheris.CodeNativeBracket.csproj" />
<ProjectReference Include="..\Aetheris.Kernel.Firmament\Aetheris.Kernel.Firmament.csproj" />
<ProjectReference Include="..\Aetheris.Firmament.SchemaGenerator\Aetheris.Firmament.SchemaGenerator.csproj" />
<ProjectReference Include="..\Aetheris.Surfacing\Aetheris.Surfacing.csproj" />
diff --git a/Aetheris.Kernel.Firmament.Tests/CodeNativeBracketRehearsalTests.cs b/Aetheris.Kernel.Firmament.Tests/CodeNativeBracketRehearsalTests.cs
new file mode 100644
index 00000000..18d7ab77
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/CodeNativeBracketRehearsalTests.cs
@@ -0,0 +1,52 @@
+using System.Text;
+using System.Text.Json;
+using Aetheris.CodeNativeBracket;
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class CodeNativeBracketRehearsalTests
+{
+ [Fact]
+ public void TypedFamily_ExportsNominalAndResizedPartThroughRealPaths()
+ {
+ var root = Path.Combine(Path.GetTempPath(), "aetheris-bracket-" + Guid.NewGuid().ToString("N"));
+ try
+ {
+ var specifications = new[] { new BracketDimensions(), new BracketDimensions(100, 75, 25, 24, 15, 70, 12, 8, 14) };
+ foreach (var (spec, index) in specifications.Select((spec, i) => (spec, i)))
+ {
+ var output = Path.Combine(root, index.ToString());
+ Aetheris.CodeNativeBracket.Program.MakeBracket(spec, output);
+ var step = File.ReadAllText(Path.Combine(output, "Bracket.step"));
+ Assert.True(Step242Importer.ImportBody(step).IsSuccess);
+ Assert.Equal(2, Step242SemanticPmiInspector.Inspect(step).Items.Count);
+ var glb = File.ReadAllBytes(Path.Combine(output, "Bracket.glb"));
+ Assert.Equal("glTF", Encoding.ASCII.GetString(glb, 0, 4));
+ using var json = JsonDocument.Parse(glb.AsMemory(20, BitConverter.ToInt32(glb, 12)));
+ Assert.Equal(2, json.RootElement.GetProperty("asset").GetProperty("extras").GetProperty("pmi").GetArrayLength());
+ Assert.Equal("%PDF-", Encoding.ASCII.GetString(File.ReadAllBytes(Path.Combine(output, "Bracket.pdf")), 0, 5));
+ var svg = File.ReadAllText(Path.Combine(output, "Bracket.svg"));
+ Assert.Contains("O (X0, Y0)", svg); Assert.Contains("CSK", svg);
+ Assert.Contains("Process capability / inspection approval pending.", svg);
+ using var drawing = JsonDocument.Parse(File.ReadAllText(Path.Combine(output, "Bracket.drawing.json")));
+ var top = drawing.RootElement.GetProperty("Pages")[0].GetProperty("Views").EnumerateArray().Single(v => v.GetProperty("Identity").GetString() == "TOP");
+ Assert.Equal(2, top.GetProperty("HiddenLinePolicy").GetInt32()); // actual Wireframe, not a silently substituted visibility policy
+ var source = File.ReadAllText(Path.Combine(output, "bracket.firmament"));
+ var rebuilt = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(rebuilt.IsSuccess);
+ Assert.Equal(step, rebuilt.Value.StepText);
+ }
+ Assert.NotEqual(File.ReadAllBytes(Path.Combine(root, "0", "Bracket.step")), File.ReadAllBytes(Path.Combine(root, "1", "Bracket.step")));
+ }
+ finally { if (Directory.Exists(root)) Directory.Delete(root, true); }
+ }
+
+ [Fact]
+ public void LimitsThatPermitBreakout_AreRejectedBeforeArtifacts()
+ {
+ var output = Path.Combine(Path.GetTempPath(), "aetheris-bracket-" + Guid.NewGuid().ToString("N"));
+ Assert.Throws<InvalidOperationException>(() => Aetheris.CodeNativeBracket.Program.MakeBracket(new(HoleY: 6.1), output));
+ Assert.False(Directory.Exists(output));
+ }
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/ComposedHoleFamilyTests.cs b/Aetheris.Kernel.Firmament.Tests/ComposedHoleFamilyTests.cs
new file mode 100644
index 00000000..7dd837b1
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/ComposedHoleFamilyTests.cs
@@ -0,0 +1,281 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Queries;
+using Aetheris.Kernel.Core.Brep.Verification;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.Materializer;
+using Aetheris.Kernel.Firmament.Visualization;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class ComposedHoleFamilyTests
+{
+ private static string Source => FirmamentCorpusHarness.ReadFixtureText("fixtures/Regression/ComposeHoleFamilies/l-bracket-countersink.firmament");
+
+ [Theory]
+ [InlineData(90d)]
+ [InlineData(82d)]
+ [InlineData(120d)]
+ public void CountersinkOnTracedL_IsAnExactClosedConeAndShaft(double angle)
+ {
+ var source = Source.Replace("90deg", FormattableString.Invariant($"{angle}deg"));
+ var result = Admit(source, true);
+ var body = Assert.IsType<BrepBody>(result.RuntimeBody);
+ var parsed = PrismaticProfileCompositionParser.Parse(source);
+ var stack = Assert.IsType<PrismaticSectionStackConstruction>(PrismaticSectionStackCompiler.Normalize(parsed, out var diagnostics));
+ Assert.Empty(diagnostics);
+ var hole = Assert.Single(stack.Feature.CountersinkHoles!);
+ var coneDepth = 3d / Math.Tan(angle * Math.PI / 360d);
+ var expected = 28800d - Math.PI * 9d * 12d - Math.PI * coneDepth * 12d;
+ Assert.Equal(expected, stack.AnalyticVolume, 8);
+ Assert.Equal(coneDepth, hole.ConeDepth, 10);
+ CheckBody(body, expected, angle);
+ var imported = Step242Importer.ImportBody(result.StepText);
+ Assert.True(imported.IsSuccess, string.Join("; ", imported.Diagnostics.Select(d => d.Message)));
+ CheckBody(imported.Value, expected, angle);
+ Assert.Contains(result.RuntimeCorrespondence!.Descendants, d => d.SourceStableId == hole.StableId && d.Role == SemanticTopologyRole.HoleCountersinkWallFace);
+ Assert.Contains(result.RuntimeCorrespondence.Descendants, d => d.SourceStableId == hole.StableId && d.Role == SemanticTopologyRole.HoleWallFace);
+ Assert.Contains(result.RuntimeCorrespondence.Descendants, d => d.SourceStableId == hole.StableId && d.Role == SemanticTopologyRole.HoleEntryLoop);
+ Assert.Equal(result.StepText, FirmamentBuildAndExport.CompileSource(source).Value.StepText);
+ }
+
+ [Theory]
+ [InlineData("Point2(20mm, -10mm)", "Point2(20mm, -17mm)", "ComposeCountersinkFootprintLeavesProfileMaterial")]
+ [InlineData("90deg", "20deg", "ComposeCountersinkDepthExceedsHost")]
+ [InlineData("on: +Z", "on: +X", "ComposeCountersinkAxisUnsupported")]
+ [InlineData("end: ThroughAll", "end: Blind", "")]
+ [InlineData("countersinkDiameter: 12mm", "countersinkDiameter: 5mm", "")]
+ public void UnsupportedCountersinks_RejectInValidateAndBuild(string before, string after, string diagnostic)
+ {
+ var source = Source.Replace(before, after);
+ Admit(source, false);
+ if (diagnostic.Length > 0) Assert.Contains(FirmamentBuildAndExport.CompileSource(source).Diagnostics, d => d.Message.Contains(diagnostic, StringComparison.Ordinal));
+ }
+
+ [Theory]
+ [InlineData("Hole<Countersink>", "Hole<Shaft>")]
+ [InlineData("countersinkDiameter", "countersinkDiametre")]
+ [InlineData("countersinkDiameter: 12mm", "counterboreDepth: 2mm; countersinkDiameter: 12mm")]
+ public void UnknownOrInapplicableFields_NeverDisappear(string before, string after)
+ {
+ Admit(Source.Replace(before, after), false);
+ }
+
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void CavityCollision_DoesNotDependOnDeclarationOrder(bool sinkFirst)
+ {
+ const string shaft = "Hole<Shaft> Other { on: +Z; center: Point2(27mm, -10mm); diameter: 4mm; end: ThroughAll }";
+ var source = Source.Replace(" Hole<Countersink>", sinkFirst ? " Hole<Countersink>" : shaft + "\n Hole<Countersink>");
+ if (sinkFirst) source = source.Replace("end: ThroughAll }", "end: ThroughAll }\n" + shaft);
+ Admit(source, false);
+ Assert.Contains(FirmamentBuildAndExport.CompileSource(source).Diagnostics, d => d.Message.Contains("ComposeCountersinkIntersectsExistingCavity", StringComparison.Ordinal));
+ }
+
+ [Theory]
+ [InlineData("counterbore")]
+ [InlineData("capsule")]
+ [InlineData("rounded-slot")]
+ public void DisjointFeatures_CoexistWithoutOmission(string kind)
+ {
+ var feature = kind switch
+ {
+ "counterbore" => "Hole<Counterbore> Other { on: +Z; center: Point2(-30mm, 20mm); diameter: 4mm; counterboreDiameter: 8mm; counterboreDepth: 2mm; end: ThroughAll }",
+ "capsule" => "Slot<Capsule> Other { center: Point2(-30mm, 20mm); direction: [0, 1]; length: 12mm; width: 4mm; extent: ThroughAll }",
+ _ => "Slot<RoundedRectangle> Other { center: Point2(-30mm, 20mm); direction: [0, 1]; length: 12mm; width: 4mm; cornerRadius: 1mm; extent: ThroughAll }"
+ };
+ var source = Source.Replace(" Hole<Countersink>", feature + "\n Hole<Countersink>");
+ var built = Admit(source, true);
+ Assert.Contains(built.RuntimeCorrespondence!.Descendants, d => d.SourceStableId.EndsWith(".Other", StringComparison.Ordinal));
+ Assert.True(BrepExportPreflight.Validate(built.RuntimeBody!).IsValid);
+ Assert.True(Step242Importer.ImportBody(built.StepText).IsSuccess);
+ }
+
+ [Theory]
+ [InlineData("PlusMinus(0.1mm)")]
+ [InlineData("PlusMinus(0.1mm, 0.1mm)")]
+ public void ShaftPmi_UsesOnlyShaftPatches_AndGlbPresentationRetainsEveryPatch(string tolerance)
+ {
+ var source = Source.Insert(Source.LastIndexOf('}'), $$"""
+ Pmi {
+ Datum A { target: face(+Z) }
+ HoleDiameter ShaftSize { target: Mount; value: 6mm; tolerance: {{tolerance}}; }
+ }
+ """);
+ var product = Admit(source, true);
+ var inspection = Step242SemanticPmiInspector.Inspect(product.StepText);
+ Assert.True(inspection.Success);
+ var diameter = Assert.Single(inspection.Items, p => p.Kind == "Diameter");
+ Assert.Equal(.1, diameter.TolerancePlus); Assert.Equal(.1, diameter.ToleranceMinus);
+ var body = Step242Importer.ImportBody(product.StepText).Value;
+ var faces = body.Bindings.FaceBindings.Where(b => b.SourceStepEntityId.HasValue && diameter.GeometricFaceEntityIds.Contains(b.SourceStepEntityId.Value)).ToArray();
+ Assert.Equal(4, faces.Length);
+ Assert.All(faces, f => Assert.Equal(3d, body.GetFaceSurface(f.FaceId).Cylinder!.Value.Radius, 9));
+ var display = Assert.Single(PmiDisplayProjection.FromStep(product.StepText), p => p.Kind == "Diameter");
+ Assert.Equal(diameter.GeometricFaceEntityIds, display.StepFaceEntities);
+ Assert.Equal("CylinderWall", display.Target!.Kind);
+ Assert.True(display.Lines.Count >= 4);
+ var feature = Assert.Single(product.Features!);
+ Assert.Equal("Countersink", feature.StackKind);
+ Assert.Equal(4, feature.CylindricalFaces); Assert.Equal(4, feature.ConicalFaces);
+ }
+
+ [Fact]
+ public void DifferentCylinderAxes_AreNotCollapsedIntoOnePmiWall()
+ {
+ var source = Source.Replace(" Hole<Countersink>", "Hole<Shaft> Other { on: +Z; center: Point2(-30mm, 20mm); diameter: 6mm; end: ThroughAll }\n Hole<Countersink>");
+ var product = Admit(source, true); var body = product.RuntimeBody!;
+ var faces = body.Topology.Faces.Where(f => body.GetFaceSurface(f.Id).Kind == SurfaceGeometryKind.Cylinder).Select(f => f.Id.Value).ToArray();
+ var step = Step242Exporter.ExportBody(body, [new Step242SemanticPmiHole("group", 6d, null, "test", .1, .1) { GeometricFaceIds = faces }]);
+ Assert.True(step.IsSuccess);
+ var failure = Assert.Throws<InvalidOperationException>(() => PmiDisplayProjection.FromStep(step.Value));
+ Assert.StartsWith("pmi-display-target-multiple-unsupported:", failure.Message);
+ }
+
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public void ARecessNearTheEntry_CannotSilentlyClipTheLargerCavity(bool counterbore)
+ {
+ var source = Source.Replace("Point2 Notch", "Rect2 Relief { center: [26mm, -10mm]; size: [2mm, 2mm] }\n Point2 Notch")
+ .Replace(" Struct BracketBody", "Profile ReliefProfile using Layout { Loop Outer { Relief |> TraceLoop } }\n Struct BracketBody")
+ .Replace("Base Stock { Profile: Bracket; From: 0mm; To: 12mm; Role: Stock }", "Base Stock { Profile: Bracket; From: 0mm; To: 12mm; Role: Stock }\nRemove Recess { profile: ReliefProfile; from: 8mm; to: 12mm }");
+ if (counterbore) source = source.Replace("Hole<Countersink>", "Hole<Counterbore>").Replace("countersinkDiameter: 12mm; countersinkAngle: 90deg", "counterboreDiameter: 12mm; counterboreDepth: 3mm");
+ Admit(source, false);
+ Assert.Contains(FirmamentBuildAndExport.CompileSource(source).Diagnostics, d => d.Message.Contains(counterbore ? "ComposeCounterboreFootprintLeavesProfileMaterial" : "ComposeCountersinkFootprintLeavesProfileMaterial", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void OrientedHoleSupport_RemainsAnExplicitAdmissionBoundary()
+ {
+ var source = Source.Replace("On XY", "On XZ");
+ Admit(source, false);
+ Assert.Contains(FirmamentBuildAndExport.CompileSource(source).Diagnostics, d => d.Message.StartsWith("compose-oriented-feature-not-admitted:", StringComparison.Ordinal));
+ }
+
+ [Theory]
+ [InlineData("Distance: 1mm", true, "")]
+ [InlineData("Distance: 3mm", false, "ProfileBoundaryChamferCountersinkStationOverlapUnsupported")]
+ public void CountersinkAndDisjointPerimeterChamfer_PreserveTheCone(string distance, bool accepted, string diagnostic)
+ {
+ var source = FirmamentCorpusHarness.ReadFixtureText("fixtures/Regression/CanonicalGeometry/profile-compose-reflex-chamfer-with-counterbore.firmament")
+ .Replace("Hole<Counterbore>", "Hole<Countersink>").Replace("CounterboreDiameter: 12mm; CounterboreDepth: 4mm", "CountersinkDiameter: 12mm; CountersinkAngle: 90deg")
+ .Replace("Distance: 1mm", distance);
+ var built = Admit(source, accepted);
+ if (accepted)
+ {
+ var body = Step242Importer.ImportBody(built.StepText).Value;
+ Assert.True(BrepMassProperties.Evaluate(body).IsEnclosed);
+ Assert.Contains(body.Geometry.Surfaces, s => s.Value.Kind == SurfaceGeometryKind.Cone);
+ Assert.Contains(body.Geometry.Surfaces, s => s.Value.Kind == SurfaceGeometryKind.Cylinder);
+ }
+ else Assert.Contains(FirmamentBuildAndExport.CompileSource(source).Diagnostics, d => d.Message.Contains(diagnostic, StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void ComposedFillet_CannotRebuildFreshStockAndLoseTheCountersink()
+ {
+ var source = Source.Insert(Source.LastIndexOf('}'), "Modify BracketBody { EdgeFinish Round { Target: Bracket.Outer.South; On: Top; Kind: Fillet; Radius: 1mm; EndClearance: 2mm } }\n");
+ Admit(source, false);
+ Assert.Contains(FirmamentBuildAndExport.CompileSource(source).Diagnostics, d => d.Message.StartsWith("ProfileBoundaryFilletComposeUnsupported:", StringComparison.Ordinal)
+ && d.Message.Contains("retains its existing material intervals and cavities", StringComparison.Ordinal));
+ }
+
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public void A4LocalPlateEntriesAndPerimeter_AreNotLiftedOntoAnUnrelatedBoss(bool countersink)
+ {
+ var source = FirmamentCorpusHarness.ReadFixtureText("fixtures/Canonical/Integration/machined-mounting-block.firmament");
+ if (countersink) source = source.Replace("Hole<Counterbore>", "Hole<Countersink>")
+ .Replace("counterboreDiameter: 11mm", "countersinkDiameter: 11mm").Replace("counterboreDepth: 3mm", "countersinkAngle: 90deg");
+ var parsed = PrismaticProfileCompositionParser.Parse(source);
+ Assert.Empty(parsed.Diagnostics);
+ if (countersink) Assert.All(parsed.Feature!.CountersinkHoles!, h => Assert.Equal(12d, h.To));
+ else Assert.All(parsed.Feature!.CounterboreHoles!, h => Assert.Equal(12d, h.To));
+ var built = Admit(source, true);
+ var body = Step242Importer.ImportBody(built.StepText).Value;
+ Assert.True(BrepExportPreflight.Validate(body).IsValid);
+ var mass = BrepMassProperties.Evaluate(body, new(.001, Math.PI / 360d, .001, MinimumSegments: 64, MaximumSegments: 256));
+ Assert.True(mass.IsEnclosed);
+ var removedEntries = countersink ? 2d * Math.PI * 2.5d * (5.5d * 5.5d + 5.5d * 3d - 18d) / 3d : 2d * Math.PI * (5.5d * 5.5d - 9d) * 3d;
+ var expected = 70d * 44d * 12d + 14d * 14d * 6d - 20d * 16d * 4d
+ - Math.PI * (9d * 18d + 2d * 9d * 12d) - removedEntries - (70d + 44d - 4d / 3d);
+ var stack = PrismaticSectionStackCompiler.Normalize(parsed, out _)!;
+ var profile = parsed.Profiles["BaseProfile"];
+ Assert.True(ProfileBoundaryChamferSourceBinder.TryBind(source, profile, stack.Feature.Name, out var target, out var distance, out _));
+ var finished = ComposedProfileBoundaryChamferStackPlanner.TryApply(stack, profile, target!, distance, out var planDiagnostics);
+ Assert.Empty(planDiagnostics);
+ Assert.Equal(expected, finished!.AnalyticVolume, 8);
+ Assert.InRange(Math.Abs(mass.AbsoluteVolume - expected), 0d, Math.Min(mass.ErrorBound ?? 0d, .01d));
+ Assert.All(built.Features!.Where(h => h.Name is "MountNorth" or "MountSouth"), h =>
+ {
+ Assert.True(h.CylindricalFaces > 0);
+ if (countersink) Assert.True(h.ConicalFaces > 0);
+ });
+ }
+
+ [Theory]
+ [InlineData(16, true)]
+ [InlineData(8, false)]
+ public void CountersinkEntryMustFitTheExposedPocketFloor(int size, bool accepted)
+ {
+ var source = Source.Replace("Point2 Notch", $"Rect2 Relief {{ center: [20mm, -10mm]; size: [{size}mm, {size}mm] }}\n Point2 Notch")
+ .Replace(" Struct BracketBody", "Profile ReliefProfile using Layout { Loop Outer { Relief |> TraceLoop } }\n Struct BracketBody")
+ .Replace("Base Stock { Profile: Bracket; From: 0mm; To: 12mm; Role: Stock }", "Base Stock { Profile: Bracket; From: 0mm; To: 12mm; Role: Stock }\nRemove Recess { profile: ReliefProfile; from: 8mm; to: 12mm }");
+ var parsed = PrismaticProfileCompositionParser.Parse(source);
+ if (!accepted) { Admit(source, false); Assert.Contains(parsed.Diagnostics, d => d.Contains("entry-footprint-is-not-contained", StringComparison.Ordinal)); return; }
+ Assert.Empty(parsed.Diagnostics);
+ Assert.Equal(8d, Assert.Single(parsed.Feature!.CountersinkHoles!).To);
+ var built = Admit(source, true);
+ var body = Step242Importer.ImportBody(built.StepText).Value;
+ Assert.True(BrepExportPreflight.Validate(body).IsValid);
+ Assert.Contains(body.Geometry.Curves, c => c.Value.Circle3 is { } arc && Math.Abs(arc.Center.Z - 8d) < 1e-9 && Math.Abs(arc.Radius - 6d) < 1e-9);
+ }
+
+ private static void CheckBody(BrepBody body, double expectedVolume, double angle)
+ {
+ Assert.True(BrepExportPreflight.Validate(body).IsValid);
+ var mass = BrepMassProperties.Evaluate(body);
+ Assert.True(mass.IsEnclosed);
+ Assert.True(mass.IsOrientationConsistent);
+ // The generic cone verifier is a bounded tessellation estimate. Exact
+ // volume is checked against the construction integral above; never
+ // pretend its display-mesh sanity estimate has analytic precision.
+ Assert.InRange(Math.Abs(mass.AbsoluteVolume - expectedVolume), 0d, Math.Min(mass.ErrorBound ?? 0d, expectedVolume * 2e-5));
+ var cones = body.Geometry.Surfaces.Where(s => s.Value.Kind == SurfaceGeometryKind.Cone).ToArray();
+ Assert.NotEmpty(cones);
+ Assert.All(cones, c => Assert.Equal(angle * Math.PI / 360d, c.Value.Cone!.Value.SemiAngleRadians, 10));
+ var coneFrom = 12d - 3d / Math.Tan(angle * Math.PI / 360d);
+ foreach (var face in body.Topology.Faces.Where(f => body.GetFaceSurface(f.Id).Kind == SurfaceGeometryKind.Cone))
+ {
+ var surface = body.GetFaceSurface(face.Id).Cone!.Value;
+ Assert.Equal(20d, surface.PlacementOrigin.X, 9);
+ Assert.Equal(-10d, surface.PlacementOrigin.Y, 9);
+ Assert.Equal(coneFrom, surface.PlacementOrigin.Z, 9);
+ var arcs = face.LoopIds.SelectMany(id => body.Topology.Loops.Single(l => l.Id == id).CoedgeIds)
+ .Select(id => body.Topology.Coedges.Single(c => c.Id == id).EdgeId)
+ .Select(id => { Assert.True(body.TryGetEdgeCurveGeometry(id, out var curve)); return curve!; }).Where(c => c.Kind == CurveGeometryKind.Circle3).Select(c => c.Circle3!.Value).ToArray();
+ Assert.Contains(arcs, c => Math.Abs(c.Radius - 3d) < 1e-9 && Math.Abs(c.Center.Z - coneFrom) < 1e-9);
+ Assert.Contains(arcs, c => Math.Abs(c.Radius - 6d) < 1e-9 && Math.Abs(c.Center.Z - 12d) < 1e-9);
+ }
+ Assert.Contains(body.Geometry.Surfaces, s => s.Value.Kind == SurfaceGeometryKind.Cylinder && Math.Abs(s.Value.Cylinder!.Value.Radius - 3d) < 1e-9);
+ Assert.Equal(-40d, body.Topology.Vertices.Select(v => { Assert.True(body.TryGetVertexPoint(v.Id, out var p)); return p; }).Min(p => p.X), 9);
+ Assert.Equal(40d, body.Topology.Vertices.Select(v => { Assert.True(body.TryGetVertexPoint(v.Id, out var p)); return p; }).Max(p => p.X), 9);
+ Assert.Equal(-20d, body.Topology.Vertices.Select(v => { Assert.True(body.TryGetVertexPoint(v.Id, out var p)); return p; }).Min(p => p.Y), 9);
+ Assert.Equal(40d, body.Topology.Vertices.Select(v => { Assert.True(body.TryGetVertexPoint(v.Id, out var p)); return p; }).Max(p => p.Y), 9);
+ Assert.Equal(0d, body.Topology.Vertices.Select(v => { Assert.True(body.TryGetVertexPoint(v.Id, out var p)); return p; }).Min(p => p.Z), 9);
+ Assert.Equal(12d, body.Topology.Vertices.Select(v => { Assert.True(body.TryGetVertexPoint(v.Id, out var p)); return p; }).Max(p => p.Z), 9);
+ }
+
+ private static FirmamentStepExportResult Admit(string source, bool accepted)
+ {
+ var validation = FirmamentBuildAdmissionValidation.Admit(FirmamentV2ValidationReportBuilder.Build(FirmamentV2Parser.Parse(source)), source);
+ var build = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(validation.Status == (accepted ? "valid" : "invalid"), string.Join("; ", build.Diagnostics.Select(d => d.Message)));
+ Assert.True(build.IsSuccess == accepted, string.Join("; ", build.Diagnostics.Select(d => d.Message)));
+ return accepted ? build.Value : null!;
+ }
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/PrismaticSectionStackHoleTraversalTests.cs b/Aetheris.Kernel.Firmament.Tests/PrismaticSectionStackHoleTraversalTests.cs
index 916a01eb..333245b3 100644
--- a/Aetheris.Kernel.Firmament.Tests/PrismaticSectionStackHoleTraversalTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/PrismaticSectionStackHoleTraversalTests.cs
@@ -6,6 +6,26 @@ namespace Aetheris.Kernel.Firmament.Tests;
public sealed class PrismaticSectionStackHoleTraversalTests
{
+ [Fact]
+ public void UnsupportedBoundaryDistance_CannotBePromotedToInsideMaterial()
+ {
+ var original = Stack();
+ var slabs = original.Slabs.Select(s =>
+ {
+ var profile = s.Region.Outer;
+ var first = profile.Loops[0].Segments[0]; var line = Assert.IsType<LineArcLineSegment2D>(first.Geometry);
+ var cubic = new LineArcCubicBezier2D(line.Start, line.Start, line.End, line.End);
+ var loop = profile.Loops[0] with { Segments = profile.Loops[0].Segments.Select((segment, i) => i == 0 ? segment with { Geometry = cubic } : segment).ToArray() };
+ var region = s.Region with { Outer = profile with { Loops = [loop] } };
+ return s with { Region = region, RegionSet = [region] };
+ }).ToArray();
+ var stack = original with { Slabs = slabs }; var placement = Placement(new Point3D(0, 0, 0), new Vector3D(0, 0, 1));
+ var feature = Feature(4d, placement);
+ var evidence = PrismaticSectionStackHoleTraversal.Traverse(feature, stack, placement);
+ Assert.All(evidence.FootprintChecks, check => Assert.Equal(SectionStackFootprintClassification.Ambiguous, check.Classification));
+ Assert.False(HoleEndConditionContract.Evaluate(feature, evidence.HostTraversal).ContractSatisfied);
+ }
+
[Fact]
public void AxialConstructionPlaneHole_OnePhysicalSpanMayCrossTwoPlannerSlabs()
{
diff --git a/Aetheris.Kernel.Firmament/Drawing/DrawingProjectionEngine.cs b/Aetheris.Kernel.Firmament/Drawing/DrawingProjectionEngine.cs
index dae89392..617446d4 100644
--- a/Aetheris.Kernel.Firmament/Drawing/DrawingProjectionEngine.cs
+++ b/Aetheris.Kernel.Firmament/Drawing/DrawingProjectionEngine.cs
@@ -49,7 +49,7 @@ internal static class DrawingProjectionEngine
foreach (var line in samples.Boundaries)
{
var edge = body.Topology.Edges.Single(e => e.Id.Value == line.EdgeId);
- if (IsCoplanarInternalEdge(body, edge.Id)) continue;
+ if (IsInternalSupportEdge(body, edge.Id)) continue;
var curved = body.TryGetEdgeCurveGeometry(edge.Id, out var curve) && curve?.Kind != CurveGeometryKind.Line3;
var points = curved ? line.Points : new[] { line.Points[0], line.Points[^1] };
raw.Add(new(line.Identity, projectionBody.OccurrenceIdentity, projectionBody.DefinitionIdentity, points.Select(Camera).ToArray(), curved));
@@ -173,14 +173,24 @@ internal static class DrawingProjectionEngine
private static CameraPoint Lerp(CameraPoint a, CameraPoint b, double t) => new(a.X + (b.X - a.X) * t, a.Y + (b.Y - a.Y) * t, a.Depth + (b.Depth - a.Depth) * t);
private static Vector3D Normalize(Vector3D vector) { var length = Math.Sqrt(vector.Dot(vector)); if (length < 1e-12) throw new InvalidOperationException("drawing-view-direction-zero"); return vector * (1 / length); }
- private static bool IsCoplanarInternalEdge(BrepBody body, Aetheris.Kernel.Core.Topology.EdgeId edgeId)
+ private static bool IsInternalSupportEdge(BrepBody body, Aetheris.Kernel.Core.Topology.EdgeId edgeId)
{
var loopIds = body.Topology.Coedges.Where(coedge => coedge.EdgeId == edgeId).Select(coedge => coedge.LoopId).ToHashSet();
var faces = body.Topology.Faces.Where(face => face.LoopIds.Any(loopIds.Contains)).ToArray();
if (faces.Length != 2) return false;
- if (!body.TryGetFaceSurfaceGeometry(faces[0].Id, out var first) || !body.TryGetFaceSurfaceGeometry(faces[1].Id, out var second)
- || first?.Plane is not { } a || second?.Plane is not { } b) return false;
- var na = a.Normal.ToVector(); var nb = b.Normal.ToVector();
- return Math.Abs(Math.Abs(na.Dot(nb)) - 1) < 1e-8 && Math.Abs((b.Origin - a.Origin).Dot(na)) < 1e-7;
+ if (!body.TryGetFaceSurfaceGeometry(faces[0].Id, out var first) || !body.TryGetFaceSurfaceGeometry(faces[1].Id, out var second)) return false;
+ if (first?.Plane is { } a && second?.Plane is { } b)
+ return Math.Abs(Math.Abs(a.Normal.ToVector().Dot(b.Normal.ToVector())) - 1) < 1e-8
+ && Math.Abs((b.Origin - a.Origin).Dot(a.Normal.ToVector())) < 1e-7;
+ if (first?.Cylinder is { } ca && second?.Cylinder is { } cb)
+ {
+ var axis = ca.Axis.ToVector(); var delta = cb.Origin - ca.Origin;
+ return Math.Abs(ca.Radius - cb.Radius) < 1e-7 && axis.Cross(cb.Axis.ToVector()).Length < 1e-8
+ && (delta - axis * delta.Dot(axis)).Length < 1e-7;
+ }
+ if (first?.Cone is { } sa && second?.Cone is { } sb)
+ return Math.Abs(sa.SemiAngleRadians - sb.SemiAngleRadians) < 1e-8 && (sa.Apex - sb.Apex).Length < 1e-7
+ && sa.Axis.ToVector().Dot(sb.Axis.ToVector()) > 1 - 1e-8;
+ return false;
}
}
diff --git a/Aetheris.Kernel.Firmament/Drawing/FirmamentDrawingSyntax.cs b/Aetheris.Kernel.Firmament/Drawing/FirmamentDrawingSyntax.cs
index 9c9428dc..5a7fc11f 100644
--- a/Aetheris.Kernel.Firmament/Drawing/FirmamentDrawingSyntax.cs
+++ b/Aetheris.Kernel.Firmament/Drawing/FirmamentDrawingSyntax.cs
@@ -121,7 +121,8 @@ public static partial class FirmamentDrawingCompiler
if(hidden is not ("VisibleOnly" or "VisibleAndHidden" or "Wireframe"))view.Invalid("HiddenLines");
var pmi=List(view,"PMI",false);
var kind=projection=="Isometric" || projection is null && direction.Count(v=>Math.Abs(v)>1e-12)>1?DrawingProjectionKind.Isometric:DrawingProjectionKind.Orthographic;
- views.Add(new(view.Name,direction,kind,hidden=="VisibleAndHidden"?DrawingHiddenLinePolicy.VisibleAndHidden:DrawingHiddenLinePolicy.VisibleOnly,pmi));
+ views.Add(new(view.Name,direction,kind,hidden switch
+ { "Wireframe" => DrawingHiddenLinePolicy.Wireframe, "VisibleAndHidden" => DrawingHiddenLinePolicy.VisibleAndHidden, _ => DrawingHiddenLinePolicy.VisibleOnly },pmi));
}
if(views.Count==0)diagnostics.Add(DrawingViewMissing);
if(views.Select(v=>v.Name).Distinct().Count()!=views.Count)diagnostics.Add("drawing-view-duplicate");
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
index ed1da513..ec1816ee 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
@@ -481,6 +481,7 @@ public static partial class FirmamentBuildAndExport
if (!support.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(support.Diagnostics);
var features = (stack.Feature.ShaftHoles ?? []).ToDictionary(hole => hole.Name, hole => hole.StableId, StringComparer.Ordinal);
foreach (var hole in stack.Feature.CounterboreHoles ?? []) features[hole.Name] = hole.StableId;
+ foreach (var hole in stack.Feature.CountersinkHoles ?? []) features[hole.Name] = hole.StableId;
semanticPmi = BuildV2SemanticPmi(v2Parse.Document, [], stack.Feature.Name, features, emitted.Correspondence, completedBody).ToArray();
}
var step = Step242Exporter.ExportBody(completedBody, semanticPmi);
@@ -488,8 +489,9 @@ public static partial class FirmamentBuildAndExport
return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, stack.Feature.Name, 0, "prismatic-section-stack", "line-arc-profile-composition",
DatumInspection: v2Parse.Document?.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.DatumPlane).Select(p => new FirmamentPmiInspectionDatum(p.Name, "planar", p.Target)).ToArray() ?? [],
DimensionInspection: v2Parse.Document?.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.HoleDiameter).Select(p => new FirmamentPmiInspectionDimension("Diameter", p.Target, null, p.Value ?? 0d, "explicit-v2-record-pmi", p.Name)).ToArray() ?? [],
- Features: CompositionHoleReports(stack.Feature),
- EngineeringFeatures: EngineeringFeatureReports(stack.Feature)));
+ Features: CompositionHoleReports(stack.Feature, completedBody, emitted.Correspondence),
+ EngineeringFeatures: EngineeringFeatureReports(stack.Feature))
+ { RuntimeBody = completedBody, RuntimeCorrespondence = emitted.Correspondence, RuntimeBodySourceName = stack.Feature.Name });
}
if (v2Parse.BoundProfile is not null || (!v2Parse.OwnsUnifiedAdmission && ProfileAuthoringParser.IsProfileSource(materializerSource)))
{
@@ -1109,7 +1111,7 @@ public static partial class FirmamentBuildAndExport
if (filletProfile is null || filletTarget is null) return Fail(filletDiagnostic ?? "ProfileBoundaryFilletProfileUnknown");
var filletAdmission = ProfileStraightEdgeFilletAdmissionChecker.Check(stack, filletProfile, filletTarget, radius, clearance);
if (!filletAdmission.Disjoint) return Fail(filletAdmission.Diagnostics.FirstOrDefault() ?? "ProfileBoundaryFilletCavityInteractionUnsupported");
- return Fail("ProfileBoundaryFilletComposeUnsupported");
+ return Fail("ProfileBoundaryFilletComposeUnsupported: A composed-body fillet requires an adapter that retains its existing material intervals and cavities. The current profile fillet planner constructs a fresh extrusion; it cannot replace this body without losing authored features. No geometry was emitted.");
}
ProfileBoundaryChamferTarget? target = null; double distance = 0d; string? bindingDiagnostic = null; ResolvedProfile2D? profile = null;
foreach (var candidate in parsed.Profiles.Values.OrderBy(x => x.Name, StringComparer.Ordinal))
@@ -1131,6 +1133,7 @@ public static partial class FirmamentBuildAndExport
if (!support.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(support.Diagnostics);
var features = (stack.Feature.ShaftHoles ?? []).ToDictionary(hole => hole.Name, hole => hole.StableId, StringComparer.Ordinal);
foreach (var hole in stack.Feature.CounterboreHoles ?? []) features[hole.Name] = hole.StableId;
+ foreach (var hole in stack.Feature.CountersinkHoles ?? []) features[hole.Name] = hole.StableId;
semanticPmi = BuildV2SemanticPmi(canonicalDocument, [], stack.Feature.Name, features, plannedEmission.Correspondence, plannedEmission.Body).ToArray();
}
var plannedStep = Step242Exporter.ExportBody(plannedEmission.Body, semanticPmi, new Step242ExportOptions { ProductName = target.StableId, ApplicationName = "Aetheris.Firmament.ComposedProfileBoundaryChamfer.M3", BrepExportPreflightMode = BrepExportPreflightMode.Enforce, BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute });
@@ -1140,7 +1143,7 @@ public static partial class FirmamentBuildAndExport
return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(plannedStep.Value, target.StableId, 0, "composed-profile-boundary-chamfer-section-stack", "source-grounded-composed-profile-boundary-chamfer",
DatumInspection: canonicalDocument?.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.DatumPlane).Select(p => new FirmamentPmiInspectionDatum(p.Name, "planar", p.Target)).ToArray() ?? [],
DimensionInspection: canonicalDocument?.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.HoleDiameter).Select(p => new FirmamentPmiInspectionDimension("Diameter", p.Target, null, p.Value ?? 0d, "explicit-v2-record-pmi", p.Name)).ToArray() ?? [],
- Features: CompositionHoleReports(stack.Feature),
+ Features: CompositionHoleReports(stack.Feature, plannedEmission.Body!, plannedEmission.Correspondence),
EngineeringFeatures: EngineeringFeatureReports(stack.Feature).Append(new FirmamentEngineeringFeatureReport(
target.StableId["edgefinish:".Length..],
"EdgeFinish",
@@ -2854,6 +2857,11 @@ public static partial class FirmamentBuildAndExport
.Where(descendant => descendant.Face.HasValue
&& (string.Equals(descendant.SourceStableId, item.FeatureId, StringComparison.Ordinal)
|| string.Equals(descendant.ParentStableId, item.FeatureId, StringComparison.Ordinal)))
+ // Shaft dimensions follow semantic wall ownership, not the
+ // asserted PMI number: contradictory PMI must keep its target
+ // so downstream geometry/requirement checks can diagnose it.
+ .Where(descendant => item is not Step242SemanticPmiHole
+ || descendant.Role is not (SemanticTopologyRole.HoleCounterboreWallFace or SemanticTopologyRole.HoleCountersinkWallFace))
.Select(descendant => descendant.Face!.Value.Value)
.Distinct()
.Order()
@@ -2972,17 +2980,33 @@ public static partial class FirmamentBuildAndExport
.OrderBy(item => item.FeatureId, StringComparer.Ordinal)
.ToArray();
- private static IReadOnlyList<FirmamentHoleFeatureReport> CompositionHoleReports(PrismaticProfileCompositionFeature feature) =>
+ private static IReadOnlyList<FirmamentHoleFeatureReport> CompositionHoleReports(PrismaticProfileCompositionFeature feature, BrepBody body, SemanticTopologyCorrespondence? correspondence) =>
(feature.ShaftHoles ?? []).Select(item => new FirmamentHoleFeatureReport(
item.Name, "Hole<Shaft>", item.StableId, item.Diameter, item.CenterX, item.CenterY,
null, "ProfileCompose.Center", null, null, "+Z", item.SourceSpan,
- "PrismaticSectionStack/Remove", "SemanticShaftProfile", "ThroughAll",
+ "PrismaticSectionStack/Remove", "SemanticShaftProfile", "SimpleShaft",
SupportSpan: item.SupportSpan, ParentSupport: item.ParentSupport, SupportBoundaryMargin: item.SupportBoundaryMargin))
.Concat((feature.CounterboreHoles ?? []).Select(item => new FirmamentHoleFeatureReport(
item.Name, "Hole<Counterbore>", item.StableId, item.Diameter, item.CenterX, item.CenterY,
null, "ProfileCompose.Center", null, null, "+Z", item.SourceSpan,
- "PrismaticSectionStack/Remove", "SemanticCounterboreProfiles", "ThroughAll",
+ "PrismaticSectionStack/Remove", "SemanticCounterboreProfiles", "Counterbore",
SupportSpan: item.SupportSpan, ParentSupport: item.ParentSupport, SupportBoundaryMargin: item.SupportBoundaryMargin)))
+ .Concat((feature.CountersinkHoles ?? []).Select(item => new FirmamentHoleFeatureReport(
+ item.Name, "Hole<Countersink>", item.StableId, item.Diameter, item.CenterX, item.CenterY,
+ null, "ProfileCompose.Center", null, null, "+Z", item.SourceSpan,
+ "PrismaticSectionStack/VariableCircularCavity", "SemanticCountersinkProfile", "Countersink",
+ SupportSpan: item.SupportSpan, ParentSupport: item.ParentSupport, SupportBoundaryMargin: item.SupportBoundaryMargin)))
+ .Select(report =>
+ {
+ var surfaces = (correspondence?.Descendants ?? []).Where(d => d.SourceStableId == report.FeatureId && d.Face.HasValue)
+ .Select(d => d.Face!.Value).Distinct().Select(body.GetFaceSurface).ToArray();
+ return report with
+ {
+ CylindricalFaces = surfaces.Count(s => s.Kind == SurfaceGeometryKind.Cylinder),
+ ConicalFaces = surfaces.Count(s => s.Kind == SurfaceGeometryKind.Cone),
+ PlanarFaces = surfaces.Count(s => s.Kind == SurfaceGeometryKind.Plane)
+ };
+ })
.OrderBy(item => item.FeatureId, StringComparer.Ordinal)
.ToArray();
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index 02c63320..71f237e6 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -1268,7 +1268,7 @@ public static partial class FirmamentV2Parser
[feature.Name] = new FirmamentV2SolidBinding(feature.Name, "Compose", new FirmamentV2AdvancedMaterialRecord("Compose"))
};
var (compositionPmi, compositionPmiBlock, compositionBoundPmi) = ParsePmi(
- source, compositionSolids, [], [], [], [], diagnostics, (feature.ShaftHoles ?? []).Select(hole => hole.Name).Concat((feature.CounterboreHoles ?? []).Select(hole => hole.Name)));
+ source, compositionSolids, [], [], [], [], diagnostics, (feature.ShaftHoles ?? []).Select(hole => hole.Name).Concat((feature.CounterboreHoles ?? []).Select(hole => hole.Name)).Concat((feature.CountersinkHoles ?? []).Select(hole => hole.Name)));
if (Regex.IsMatch(body, @"\bEdgeFinish\b", RegexOptions.CultureInvariant)
&& !ProfileBoundaryChamferSourceBinder.HasSemanticProfileBoundaryFinish(body)
&& composition.Profiles.Values.Any(profile => profile.Loops.Single().Segments.Count != 4))
@@ -2378,7 +2378,7 @@ public static partial class FirmamentV2Parser
var entryClose = FindMatchingBrace(body, entryOpen);
if (entryClose < 0) { diagnostics.Add(UnsupportedConstruct); continue; }
var eb = body[(entryOpen + 1)..entryClose];
- var fields = ParsePmiFields(eb, open + 1 + entryOpen, diagnostics);
+ var fields = ParsePmiFields(eb, open + 2 + entryOpen, diagnostics);
ValidatePmiFieldSet(kindRaw, name, fields, diagnostics);
var record = new FirmamentV2PmiRecord(kind, name, fields, new FirmamentV2SourceSpan(open + 1 + em.Index, entryClose - em.Index + 1));
records.Add(record);
@@ -2397,21 +2397,20 @@ public static partial class FirmamentV2Parser
private static Dictionary<string, FirmamentV2PmiField> ParsePmiFields(string body, int baseOffset, List<string> diagnostics)
{
var fields = new Dictionary<string, FirmamentV2PmiField>(StringComparer.Ordinal);
- // Capture every field first. A whitelist-only capture silently lost
- // misspellings such as Tolerence, precisely what canonical PMI must not do.
- var fieldRegex = new Regex(@"(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*(?<value>.*?)(?=\s+[A-Za-z_][A-Za-z0-9_]*\s*:|$)", RegexOptions.CultureInvariant | RegexOptions.Singleline);
- foreach (Match m in fieldRegex.Matches(body))
- {
- var n = NormalizePmiField(m.Groups["name"].Value);
- var v = m.Groups["value"].Value.Trim();
- if (v.EndsWith("}", StringComparison.Ordinal)) v = v[..^1].Trim();
- if (string.Equals(m.Groups["name"].Value, "DatumRefs", StringComparison.Ordinal)
- && v.StartsWith("[", StringComparison.Ordinal) && v.EndsWith("]", StringComparison.Ordinal))
+ // Reuse the structural field boundaries. A trailing semicolon is syntax,
+ // not part of a target, length or tolerance expression.
+ var syntax = FirmamentSyntaxParser.Parse(body);
+ diagnostics.AddRange(syntax.Diagnostics.Select(d => d.Code));
+ foreach (var statement in syntax.Document.Statements)
+ {
+ if (statement is not FieldSyntax field) { diagnostics.Add(PmiUnsupported); continue; }
+ var n = NormalizePmiField(field.Name.Text);
+ var v = body.Substring(field.Value.Span.Start, field.Value.Span.Length).Trim();
+ if (n == "datum" && field.Value is SequenceSyntax && v.StartsWith("[", StringComparison.Ordinal) && v.EndsWith("]", StringComparison.Ordinal))
v = v[1..^1].Trim();
if (fields.ContainsKey(n)) { diagnostics.Add(PmiDuplicateField); continue; }
- fields[n] = new(n, v, new FirmamentV2SourceSpan(baseOffset + m.Index, m.Length), null);
+ fields[n] = new(n, v, new FirmamentV2SourceSpan(baseOffset + field.Span.Start, field.Span.Length), null);
}
- if (fields.Count == 0 && body.Split(['\r','\n'], StringSplitOptions.RemoveEmptyEntries).Any(l => l.Trim().Length > 0)) diagnostics.Add(PmiUnsupported);
return fields;
}
@@ -2503,13 +2502,17 @@ public static partial class FirmamentV2Parser
private static bool TryParseToleranceLiteral(string s,List<string>d,out FirmamentV2Tolerance tol)
{
tol=null!;
- var plusMinus = Regex.Match(s, @"^PlusMinus\(\s*(?<plus>[-+]?\d+(?:\.\d+)?)mm\s*,\s*(?<minus>[-+]?\d+(?:\.\d+)?)mm\s*\)$", RegexOptions.CultureInvariant);
- if (plusMinus.Success)
- {
- var plus = double.Parse(plusMinus.Groups["plus"].Value, CultureInfo.InvariantCulture);
- var minus = double.Parse(plusMinus.Groups["minus"].Value, CultureInfo.InvariantCulture);
- if (plus < 0 || minus < 0) { d.Add(PmiToleranceTypeMismatch); return false; }
- tol = new(FirmamentV2ToleranceKind.Asymmetric, plus, minus, "mm", FirmamentV2PrimitiveType.Length, new(0, s.Length));
+ var expression = FirmamentSyntaxParser.ParseExpression(s);
+ if (expression.Expression is CallSyntax call && FirmamentSyntaxValues.Reference(call.Target) == "PlusMinus")
+ {
+ if (expression.Diagnostics.Count > 0 || call.Arguments.Count is < 1 or > 2 || call.Arguments.Any(a => a.Name is not null)
+ || !FirmamentSyntaxValues.TryMeasure(call.Arguments[0].Value, "mm", out var plus) || !double.IsFinite(plus) || plus < 0)
+ { d.Add(PmiToleranceTypeMismatch); return false; }
+ var minus = plus;
+ if (call.Arguments.Count == 2 && (!FirmamentSyntaxValues.TryMeasure(call.Arguments[1].Value, "mm", out minus) || !double.IsFinite(minus) || minus < 0))
+ { d.Add(PmiToleranceTypeMismatch); return false; }
+ tol = new(call.Arguments.Count == 1 ? FirmamentV2ToleranceKind.Bilateral : FirmamentV2ToleranceKind.Asymmetric,
+ plus, minus, "mm", FirmamentV2PrimitiveType.Length, new(0, s.Length));
return true;
}
var t=ParseTolerance(FirmamentV2PrimitiveType.Length,s,d); if(t is null){d.Add(PmiToleranceTypeMismatch); return false;} tol=t; return true;
diff --git a/Aetheris.Kernel.Firmament/Materializer/ComposedProfileBoundaryChamferAdmission.cs b/Aetheris.Kernel.Firmament/Materializer/ComposedProfileBoundaryChamferAdmission.cs
index 22a70d7d..e644981f 100644
--- a/Aetheris.Kernel.Firmament/Materializer/ComposedProfileBoundaryChamferAdmission.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/ComposedProfileBoundaryChamferAdmission.cs
@@ -31,7 +31,8 @@ public static class ComposedProfileBoundaryChamferAdmissionChecker
var loop = profile.Loops.SingleOrDefault(x => x.Name == target.LoopId);
if (loop is null || !loop.IsOuter || loop.Segments.Any(x => x.Geometry is not LineArcLineSegment2D))
return new(false, null, [], ["ProfileBoundaryChamferSegmentKindUnsupported"]);
- var top = stack.Feature.CriticalLevels.Max();
+ if (ComposedProfileBoundaryChamferStackPlanner.SupportLevel(stack, profile) is not { } top)
+ return new(false, null, [], ["ProfileBoundaryChamferComposeProfileSupportMissing"]);
var corridor = new ProfileBoundaryChamferCorridor(target.StableId, profile.Name, loop.Name, distance, top - distance, top, target.SegmentIds);
var interactions = new List<ProfileBoundaryChamferCavityInteraction>();
foreach (var hole in stack.Feature.ShaftHoles ?? [])
@@ -45,6 +46,11 @@ public static class ComposedProfileBoundaryChamferAdmissionChecker
if (boreFrom > hole.From + Tol)
interactions.Add(Classify(loop, corridor, hole.StableId, "CounterboreShaft", hole.CenterX, hole.CenterY, hole.Diameter / 2d, hole.From, boreFrom));
}
+ foreach (var hole in stack.Feature.CountersinkHoles ?? [])
+ {
+ interactions.Add(Classify(loop, corridor, hole.StableId, "Countersink", hole.CenterX, hole.CenterY, hole.CountersinkDiameter / 2d, hole.ConeFrom, hole.To));
+ interactions.Add(Classify(loop, corridor, hole.StableId, "CountersinkShaft", hole.CenterX, hole.CenterY, hole.Diameter / 2d, hole.From, hole.ConeFrom));
+ }
var rejected = interactions.Where(x => x.Classification != "Disjoint").ToArray();
return new(rejected.Length == 0, corridor, interactions,
rejected.Select(x => x.Diagnostic).Distinct(StringComparer.Ordinal).ToArray());
@@ -64,7 +70,8 @@ public static class ComposedProfileBoundaryChamferAdmissionChecker
// result is intentionally rejected; a later exact cell test may only relax it.
if (boundaryDistance <= radius + corridor.Distance + Tol)
{
- var code = kind == "Shaft" ? "ProfileBoundaryChamferIntersectsShaft" : "ProfileBoundaryChamferIntersectsCounterbore";
+ var code = kind == "Shaft" ? "ProfileBoundaryChamferIntersectsShaft"
+ : kind.StartsWith("Countersink", StringComparison.Ordinal) ? "ProfileBoundaryChamferIntersectsCountersink" : "ProfileBoundaryChamferIntersectsCounterbore";
var classification = Math.Abs(boundaryDistance - radius - corridor.Distance) <= Tol ? "TouchingWithinTolerance" : "Intersecting";
return new(featureId, kind, x, y, radius, from, to, classification,
$"{code}:edgeFinish={corridor.EdgeFinishId}:cavity={featureId}:profile={corridor.ProfileId}.{corridor.LoopId}:distance={corridor.Distance:R}:center=({x:R},{y:R}):radius={radius:R}:interval=({Math.Max(from, corridor.From):R},{Math.Min(to, corridor.To):R})");
diff --git a/Aetheris.Kernel.Firmament/Materializer/ComposedProfileBoundaryChamferStackPlanner.cs b/Aetheris.Kernel.Firmament/Materializer/ComposedProfileBoundaryChamferStackPlanner.cs
index cc4b613a..7ed3cb3f 100644
--- a/Aetheris.Kernel.Firmament/Materializer/ComposedProfileBoundaryChamferStackPlanner.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/ComposedProfileBoundaryChamferStackPlanner.cs
@@ -4,9 +4,16 @@ namespace Aetheris.Kernel.Firmament.Materializer;
public static class ComposedProfileBoundaryChamferStackPlanner
{
private const double Tol = 1e-7;
+ internal static double? SupportLevel(PrismaticSectionStackConstruction stack, ResolvedProfile2D profile) =>
+ stack.Feature.Operations.Where(o => o.Intent != PrismaticProfileIntent.Remove && o.ProfileReference == profile.Name)
+ .Select(o => (double?)o.To).Max();
+
public static PrismaticSectionStackConstruction? TryApply(PrismaticSectionStackConstruction stack, ResolvedProfile2D profile, ProfileBoundaryChamferTarget target, double distance, out IReadOnlyList<string> diagnostics)
{
- var d = new List<string>(); var top = stack.Feature.CriticalLevels.Max(); var lower = top - distance;
+ if (SupportLevel(stack, profile) is not { } top) { diagnostics = ["ProfileBoundaryChamferComposeProfileSupportMissing"]; return null; }
+ var d = new List<string>(); var lower = top - distance;
+ if (stack.Feature.CountersinkHoles?.Any(h => h.ConeFrom > lower + Tol && h.ConeFrom < top - Tol) == true)
+ { diagnostics = ["ProfileBoundaryChamferCountersinkStationOverlapUnsupported:chamfer-corridor-crosses-shaft-to-cone-transition"]; return null; }
var topSlab = stack.Slabs.SingleOrDefault(x => x.From < lower + Tol && x.To >= top - Tol);
if (topSlab is null) { diagnostics = ["ProfileBoundaryChamferComposeStationUnavailable"]; return null; }
if (stack.Feature.CounterboreHoles?.Any(h => h.To - h.CounterboreDepth > lower + Tol && h.To - h.CounterboreDepth < top - Tol) == true) { diagnostics = ["ProfileBoundaryChamferCounterboreStationOverlapUnsupported"]; return null; }
@@ -25,9 +32,26 @@ public static class ComposedProfileBoundaryChamferStackPlanner
if (d.Count != 0) { diagnostics = d; return null; }
var slabs = stack.Slabs.Where(x => !ReferenceEquals(x, topSlab)).Append(new PrismaticSectionSlab(topSlab.From, lower, topSlab.Region, topSlab.ActiveOperations, topSlab.Arrangement)).OrderBy(x => x.From).ToArray();
var capRegion = new PrismaticSectionRegion(inset, topSlab.Region.Holes, topSlab.Region.Provenance.Concat([target.StableId]).ToArray());
- var transitions = stack.Transitions.Where(x => Math.Abs(x.Level - top) > Tol).Append(new PrismaticSectionTransition(top, [capRegion], [])).OrderBy(x => x.Level).ToArray();
+ // A boss elsewhere may continue above the named Profile's top. Keep its
+ // material and remove its footprint from this support's exposed cap.
+ var above = stack.Slabs.SingleOrDefault(s => Math.Abs(s.From - top) < Tol)?.MaterialRegions ?? [];
+ var protruding = ProfileArrangementBuilder.Difference(stack.Feature.Frame, above, [capRegion], "chamfer-continuing-material");
+ if (protruding.Arrangement.Diagnostics.Count > 0 || protruding.MaterialRegions.Count > 0)
+ { diagnostics = ["ProfileBoundaryChamferIntersectsContinuingMaterial:the-named-profile-corridor-cannot-cut-a-continuing-boss"]; return null; }
+ var cap = ProfileArrangementBuilder.Difference(stack.Feature.Frame, [capRegion], above, "chamfer-exposed-cap");
+ if (cap.Arrangement.Diagnostics.Count > 0) { diagnostics = cap.Arrangement.Diagnostics; return null; }
+ var transitions = stack.Transitions.Where(x => Math.Abs(x.Level - top) > Tol).Append(new PrismaticSectionTransition(top, cap.MaterialRegions, [])).OrderBy(x => x.Level).ToArray();
+ var middle = outer with { Loops = [outer.Loops[0] with { Segments = outer.Loops[0].Segments.Zip(inset.Loops[0].Segments).Select(pair =>
+ {
+ var a = (LineArcLineSegment2D)pair.First.Geometry; var b = (LineArcLineSegment2D)pair.Second.Geometry;
+ return pair.First with { Geometry = new LineArcLineSegment2D(((a.Start.X + b.Start.X) / 2, (a.Start.Y + b.Start.Y) / 2), ((a.End.X + b.End.X) / 2, (a.End.Y + b.End.Y) / 2)) };
+ }).ToArray() }] };
+ // Linear vertex transport gives a quadratic section area. Simpson's
+ // integral is exact here; disjoint cavity volumes are retained unchanged.
+ var lowerArea = Math.Abs(PrismaticSectionStackCompiler.ProfileArea(outer));
+ var removedVolume = distance * (lowerArea - (lowerArea + 4 * Math.Abs(PrismaticSectionStackCompiler.ProfileArea(middle)) + Math.Abs(PrismaticSectionStackCompiler.ProfileArea(inset))) / 6);
diagnostics = [];
- return stack with { Slabs = slabs, Transitions = transitions, VariableOuterIntervals = [interval] };
+ return stack with { Slabs = slabs, Transitions = transitions, VariableOuterIntervals = [interval], AnalyticVolume = stack.AnalyticVolume - removedVolume };
string FeatureFor(string profileName) => stack.Feature.Operations.FirstOrDefault(x => x.ProfileReference == profileName)?.SemanticFeatureId ?? $"profile:{profileName}";
}
diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs
index 448f5c1c..c5623f14 100644
--- a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs
@@ -53,6 +53,20 @@ public sealed record PrismaticCounterboreHoleFeature(
double CenterX, double CenterY, double Diameter, double CounterboreDiameter, double CounterboreDepth,
double From, double To, string SemanticRole, string SourceSpan,
string? SupportSpan = null, string? ParentSupport = null, double? SupportBoundaryMargin = null);
+/// <summary>Exact conical entry on a circular through cavity; stations are in the composition frame.</summary>
+public sealed record PrismaticCountersinkHoleFeature(
+ string Name, string StableId, string ShaftProfileReference,
+ double CenterX, double CenterY, double Diameter, double CountersinkDiameter, double AngleDegrees,
+ double From, double To, string SemanticRole, string SourceSpan,
+ string? SupportSpan = null, string? ParentSupport = null, double? SupportBoundaryMargin = null)
+{
+ public double SemiAngle => AngleDegrees * Math.PI / 360d;
+ public double ConeDepth => (CountersinkDiameter - Diameter) / (2d * Math.Tan(SemiAngle));
+ public double ConeFrom => To - ConeDepth;
+ public double RadiusAt(double station) => Diameter / 2d + Math.Clamp(station - ConeFrom, 0d, ConeDepth) * Math.Tan(SemiAngle);
+ public double AdditionalVoidVolume => Math.PI * ConeDepth *
+ (Math.Pow(CountersinkDiameter / 2d, 2) + CountersinkDiameter * Diameter / 4d - 2d * Math.Pow(Diameter / 2d, 2)) / 3d;
+}
/// <summary>Source-owned transverse blind drill; its cavity is planned after host construction.</summary>
public sealed record PrismaticConstructionPlaneBlindDrillFeature(
string Name, string StableId, string ConstructionPlaneId, string SourceConceptPlaneId,
@@ -148,7 +162,8 @@ public sealed record PrismaticProfileCompositionFeature(
IReadOnlyList<PrismaticCounterboreHoleFeature>? CounterboreHoles = null,
IReadOnlyList<PrismaticBossFeature>? Bosses = null,
IReadOnlyList<PrismaticPocketFeature>? Pockets = null,
- IReadOnlyList<PrismaticMaterialOffsetFeature>? MaterialOffsets = null)
+ IReadOnlyList<PrismaticMaterialOffsetFeature>? MaterialOffsets = null,
+ IReadOnlyList<PrismaticCountersinkHoleFeature>? CountersinkHoles = null)
{
public IEnumerable<(string Name, string StableId, string ProfileReference)> AllSlotProfiles =>
(CapsuleSlots ?? []).Select(x => (x.Name, x.StableId, x.ProfileReference))
@@ -594,17 +609,52 @@ public static class PrismaticProfileCompositionParser
}
var shaftHoles = new List<PrismaticShaftHoleFeature>();
var counterboreHoles = new List<PrismaticCounterboreHoleFeature>();
+ var countersinkHoles = new List<PrismaticCountersinkHoleFeature>();
var constructionPlaneBlindDrills = new List<PrismaticConstructionPlaneBlindDrillFeature>();
var capsuleSlots = new List<PrismaticCapsuleSlotFeature>();
var roundedRectangleSlots = new List<PrismaticRoundedRectangleSlotFeature>();
var materialFrom = operations.Count == 0 ? 0d : operations.Min(x => x.From);
var materialTo = operations.Count == 0 ? 0d : operations.Max(x => x.To);
+ var circularHostOperations = operations.ToArray();
+ PrismaticSectionStackConstruction? circularHost = null;
+ bool TryCircularHostInterval(string name, double x, double y, double entryRadius, string diagnostic, out double start, out double end)
+ {
+ start = end = 0d;
+ // Normalize once before drilling. The semantic top is local to the
+ // authored center, not the height of an unrelated boss elsewhere.
+ if (circularHost is null)
+ {
+ var levels = circularHostOperations.SelectMany(o => new[] { o.From, o.To }).Distinct().Order().ToArray();
+ var host = new PrismaticProfileCompositionFeature(compose.Name.Text, placement.ProfilePlane, placement.Axis, placement,
+ circularHostOperations, levels, "CircularCavityHost");
+ circularHost = PrismaticSectionStackCompiler.Normalize(new(host, profiles, []), out var hostDiagnostics);
+ diagnostics.AddRange(hostDiagnostics);
+ }
+ var intervals = circularHost?.Slabs.Where(s => s.MaterialRegions.Any(r =>
+ PrismaticSectionStackHoleTraversal.CheckDisk(r, (x, y), 0d, s.From, s.To).Classification == SectionStackFootprintClassification.InsideMaterial)).OrderBy(s => s.From).ToArray() ?? [];
+ if (intervals.Length == 0)
+ { diagnostics.Add($"{diagnostic}:{name}:center-has-no-material-support"); return false; }
+ if (intervals.Zip(intervals.Skip(1)).Any(p => Math.Abs(p.First.To - p.Second.From) > 1e-7d))
+ { diagnostics.Add($"{diagnostic}:{name}:disconnected-axial-material-spans-not-admitted"); return false; }
+ start = intervals[0].From; end = intervals[^1].To;
+ var entryLevel = end;
+ var exposed = circularHost!.Transitions.Where(t => Math.Abs(t.Level - entryLevel) < 1e-7d).SelectMany(t => t.UpwardRegions);
+ if (!exposed.Any(r => PrismaticSectionStackHoleTraversal.CheckDisk(r, (x, y), entryRadius, entryLevel, entryLevel).Classification == SectionStackFootprintClassification.InsideMaterial))
+ { diagnostics.Add($"{diagnostic}:{name}:entry-footprint-is-not-contained-in-the-exposed-local-support:radius={entryRadius:R}"); return false; }
+ return true;
+ }
foreach (var declaration in operationsSyntax.Document.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "Hole"))
{
var name = declaration.Name?.Text ?? "";
var fields = new FirmamentSyntaxFields(declaration, diagnostics);
var body = declaration.Body is null ? null : composeBody.Substring(declaration.Body.Span.Start + 1, declaration.Body.Span.Length - 2);
if (body is null) { diagnostics.Add($"compose-hole-unclosed:{name}"); continue; }
+ var variant = FirmamentSyntaxValues.Reference(declaration.Type.Arguments.FirstOrDefault()?.Value) ?? "";
+ var schemaVariant = Enum.TryParse<FirmamentV2SemanticHoleVariant>(variant, true, out var knownVariant) ? knownVariant.ToString() : variant;
+ foreach (var authored in fields.AuthoredFields)
+ if (FirmamentSemanticSchemas.Get("Hole")!.Fields.FirstOrDefault(f => FirmamentSyntaxFields.SameField(authored.Name, f.Name)) is { } schemaField
+ && !schemaField.AppliesTo(schemaVariant))
+ diagnostics.Add($"{FirmamentV2Parser.CanonicalFieldUnknown}:Hole:{authored.Name}");
fields.Take("PatternIdentity");
var patternIdentityMatch = Regex.Match(body, @"\bPatternIdentity\s*:\s*(?<id>[A-Za-z_]\w*\.[A-Za-z_]\w*)", RegexOptions.CultureInvariant);
var diagnosticName = patternIdentityMatch.Success ? patternIdentityMatch.Groups["id"].Value : name;
@@ -616,6 +666,8 @@ public static class PrismaticProfileCompositionParser
if (onExpression is not null && (!on.Success || on.Groups["face"].Value != onName))
diagnostics.Add($"compose-hole-support-invalid:{name}: Use a host face or an admitted Span<Plane>.");
var from = ReadFeatureField(fields, composeBody, HoleFrom, "From"); var depthEnd = ReadFeatureField(fields, composeBody, HoleDepthEnd, "End"); var termination = ReadFeatureField(fields, composeBody, HoleTermination, "Termination");
+ var countersinkDiameter = fields.Number("CountersinkDiameter", "mm");
+ var countersinkAngle = fields.Number("CountersinkAngle", "deg");
fields.Complete();
if (from.Success)
{
@@ -640,7 +692,45 @@ public static class PrismaticProfileCompositionParser
role.Success ? role.Groups["role"].Value : "BlindDrillPoint", $"offset:{declaration.Span.Start}", plane.Provenance));
continue;
}
- var variant = (FirmamentSyntaxValues.Reference(declaration.Type.Arguments.FirstOrDefault()?.Value) ?? "");
+ if (string.Equals(variant, "Countersink", StringComparison.OrdinalIgnoreCase))
+ {
+ if (!end.Success || !string.Equals(end.Groups["end"].Value, "ThroughAll", StringComparison.OrdinalIgnoreCase))
+ { diagnostics.Add($"ComposeCountersinkEndUnsupported:{name}:supported=ThroughAll"); continue; }
+ var supportName = on.Success ? on.Groups["face"].Value : null;
+ surfaceSpans.TryGetValue(supportName ?? string.Empty, out var supportSpan);
+ if (!on.Success || (!string.Equals(supportName, "+Z", StringComparison.OrdinalIgnoreCase) && supportSpan is null))
+ { diagnostics.Add($"ComposeCountersinkAxisUnsupported:{name}:supported=+Z-or-Span<Plane>"); continue; }
+ if (!center.Success || !diameter.Success)
+ { diagnostics.Add($"ComposeCountersinkMissingRequiredField:{name}"); continue; }
+ var cx = N(center, "x"); var cy = N(center, "y"); var shaftDiameter = N(diameter, "d");
+ if (!double.IsFinite(cx) || !double.IsFinite(cy) || !double.IsFinite(shaftDiameter) || shaftDiameter <= 0d
+ || !double.IsFinite(countersinkDiameter) || countersinkDiameter <= shaftDiameter
+ || !double.IsFinite(countersinkAngle) || countersinkAngle <= 0d || countersinkAngle >= 180d)
+ { diagnostics.Add($"ComposeCountersinkInvalidGeometry:{name}:require=positive-shaft-smaller-than-entry-and-angle-between-0-and-180deg"); continue; }
+ var stable = $"hole:{compose.Name.Text}.{name}"; var profile = $"{name}ShaftProfile";
+ var sinkSourceSpan = $"offset:{declaration.Span.Start}"; var sinkRole = role.Success ? role.Groups["role"].Value : "CountersinkHole";
+ if (!TryCircularHostInterval(name, cx, cy, countersinkDiameter / 2d, "ComposeCountersinkFootprintLeavesProfileMaterial", out var sinkFrom, out var sinkTo)) continue;
+ var hole = new PrismaticCountersinkHoleFeature(name, stable, profile, cx, cy, shaftDiameter, countersinkDiameter, countersinkAngle,
+ sinkFrom, sinkTo, sinkRole, sinkSourceSpan, supportSpan?.SpanId, supportSpan?.ParentId);
+ if (!double.IsFinite(hole.ConeDepth) || hole.ConeFrom <= sinkFrom + 1e-8d)
+ { diagnostics.Add($"ComposeCountersinkDepthExceedsHost:{name}:coneDepth={hole.ConeDepth:R}:hostDepth={sinkTo - sinkFrom:R}:require=positive-shaft-length"); continue; }
+ if (supportSpan is not null)
+ {
+ var normal = supportSpan.ParentPlane!.AxisZ.ToVector();
+ if (Math.Abs(normal.X) > 1e-8d || Math.Abs(normal.Y) > 1e-8d || normal.Z < 1d - 1e-8d
+ || Math.Abs(supportSpan.ParentPlane.Origin.Z - sinkTo) > 1e-7d)
+ { diagnostics.Add($"firmament-feature-support-parent-mismatch:{name}:{supportSpan.SpanId}"); continue; }
+ if (!PlanarSpanContainment.ContainsCircle(supportSpan, cx, cy, countersinkDiameter / 2d, out var margin))
+ { diagnostics.Add($"firmament-feature-footprint-outside-span:{diagnosticName}:{supportSpan.SpanId}:radius={countersinkDiameter / 2d:R}:margin={margin:R}"); continue; }
+ hole = hole with { SupportBoundaryMargin = margin };
+ }
+ if (!names.Add(name)) { diagnostics.Add($"compose-duplicate-operation:{name}"); continue; }
+ if (profiles.ContainsKey(profile)) { diagnostics.Add($"compose-hole-profile-name-collision:{name}"); continue; }
+ profiles.Add(profile, CircleProfile(profile, cx, cy, shaftDiameter / 2d, stable, sinkSourceSpan));
+ countersinkHoles.Add(hole);
+ operations.Add(new(name, PrismaticProfileIntent.Remove, profile, sinkFrom, sinkTo, sinkRole, sinkSourceSpan, stable, "Hole<Countersink>", shaftDiameter));
+ continue;
+ }
if (string.Equals(variant, "Counterbore", StringComparison.OrdinalIgnoreCase))
{
if (!end.Success || !string.Equals(end.Groups["end"].Value, "ThroughAll", StringComparison.OrdinalIgnoreCase))
@@ -654,19 +744,19 @@ public static class PrismaticProfileCompositionParser
var counterboreX = N(center, "x"); var counterboreY = N(center, "y"); var shaftDiameter = N(diameter, "d"); var boreDiameter = N(counterboreDiameter, "d"); var boreDepth = N(counterboreDepth, "d");
if (!double.IsFinite(counterboreX) || !double.IsFinite(counterboreY) || !double.IsFinite(shaftDiameter) || shaftDiameter <= 0d || !double.IsFinite(boreDiameter) || boreDiameter <= shaftDiameter || !double.IsFinite(boreDepth) || boreDepth <= 0d)
{ diagnostics.Add($"ComposeCounterboreInvalidGeometry:{name}"); continue; }
- var hostDepth = materialTo - materialFrom;
- if (boreDepth > hostDepth + 1e-8d)
- { diagnostics.Add($"ComposeCounterboreDepthExceedsHost:{name}:depth={boreDepth:R}:hostDepth={hostDepth:R}"); continue; }
+ var hasLocalSupport = TryCircularHostInterval(name, counterboreX, counterboreY, boreDiameter / 2d, "ComposeCounterboreFootprintLeavesProfileMaterial", out var boreFrom, out var boreTo);
+ var hostDepth = hasLocalSupport ? boreTo - boreFrom : materialTo - materialFrom;
+ if (boreDepth >= hostDepth - 1e-8d)
+ { diagnostics.Add($"ComposeCounterboreDepthExceedsHost:{name}:depth={boreDepth:R}:hostDepth={hostDepth:R}:require=positive-shaft-length; use Hole<Shaft> for a full-depth larger bore"); continue; }
+ if (!hasLocalSupport) continue;
if (!names.Add(name)) { diagnostics.Add($"compose-duplicate-operation:{name}"); continue; }
var counterboreStableId = $"hole:{compose.Name.Text}.{name}";
- if (!CircleContainedInBaseProfile(operations, profiles, counterboreX, counterboreY, boreDiameter / 2d))
- { diagnostics.Add($"ComposeCounterboreFootprintLeavesProfileMaterial:{name}:radius={boreDiameter / 2d:R}"); continue; }
double? supportMargin = null;
if (supportSpan is not null)
{
var parentNormal = supportSpan.ParentPlane!.AxisZ.ToVector();
if (Math.Abs(parentNormal.X) > 1e-8d || Math.Abs(parentNormal.Y) > 1e-8d || parentNormal.Z < 1d - 1e-8d
- || Math.Abs(supportSpan.ParentPlane.Origin.Z - materialTo) > 1e-7d)
+ || Math.Abs(supportSpan.ParentPlane.Origin.Z - boreTo) > 1e-7d)
{ diagnostics.Add($"firmament-feature-support-parent-mismatch:{name}:{supportSpan.SpanId}"); continue; }
if (!PlanarSpanContainment.ContainsCircle(supportSpan, counterboreX, counterboreY, boreDiameter / 2d, out var margin))
{ diagnostics.Add($"firmament-feature-footprint-outside-span:{diagnosticName}:{supportSpan.SpanId}:center=[{counterboreX:R},{counterboreY:R}]:radius={boreDiameter / 2d:R}:margin={margin:R}"); continue; }
@@ -679,9 +769,9 @@ public static class PrismaticProfileCompositionParser
profiles.Add(shaftProfile, CircleProfile(shaftProfile, counterboreX, counterboreY, shaftDiameter / 2d, counterboreStableId, $"offset:{declaration.Span.Start}"));
profiles.Add(boreProfile, CircleProfile(boreProfile, counterboreX, counterboreY, boreDiameter / 2d, counterboreStableId, $"offset:{declaration.Span.Start}"));
var counterboreSourceSpan = $"offset:{declaration.Span.Start}"; var counterboreSemanticRole = role.Success ? role.Groups["role"].Value : "CounterboreHole";
- counterboreHoles.Add(new(name, counterboreStableId, shaftProfile, boreProfile, counterboreX, counterboreY, shaftDiameter, boreDiameter, boreDepth, materialFrom, materialTo, counterboreSemanticRole, counterboreSourceSpan, supportSpan?.SpanId, supportSpan?.ParentId, supportMargin));
- operations.Add(new($"{name}Shaft", PrismaticProfileIntent.Remove, shaftProfile, materialFrom, materialTo, counterboreSemanticRole, counterboreSourceSpan, counterboreStableId, "Hole<Counterbore>", shaftDiameter));
- operations.Add(new($"{name}Counterbore", PrismaticProfileIntent.Remove, boreProfile, materialTo - boreDepth, materialTo, counterboreSemanticRole, counterboreSourceSpan, counterboreStableId, "Hole<Counterbore>", boreDiameter));
+ counterboreHoles.Add(new(name, counterboreStableId, shaftProfile, boreProfile, counterboreX, counterboreY, shaftDiameter, boreDiameter, boreDepth, boreFrom, boreTo, counterboreSemanticRole, counterboreSourceSpan, supportSpan?.SpanId, supportSpan?.ParentId, supportMargin));
+ operations.Add(new($"{name}Shaft", PrismaticProfileIntent.Remove, shaftProfile, boreFrom, boreTo, counterboreSemanticRole, counterboreSourceSpan, counterboreStableId, "Hole<Counterbore>", shaftDiameter));
+ operations.Add(new($"{name}Counterbore", PrismaticProfileIntent.Remove, boreProfile, boreTo - boreDepth, boreTo, counterboreSemanticRole, counterboreSourceSpan, counterboreStableId, "Hole<Counterbore>", boreDiameter));
continue;
}
if (!string.Equals(variant, "Shaft", StringComparison.OrdinalIgnoreCase)
@@ -725,6 +815,12 @@ public static class PrismaticProfileCompositionParser
foreach (var counterbore in counterboreHoles)
if (CirclesTouchOrOverlap(shaft.CenterX, shaft.CenterY, shaft.Diameter / 2d, counterbore.CenterX, counterbore.CenterY, counterbore.CounterboreDiameter / 2d))
diagnostics.Add($"ComposeCounterboreIntersectsExistingCavity:{counterbore.Name}:shaft={shaft.Name}");
+ foreach (var hole in countersinkHoles)
+ {
+ if (IntersectsExistingCircularCavity(shaftHoles, counterboreHoles, hole.CenterX, hole.CenterY, hole.CountersinkDiameter / 2d)
+ || countersinkHoles.Any(other => other != hole && CirclesTouchOrOverlap(hole.CenterX, hole.CenterY, hole.CountersinkDiameter / 2d, other.CenterX, other.CenterY, other.CountersinkDiameter / 2d)))
+ diagnostics.Add($"ComposeCountersinkIntersectsExistingCavity:{hole.Name}:require=disjoint-entry-footprints");
+ }
foreach (var declaration in operationsSyntax.Document.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "Slot"))
{
var name = declaration.Name?.Text ?? "";
@@ -769,8 +865,8 @@ public static class PrismaticProfileCompositionParser
if (!SameFrame(operandFrame, compositionFrame!))
diagnostics.Add($"compose-profile-frame-mismatch:{operation.Name}:{operation.ProfileReference}: All operands must use the same construction frame; an explicit Placement cannot override an oriented Profile.");
}
- var levels = operations.SelectMany(o => new[] { o.From, o.To }).Distinct().Order().ToArray();
- var feature = diagnostics.Count == 0 ? new PrismaticProfileCompositionFeature(compose.Name.Text, placement.ProfilePlane, placement.Axis, placement, operations, levels, "parser-backed-scaffold-profile-composition", shaftHoles, capsuleSlots, roundedRectangleSlots, constructionPlaneBlindDrills, counterboreHoles, bosses, pockets, materialOffsets) : null;
+ var levels = operations.SelectMany(o => new[] { o.From, o.To }).Concat(countersinkHoles.Select(h => h.ConeFrom)).Distinct().Order().ToArray();
+ var feature = diagnostics.Count == 0 ? new PrismaticProfileCompositionFeature(compose.Name.Text, placement.ProfilePlane, placement.Axis, placement, operations, levels, "parser-backed-scaffold-profile-composition", shaftHoles, capsuleSlots, roundedRectangleSlots, constructionPlaneBlindDrills, counterboreHoles, bosses, pockets, materialOffsets, countersinkHoles) : null;
return new(feature, profiles, diagnostics.Distinct().ToArray(), expansion.Evidence);
}
@@ -1056,12 +1152,6 @@ public static class PrismaticProfileCompositionParser
new($"profile:{profileName}.Outer.{names[i]}", $"{holeStableId}.axis", sourceSpan, $"Hole<Shaft>({holeStableId})", "XY"))).ToArray();
return new(profileName, "XY", [new ResolvedProfileLoop2D("Outer", true, segments)]);
}
- private static bool CircleContainedInBaseProfile(IReadOnlyList<PrismaticProfileOperation> operations, IReadOnlyDictionary<string, ResolvedProfile2D> profiles, double x, double y, double radius)
- {
- var baseOperation = operations.SingleOrDefault(operation => operation.Intent == PrismaticProfileIntent.Base);
- if (baseOperation is null || !profiles.TryGetValue(baseOperation.ProfileReference, out var profile) || ProfileArrangementBuilder.PointInProfile(profile, (x, y)) != ArrangementPointLocation.Inside) return false;
- return profile.Loops.Single().Segments.All(segment => DistanceToCurve((x, y), segment.Geometry) > radius + 1e-8d);
- }
private static bool IntersectsExistingCircularCavity(IReadOnlyList<PrismaticShaftHoleFeature> shafts, IReadOnlyList<PrismaticCounterboreHoleFeature> counterbores, double x, double y, double radius) =>
shafts.Any(hole => CirclesTouchOrOverlap(x, y, radius, hole.CenterX, hole.CenterY, hole.Diameter / 2d)) ||
counterbores.Any(hole => CirclesTouchOrOverlap(x, y, radius, hole.CenterX, hole.CenterY, hole.CounterboreDiameter / 2d));
diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs
index 023c19de..858a069d 100644
--- a/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs
@@ -86,6 +86,30 @@ public static class PrismaticSectionStackCompiler
{
var d = parsed.Diagnostics.ToList();
if (parsed.Feature is null) { diagnostics = d; return null; }
+ // A variable cavity is legal only where its complete footprint lies in
+ // actual material. A Base-profile check alone misses pockets, slots,
+ // local height changes and disconnected material spans.
+ foreach (var hole in parsed.Feature.CountersinkHoles ?? [])
+ CheckCavity(hole.StableId, hole.Name, hole.CenterX, hole.CenterY, hole.From, hole.To, hole.RadiusAt, "ComposeCountersinkFootprintLeavesProfileMaterial");
+ foreach (var hole in parsed.Feature.CounterboreHoles ?? [])
+ CheckCavity(hole.StableId, hole.Name, hole.CenterX, hole.CenterY, hole.From, hole.To,
+ z => z > hole.To - hole.CounterboreDepth + Tol ? hole.CounterboreDiameter / 2d : hole.Diameter / 2d,
+ "ComposeCounterboreFootprintLeavesProfileMaterial");
+ if (d.Count != 0) { diagnostics = d.Distinct().ToArray(); return null; }
+
+ void CheckCavity(string stableId, string name, double x, double y, double from, double to, Func<double, double> radiusAt, string code)
+ {
+ foreach (var pair in parsed.Feature.CriticalLevels.Zip(parsed.Feature.CriticalLevels.Skip(1)).Where(p => p.First >= from - Tol && p.Second <= to + Tol))
+ {
+ var mid = (pair.First + pair.Second) / 2d;
+ var active = parsed.Feature.Operations.Where(o => o.From < mid && mid < o.To && o.SemanticFeatureId != stableId).ToArray();
+ var host = ProfileArrangementBuilder.Compose(parsed.Feature.Frame, active, parsed.Profiles, $"cavity-host:{stableId}:{pair.First:R}..{pair.Second:R}");
+ d.AddRange(host.Arrangement.Diagnostics);
+ var radius = radiusAt(pair.Second);
+ if (!host.MaterialRegions.Any(region => PrismaticSectionStackHoleTraversal.CheckDisk(region, (x, y), radius, pair.First, pair.Second).Classification == SectionStackFootprintClassification.InsideMaterial))
+ d.Add($"{code}:{name}:interval={pair.First:R}..{pair.Second:R}:radius={radius:R}:require=complete-contiguous-material");
+ }
+ }
var slabs = new List<PrismaticSectionSlab>();
foreach (var pair in parsed.Feature.CriticalLevels.Zip(parsed.Feature.CriticalLevels.Skip(1)))
{
@@ -112,7 +136,8 @@ public static class PrismaticSectionStackCompiler
var downward = downwardResult.MaterialRegions;
if (upward.Count > 0 || downward.Count > 0) transitions.Add(new(level, upward, downward));
}
- var volume = slabs.Sum(s => s.MaterialRegions.Sum(Area) * (s.To - s.From));
+ var volume = slabs.Sum(s => s.MaterialRegions.Sum(Area) * (s.To - s.From))
+ - (parsed.Feature.CountersinkHoles ?? []).Sum(h => h.AdditionalVoidVolume);
diagnostics = d.Distinct().ToArray();
return d.Any(x => x.Contains("rejected", StringComparison.Ordinal))
? null
@@ -169,6 +194,16 @@ public static class PrismaticSectionStackEmitter
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, bool SameSense, string Source, string Construction, double From, double To)>(); var capFaces = new List<(FaceId Face, double Z, bool Up)>();
+ var countersinks = stack.Feature.CountersinkHoles ?? [];
+ PrismaticCountersinkHoleFeature? CountersinkFor(string source) => countersinks.SingleOrDefault(h =>
+ SourceId(source).StartsWith($"profile:{h.ShaftProfileReference}.Outer.", StringComparison.Ordinal));
+ LineArcProfileCurve2D AtStation(LineArcProfileCurve2D curve, double z, string source) =>
+ curve is LineArcCircularArc2D arc && CountersinkFor(source) is { } hole ? arc with { Radius = hole.RadiusAt(z) } : curve;
+ SurfaceGeometry WallSurface(LineArcProfileCurve2D curve, double from, double to, bool isHole, string source) =>
+ CountersinkFor(source) is { } hole && to > hole.ConeFrom + Tol
+ ? SurfaceGeometry.FromCone(new ConeSurface(new Point3D(hole.CenterX, hole.CenterY, hole.ConeFrom),
+ Direction3D.Create(new Vector3D(0, 0, 1)), hole.Diameter / 2d, hole.SemiAngle, Direction3D.Create(new Vector3D(1, 0, 0))))
+ : SideSurface(curve, from, isHole);
var variableIntervals = stack.VariableOuterIntervals ?? [];
foreach (var interval in variableIntervals)
d.AddRange(VariableOuterSectionIntervalValidator.Validate(interval).Diagnostics);
@@ -205,10 +240,13 @@ public static class PrismaticSectionStackEmitter
foreach (var segment in item.Profile.Loops[0].Segments)
foreach (var curve in Split(segment.Geometry, splitPoints))
{
- var endpoints = Ends(curve); var a = endpoints[0]; var b = endpoints[1]; var bottom = Edge(curve, slab.From); var top = Edge(curve, slab.To); var v0 = Vertical(a, slab.From, slab.To); var v1 = Vertical(b, slab.From, slab.To);
- var loop = AddLoop(builder, [new(bottom.Edge, bottom.Reverse), new(v1.Edge, v1.Reverse), new(top.Edge, !top.Reverse), new(v0.Edge, !v0.Reverse)]);
var source = SourceId(segment.Provenance.StableId);
- sideFaces.Add((loop, SideSurface(curve, slab.From, item.IsHole), !(item.IsHole && curve is LineArcCircularArc2D), source, $"slab:{slab.From:R}..{slab.To:R}:{segment.Provenance.Derivation}", slab.From, slab.To));
+ var lower = AtStation(curve, slab.From, source); var upper = AtStation(curve, slab.To, source);
+ var a = Ends(lower); var b = Ends(upper); var bottom = Edge(lower, slab.From); var top = Edge(upper, slab.To);
+ var v0 = CountersinkFor(source) is null ? Vertical(a[0], slab.From, slab.To) : Transition(a[0], b[0], slab.From, slab.To);
+ var v1 = CountersinkFor(source) is null ? Vertical(a[1], slab.From, slab.To) : Transition(a[1], b[1], 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, WallSurface(curve, slab.From, slab.To, item.IsHole, source), !(item.IsHole && curve is LineArcCircularArc2D), source, $"slab:{slab.From:R}..{slab.To:R}:{segment.Provenance.Derivation}", slab.From, slab.To));
}
foreach (var interval in variableIntervals)
{
@@ -225,15 +263,20 @@ public static class PrismaticSectionStackEmitter
foreach (var segment in inner.LowerLoop.Loops[0].Segments)
foreach (var curve in Split(segment.Geometry, splitPoints))
{
- var ends = Ends(curve); var bottom = Edge(curve, interval.LowerStation); var top = Edge(curve, interval.UpperStation); var v0 = Vertical(ends[0], interval.LowerStation, interval.UpperStation); var v1 = Vertical(ends[1], interval.LowerStation, interval.UpperStation);
+ var source = SourceId(segment.Provenance.StableId);
+ var lowerCurve = AtStation(curve, interval.LowerStation, source); var upperCurve = AtStation(curve, interval.UpperStation, source);
+ var lowerEnds = Ends(lowerCurve); var upperEnds = Ends(upperCurve);
+ var bottom = Edge(lowerCurve, interval.LowerStation); var top = Edge(upperCurve, interval.UpperStation);
+ var v0 = CountersinkFor(source) is null ? Vertical(lowerEnds[0], interval.LowerStation, interval.UpperStation) : Transition(lowerEnds[0], upperEnds[0], interval.LowerStation, interval.UpperStation);
+ var v1 = CountersinkFor(source) is null ? Vertical(lowerEnds[1], interval.LowerStation, interval.UpperStation) : Transition(lowerEnds[1], upperEnds[1], interval.LowerStation, interval.UpperStation);
var loop = AddLoop(builder, [new(bottom.Edge, !bottom.Reverse), new(v0.Edge, v0.Reverse), new(top.Edge, top.Reverse), new(v1.Edge, !v1.Reverse)]);
- sideFaces.Add((loop, SideSurface(curve, interval.LowerStation, true), false, inner.FeatureId, $"variable:{interval.StableId}:inner:{inner.FeatureId}", interval.LowerStation, interval.UpperStation));
+ sideFaces.Add((loop, WallSurface(curve, interval.LowerStation, interval.UpperStation, true, source), false, source, $"variable:{interval.StableId}:inner:{inner.FeatureId}", interval.LowerStation, interval.UpperStation));
}
}
foreach (var transition in stack.Transitions)
{
- foreach (var region in transition.UpwardRegions) capFaces.Add((AddCap(builder, region, transition.Level, Edge, splitPoints), transition.Level, true));
- foreach (var region in transition.DownwardRegions) capFaces.Add((AddCap(builder, region, transition.Level, Edge, splitPoints), transition.Level, false));
+ foreach (var region in transition.UpwardRegions) capFaces.Add((AddCap(builder, region, transition.Level, Edge, splitPoints, AtStation), transition.Level, true));
+ foreach (var region in transition.DownwardRegions) capFaces.Add((AddCap(builder, region, transition.Level, Edge, splitPoints, AtStation), transition.Level, false));
}
var faces = new List<FaceId>();
foreach (var cap in capFaces) faces.Add(cap.Face);
@@ -317,7 +360,8 @@ public static class PrismaticSectionStackEmitter
.Where(item => item.Side.Source.StartsWith(prefix, StringComparison.Ordinal)))
descendants.Add(new($"material:{feature.StableId}:wall:{item.Face.Value}", "Face", SemanticTopologyRole.ExtrusionSideFace, feature.StableId, Face: item.Face, ParentStableId: feature.StableId, GeometryPreview: feature.Kind));
}
- foreach (var hole in stack.Feature.ShaftHoles ?? [])
+ foreach (var hole in (stack.Feature.ShaftHoles ?? []).Concat(countersinks.Select(h => new PrismaticShaftHoleFeature(
+ h.Name, h.StableId, h.ShaftProfileReference, h.CenterX, h.CenterY, h.Diameter, h.From, h.To, h.SemanticRole, h.SourceSpan))))
{
var profilePrefix = $"profile:{hole.ProfileReference}.Outer.";
// ThroughAll is declared over the composition interval, but a removal can only exist where
@@ -326,6 +370,7 @@ public static class PrismaticSectionStackEmitter
// composition continues to Z=50 elsewhere).
var holeSides = sideFaces.Select((side, index) => (Side: side, Face: faces[capFaces.Count + index]))
.Where(x => x.Side.Source.StartsWith(profilePrefix, StringComparison.Ordinal)).ToArray();
+ if (holeSides.Length == 0) return new(null, d.Append($"ComposeHoleSemanticSourceMissing:{hole.Name}:requested-shaft-has-no-materialized-wall").ToArray());
var horizontalEdges = holeSides.SelectMany(x => builder.Model.Loops.Single(loop => loop.Id == x.Side.Loop).CoedgeIds)
.Select(id => builder.Model.Coedges.Single(coedge => coedge.Id == id).EdgeId).Distinct()
.Select(id => (Edge: id, Topology: builder.Model.Edges.Single(edge => edge.Id == id)))
@@ -335,10 +380,14 @@ public static class PrismaticSectionStackEmitter
var exitZ = horizontalEdges.Min(x => x.Z);
var entryEdges = horizontalEdges.Where(x => Math.Abs(x.Z - entryZ) <= Tol).Select(x => x.Edge).Distinct().OrderBy(x => x.Value).ToArray();
var exitEdges = horizontalEdges.Where(x => Math.Abs(x.Z - exitZ) <= Tol).Select(x => x.Edge).Distinct().OrderBy(x => x.Value).ToArray();
- var wallFaces = holeSides.Select(x => x.Face).Distinct().OrderBy(x => x.Value).ToArray();
foreach (var edge in entryEdges) descendants.Add(new($"material:{hole.StableId}:entry-edge:{edge.Value}", "Edge", SemanticTopologyRole.TopBoundary, hole.StableId, Edge: edge, ParentStableId: hole.StableId, GeometryPreview: $"diameter={hole.Diameter:R}"));
foreach (var edge in exitEdges) descendants.Add(new($"material:{hole.StableId}:exit-edge:{edge.Value}", "Edge", SemanticTopologyRole.BottomBoundary, hole.StableId, Edge: edge, ParentStableId: hole.StableId, GeometryPreview: $"diameter={hole.Diameter:R}"));
- foreach (var face in wallFaces) descendants.Add(new($"material:{hole.StableId}:wall:{face.Value}", "Face", SemanticTopologyRole.HoleWallFace, hole.StableId, Face: face, ParentStableId: hole.StableId, GeometryPreview: $"diameter={hole.Diameter:R}"));
+ foreach (var side in holeSides)
+ {
+ var cone = side.Side.Surface.Kind == SurfaceGeometryKind.Cone;
+ descendants.Add(new($"material:{hole.StableId}:wall:{side.Face.Value}", "Face", cone ? SemanticTopologyRole.HoleCountersinkWallFace : SemanticTopologyRole.HoleWallFace,
+ hole.StableId, Face: side.Face, ParentStableId: hole.StableId, GeometryPreview: cone ? "conical-entry" : $"diameter={hole.Diameter:R}"));
+ }
LoopId? LoopFor(IReadOnlyList<EdgeId> boundary)
{
var expected = boundary.ToHashSet();
@@ -356,7 +405,8 @@ public static class PrismaticSectionStackEmitter
.Where(item => item.Side.Source.StartsWith(borePrefix, StringComparison.Ordinal)).ToArray();
var shaftSides = sideFaces.Select((side, index) => (Side: side, Face: faces[capFaces.Count + index]))
.Where(item => item.Side.Source.StartsWith(shaftPrefix, StringComparison.Ordinal)).ToArray();
- if (boreSides.Length == 0 || shaftSides.Length == 0) { d.Add($"ComposeCounterboreSemanticSourceMissing:{hole.Name}"); continue; }
+ if (boreSides.Length == 0 || shaftSides.Length == 0)
+ return new(null, d.Append($"ComposeCounterboreSemanticSourceMissing:{hole.Name}:both-recess-and-shaft-walls-are-required").ToArray());
var boreEdges = boreSides.SelectMany(item => builder.Model.Loops.Single(loop => loop.Id == item.Side.Loop).CoedgeIds)
.Select(id => builder.Model.Coedges.Single(coedge => coedge.Id == id).EdgeId).Distinct()
.Select(id => (Edge: id, Topology: builder.Model.Edges.Single(edge => edge.Id == id)))
@@ -384,7 +434,7 @@ public static class PrismaticSectionStackEmitter
var prefix = $"profile:{slot.ProfileReference}.Outer.";
var slotSides = sideFaces.Select((side, index) => (Side: side, Face: faces[capFaces.Count + index]))
.Where(x => x.Side.Source.StartsWith(prefix, StringComparison.Ordinal)).ToArray();
- if (slotSides.Length == 0) { d.Add($"SlotCorrespondenceMissing:{slot.Name}"); continue; }
+ if (slotSides.Length == 0) return new(null, d.Append($"SlotCorrespondenceMissing:{slot.Name}:requested-slot-has-no-materialized-wall").ToArray());
var horizontalEdges = slotSides.SelectMany(x => builder.Model.Loops.Single(loop => loop.Id == x.Side.Loop).CoedgeIds)
.Select(id => builder.Model.Coedges.Single(coedge => coedge.Id == id).EdgeId).Distinct()
.Select(id => (Edge: id, Topology: builder.Model.Edges.Single(edge => edge.Id == id)))
@@ -408,6 +458,7 @@ public static class PrismaticSectionStackEmitter
var provenance = new List<string> { "ProfileArrangement2D", "PrismaticSectionStackConstruction", "PrismaticSectionStackBrepPlan", "AuthoritativeBRepPlan" };
if ((stack.Feature.ShaftHoles?.Count ?? 0) > 0) provenance.Insert(0, "SemanticHoleComposeLowering");
if ((stack.Feature.CounterboreHoles?.Count ?? 0) > 0) provenance.Insert(0, "SemanticCounterboreComposeLowering");
+ if (countersinks.Count > 0) provenance.Insert(0, "SemanticCountersinkComposeLowering");
if (stack.Feature.AllSlotProfiles.Any()) provenance.Insert(0, "SemanticSlotComposeLowering");
var correspondence = new SemanticTopologyCorrespondence(stack.Feature.Name, descendants.DistinctBy(x => x.StableId).ToArray(), provenance);
var faceMappings = new List<PrismaticSectionStackFacePlanMapping>();
@@ -427,13 +478,14 @@ public static class PrismaticSectionStackEmitter
d.Add("compose-plan-first-materialization-boundary");
return new(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)
+ private static FaceId AddCap(TopologyBuilder builder, PrismaticSectionRegion region, double z, Func<LineArcProfileCurve2D, double, (EdgeId Edge, bool Reverse)> edge, IReadOnlyList<(double X, double Y)> splitPoints,
+ Func<LineArcProfileCurve2D, double, string, LineArcProfileCurve2D> atStation)
{
var loops = new List<LoopId>();
foreach (var item in Loops(region))
{
var segments = item.IsHole ? item.Profile.Loops[0].Segments.Reverse() : item.Profile.Loops[0].Segments;
- var curves = segments.SelectMany(s => Split(s.Geometry, splitPoints)).ToArray();
+ var curves = segments.SelectMany(s => Split(s.Geometry, splitPoints).Select(curve => atStation(curve, z, s.Provenance.StableId))).ToArray();
loops.Add(AddLoop(builder, curves.Select(curve => { var e = edge(curve, z); return new Use(e.Edge, item.IsHole ? !e.Reverse : e.Reverse); }).ToArray()));
}
return builder.AddFace(loops);
@@ -493,6 +545,7 @@ public static class PrismaticSectionStackEmitter
{
SurfaceGeometryKind.Plane => SurfaceGeometry.FromPlane(new PlaneSurface(frame.ToWorld((surface.Plane!.Value.Origin.X, surface.Plane.Value.Origin.Y), surface.Plane.Value.Origin.Z), Direction3D.Create(frame.ToWorldDirection(surface.Plane.Value.Normal.ToVector())), Direction3D.Create(frame.ToWorldDirection(surface.Plane.Value.UAxis.ToVector())))),
SurfaceGeometryKind.Cylinder => SurfaceGeometry.FromCylinder(new CylinderSurface(frame.ToWorld((surface.Cylinder!.Value.Origin.X, surface.Cylinder.Value.Origin.Y), surface.Cylinder.Value.Origin.Z), Direction3D.Create(frame.ToWorldDirection(surface.Cylinder.Value.Axis.ToVector())), surface.Cylinder.Value.Radius, Direction3D.Create(frame.ToWorldDirection(surface.Cylinder.Value.XAxis.ToVector())))),
+ SurfaceGeometryKind.Cone => SurfaceGeometry.FromCone(new ConeSurface(frame.ToWorld((surface.Cone!.Value.PlacementOrigin.X, surface.Cone.Value.PlacementOrigin.Y), surface.Cone.Value.PlacementOrigin.Z), Direction3D.Create(frame.ToWorldDirection(surface.Cone.Value.Axis.ToVector())), surface.Cone.Value.PlacementRadius, surface.Cone.Value.SemiAngleRadians, Direction3D.Create(frame.ToWorldDirection(surface.Cone.Value.ReferenceAxis.ToVector())))),
SurfaceGeometryKind.LinearExtrusion => SurfaceGeometry.FromLinearExtrusion(new LinearExtrusionSurface(Transform(surface.LinearExtrusion!.Value.Directrix, frame),frame.ToWorldDirection(surface.LinearExtrusion.Value.ExtrusionVector))),
_ => throw new NotSupportedException($"Section-stack frame transform does not support surface {surface.Kind}.")
};
diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackHoleTraversal.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackHoleTraversal.cs
index 5b85b1f6..3bd2010f 100644
--- a/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackHoleTraversal.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackHoleTraversal.cs
@@ -158,12 +158,15 @@ internal static class PrismaticSectionStackHoleTraversal
return result;
}
- private static SectionStackHoleFootprintCheck CheckDisk(PrismaticSectionRegion region, (double X, double Y) center, double radius, double start, double end)
+ internal static SectionStackHoleFootprintCheck CheckDisk(PrismaticSectionRegion region, (double X, double Y) center, double radius, double start, double end)
{
var outerLocation = ProfileArrangementBuilder.PointInProfile(region.Outer, center);
var outer = BoundaryDistance(region.Outer, center);
var holes = region.Holes.Select(h => (Location: ProfileArrangementBuilder.PointInProfile(h, center), Distance: BoundaryDistance(h, center), Profile: h)).ToArray();
var provenance = region.Provenance;
+ if (!double.IsFinite(outer) || holes.Any(h => !double.IsFinite(h.Distance)))
+ return new(start, end, center.X, center.Y, radius, SectionStackFootprintClassification.Ambiguous, double.NaN,
+ provenance.Append("ExactDiskBoundaryUnsupported:requires-line-or-circular-arc").ToArray());
if (outerLocation != ArrangementPointLocation.Inside)
return new(start, end, center.X, center.Y, radius, SectionStackFootprintClassification.OutsideMaterial, outer, provenance);
if (holes.Any(x => x.Location is ArrangementPointLocation.Inside or ArrangementPointLocation.OnBoundary))
diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileBoundaryChamfer.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileBoundaryChamfer.cs
index 93a02a02..afcaa327 100644
--- a/Aetheris.Kernel.Firmament/Materializer/ProfileBoundaryChamfer.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileBoundaryChamfer.cs
@@ -1154,6 +1154,11 @@ public static class ProfileStraightEdgeFilletAdmissionChecker
AddIfCollision(hole.StableId, "Counterbore", hole.CenterX, hole.CenterY, hole.CounterboreDiameter / 2d, Math.Max(hole.From, hole.To - hole.CounterboreDepth), hole.To, "ProfileBoundaryFilletIntersectsCounterbore");
AddIfCollision(hole.StableId, "CounterboreShaft", hole.CenterX, hole.CenterY, hole.Diameter / 2d, hole.From, Math.Max(hole.From, hole.To - hole.CounterboreDepth), "ProfileBoundaryFilletIntersectsCounterbore");
}
+ foreach (var hole in stack.Feature.CountersinkHoles ?? [])
+ {
+ AddIfCollision(hole.StableId, "Countersink", hole.CenterX, hole.CenterY, hole.CountersinkDiameter / 2d, hole.ConeFrom, hole.To, "ProfileBoundaryFilletIntersectsCountersink");
+ AddIfCollision(hole.StableId, "CountersinkShaft", hole.CenterX, hole.CenterY, hole.Diameter / 2d, hole.From, hole.ConeFrom, "ProfileBoundaryFilletIntersectsCountersink");
+ }
return new(diagnostics.Count == 0, corridor, diagnostics.Distinct(StringComparer.Ordinal).ToArray());
void AddIfCollision(string feature, string kind, double x, double y, double cavityRadius, double cavityFrom, double cavityTo, string code)
diff --git a/Aetheris.Kernel.Firmament/Materializer/SemanticTopologySelections.cs b/Aetheris.Kernel.Firmament/Materializer/SemanticTopologySelections.cs
index f7567a8c..cb0c0448 100644
--- a/Aetheris.Kernel.Firmament/Materializer/SemanticTopologySelections.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/SemanticTopologySelections.cs
@@ -7,7 +7,7 @@ using Aetheris.Semantics;
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, LocalStartBoundary, LocalEndBoundary, LocalStartCapLoop, LocalEndCapLoop, TopBoundary, BottomBoundary, ExtrusionSideFace, TopFaceBoundaryLoop, BottomFaceBoundaryLoop, HoleEntryLoop, HoleExitLoop, HoleWallFace, HoleShaftToDrillPointLoop, HoleShaftToDrillPointEdge, HoleDrillPointFace, HoleTipVertex, HoleCounterboreMouthLoop, HoleCounterboreWallFace, HoleCounterboreShoulderLoop, HoleCounterboreShaftWallFace, SlotEntryLoop, SlotExitLoop, SlotWallFace, SlotStraightWallFace, SlotEndWallFace, ComposeTransition, EdgeFinishReplacementFace, FilletSurface, ConvexJunctionPatch, ReflexJunctionPatch, CapContactEdge, SideContactEdge, JunctionToRollA, JunctionToRollB, JunctionCapContact, JunctionSideAContact, JunctionSideBContact, StartTerminationFace, EndTerminationFace, StartEndpointArc, EndEndpointArc, RetainedStartSharpEdge, RetainedEndSharpEdge, BoxFace, BoxEdge, ThreadRootFace, ThreadLeadingFlank, ThreadTrailingFlank, ThreadCrest, ThreadStartCap, ThreadEndCap, ThreadBoundaryEdge }
+public enum SemanticTopologyRole { Unknown, ProfileVertex, VerticalExtrusionEdge, LocalStartBoundary, LocalEndBoundary, LocalStartCapLoop, LocalEndCapLoop, TopBoundary, BottomBoundary, ExtrusionSideFace, TopFaceBoundaryLoop, BottomFaceBoundaryLoop, HoleEntryLoop, HoleExitLoop, HoleWallFace, HoleShaftToDrillPointLoop, HoleShaftToDrillPointEdge, HoleDrillPointFace, HoleTipVertex, HoleCounterboreMouthLoop, HoleCounterboreWallFace, HoleCounterboreShoulderLoop, HoleCounterboreShaftWallFace, SlotEntryLoop, SlotExitLoop, SlotWallFace, SlotStraightWallFace, SlotEndWallFace, ComposeTransition, EdgeFinishReplacementFace, FilletSurface, ConvexJunctionPatch, ReflexJunctionPatch, CapContactEdge, SideContactEdge, JunctionToRollA, JunctionToRollB, JunctionCapContact, JunctionSideAContact, JunctionSideBContact, StartTerminationFace, EndTerminationFace, StartEndpointArc, EndEndpointArc, RetainedStartSharpEdge, RetainedEndSharpEdge, BoxFace, BoxEdge, ThreadRootFace, ThreadLeadingFlank, ThreadTrailingFlank, ThreadCrest, ThreadStartCap, ThreadEndCap, ThreadBoundaryEdge, HoleCountersinkWallFace }
public enum SemanticTopologyAddressability { AuthoredStable, DerivedStable, ImportedStable, RuntimeOnly, Ambiguous, Unstable }
public enum SemanticSelectionRequirement { ExactlyOne, OneOrMore, ConnectedChain, ClosedLoop, NonEmptyFaceSet }
public enum SemanticSelectionFailure { None, SemanticSourceNotFound, NoMaterializedDescendants, AmbiguousBodyContext, SelectionCardinalityMismatch, DescendantsNotConnected, DescendantsBranch, DescendantsDoNotClose, MixedBoundaryRoles, UnsupportedTopologyChange, SelectionConsumerMismatch }
diff --git a/Aetheris.Kernel.Firmament/Visualization/PmiDisplayProjection.cs b/Aetheris.Kernel.Firmament/Visualization/PmiDisplayProjection.cs
index 5db704ca..e97f450a 100644
--- a/Aetheris.Kernel.Firmament/Visualization/PmiDisplayProjection.cs
+++ b/Aetheris.Kernel.Firmament/Visualization/PmiDisplayProjection.cs
@@ -60,11 +60,27 @@ public static class PmiDisplayProjection
if (targets.Length == 0 || targets.Length != item.GeometricFaceEntityIds.Count)
throw new InvalidOperationException($"pmi-display-target-unresolved: '{item.Name}' has no complete geometric face association.");
double[] label = [maxX + height * 3, maxY - result.Count * height * 2.5, maxZ + height];
- // One marker for every association: a multi-face requirement must not silently
- // display only the first target. Current datum/diameter authoring binds one face.
- if (targets.Length != 1)
+ // A section planner can partition one physical cylindrical wall.
+ // Admit only a connected set on the same analytic cylinder, and
+ // retain every associated patch in the highlight and leaders.
+ if (targets.Length != 1 && (item.Kind != "Diameter" || !OneCylindricalWall(body, targets)))
throw new InvalidOperationException($"pmi-display-target-multiple-unsupported: '{item.Name}' requires a multi-face presentation.");
- var (anchorPoint, normal, target) = Target(body, tessellation.Value, targets[0], item.Kind, height, label);
+ var internalEdges = targets.SelectMany(p => body.Topology.GetFace(p.FaceId).LoopIds
+ .SelectMany(id => body.Topology.GetLoop(id).CoedgeIds).Select(id => body.Topology.GetCoedge(id).EdgeId).Distinct())
+ .GroupBy(id => id).Where(g => g.Count() > 1).Select(g => g.Key).ToHashSet();
+ var witnesses = targets.Select(p => Target(body, tessellation.Value, p, item.Kind, height, label, internalEdges)).ToArray();
+ var (anchorPoint, normal, target) = witnesses[0];
+ if (witnesses.Length > 1)
+ {
+ var positions = new List<double>(); var normals = new List<double>(); var indices = new List<int>();
+ foreach (var witness in witnesses)
+ {
+ var offset = positions.Count / 3;
+ positions.AddRange(witness.Marker.Positions); normals.AddRange(witness.Marker.Normals);
+ indices.AddRange(witness.Marker.Indices.Select(i => i + offset));
+ }
+ target = target with { Positions = positions.ToArray(), Normals = normals.ToArray(), Indices = indices.ToArray(), Lines = witnesses.SelectMany(w => w.Marker.Lines).ToArray() };
+ }
double[] anchor = P(anchorPoint);
var stem = anchorPoint + normal * target.StemLength;
string N(double value) => value.ToString("G9", CultureInfo.InvariantCulture);
@@ -72,6 +88,8 @@ public static class PmiDisplayProjection
+ (item.TolerancePlus.HasValue && item.ToleranceMinus.HasValue ? $" +{N(item.TolerancePlus.Value)}/-{N(item.ToleranceMinus.Value)}" : "") + " mm";
var outlines = PlanarTextProfiles.PresentationContours(text, height);
var lines = new List<double[][]> { new[] { anchor, P(stem), new[] { label[0] - height, label[1], label[2] }, label } };
+ foreach (var witness in witnesses.Skip(1))
+ lines.Add([P(witness.Anchor), P(witness.Anchor + witness.Normal * witness.Marker.StemLength), [label[0] - height, label[1], label[2]], label]);
// A small open arrow terminates at the actual support, along its face normal.
var side = Direction3D.Create(normal.Cross(Math.Abs(normal.Z) < .9 ? new(0,0,1) : new Vector3D(0,1,0))).ToVector();
lines.Add([P(anchorPoint + normal * target.StemLength * .35 + side * target.StemLength * .15), anchor,
@@ -101,7 +119,7 @@ public static class PmiDisplayProjection
private static double[] V(Vector3D v) => [v.X, v.Y, v.Z];
private static (Point3D Anchor, Vector3D Normal, PmiDisplayTarget Marker) Target(
- BrepBody body, DisplayTessellationResult tessellation, DisplayFaceMeshPatch patch, string kind, double height, double[] label)
+ BrepBody body, DisplayTessellationResult tessellation, DisplayFaceMeshPatch patch, string kind, double height, double[] label, IReadOnlySet<Aetheris.Kernel.Core.Topology.EdgeId> internalEdges)
{
body.TryGetFaceSurfaceGeometry(patch.FaceId, out var surface);
if (kind == "Datum" && surface?.Plane is PlaneSurface plane)
@@ -160,7 +178,7 @@ public static class PmiDisplayProjection
// Kernel edge wires identify its rims. An edge used twice by this face is a
// parameter seam, not a manufactured edge, so it receives no rim highlight.
var rims = body.Topology.GetFace(patch.FaceId).LoopIds.SelectMany(id => body.Topology.GetLoop(id).CoedgeIds)
- .Select(id => body.Topology.GetCoedge(id).EdgeId).GroupBy(id => id).Where(g => g.Count() == 1).Select(g => g.Key).ToHashSet();
+ .Select(id => body.Topology.GetCoedge(id).EdgeId).GroupBy(id => id).Where(g => g.Count() == 1 && !internalEdges.Contains(g.Key)).Select(g => g.Key).ToHashSet();
var stemLength = Math.Min(height, cylinder.Radius*.45);
var offset = Math.Min(height * .002, stemLength * .01);
double[] Lift(Point3D point) => P(point + cylinder.Normal(Uv(point).X/cylinder.Radius).ToVector() * sense * offset);
@@ -172,6 +190,26 @@ public static class PmiDisplayProjection
throw new InvalidOperationException($"pmi-display-target-kind-unsupported: {kind} requires its qualified plane or cylinder support.");
}
+ private static bool OneCylindricalWall(BrepBody body, IReadOnlyList<DisplayFaceMeshPatch> patches)
+ {
+ var surfaces = patches.Select(p => body.GetFaceSurface(p.FaceId)).ToArray();
+ if (surfaces.Any(s => s.Cylinder is null)) return false;
+ var first = surfaces[0].Cylinder!.Value; var axis = first.Axis.ToVector();
+ if (surfaces.Skip(1).Any(s =>
+ {
+ var c = s.Cylinder!.Value; var delta = c.Origin - first.Origin;
+ return Math.Abs(c.Radius - first.Radius) > 1e-7 || axis.Cross(c.Axis.ToVector()).Length > 1e-7
+ || (delta - axis * delta.Dot(axis)).Length > 1e-7;
+ })) return false;
+ var edges = patches.Select(p => body.Topology.GetFace(p.FaceId).LoopIds.SelectMany(id => body.Topology.GetLoop(id).CoedgeIds)
+ .Select(id => body.Topology.GetCoedge(id).EdgeId).ToHashSet()).ToArray();
+ var seen = new HashSet<int> { 0 }; var pending = new Queue<int>(); pending.Enqueue(0);
+ while (pending.TryDequeue(out var current))
+ for (var i = 0; i < edges.Length; i++)
+ if (!seen.Contains(i) && edges[current].Overlaps(edges[i])) { seen.Add(i); pending.Enqueue(i); }
+ return seen.Count == patches.Count;
+ }
+
private static IEnumerable<(Point3D A, Point3D B, Point3D C)> Triangles(DisplayFaceMeshPatch patch)
{
for (var i = 0; i + 2 < patch.TriangleIndices.Count; i += 3)
diff --git a/Aetheris.slnx b/Aetheris.slnx
index 47d6ded9..71222b85 100644
--- a/Aetheris.slnx
+++ b/Aetheris.slnx
@@ -75,6 +75,7 @@
</Project>
<Project Path="Aetheris.CLI/Aetheris.CLI.csproj" />
<Folder Name="/demos/">
+ <Project Path="demos/Aetheris.CodeNativeBracket/Aetheris.CodeNativeBracket.csproj" />
<Project Path="demos/Aetheris.DifferenceEngine.Showcase/Aetheris.DifferenceEngine.Showcase.csproj" />
<Project Path="demos/Aetheris.DifferenceEngine/Aetheris.DifferenceEngine.csproj" />
<Project Path="demos/Aetheris.EditableV8.Tests/Aetheris.EditableV8.Tests.csproj" />
diff --git a/demos/Aetheris.CodeNativeBracket/Aetheris.CodeNativeBracket.csproj b/demos/Aetheris.CodeNativeBracket/Aetheris.CodeNativeBracket.csproj
new file mode 100644
index 00000000..4d259713
--- /dev/null
+++ b/demos/Aetheris.CodeNativeBracket/Aetheris.CodeNativeBracket.csproj
@@ -0,0 +1,12 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <OutputType>Exe</OutputType>
+ <TargetFramework>net10.0</TargetFramework>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <Nullable>enable</Nullable>
+ </PropertyGroup>
+ <ItemGroup>
+ <ProjectReference Include="../../Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj" />
+ <EmbeddedResource Include="../../fixtures/Regression/ComposeHoleFamilies/bracket-library.firmament" LogicalName="bracket-library.firmament" />
+ </ItemGroup>
+</Project>
diff --git a/demos/Aetheris.CodeNativeBracket/BracketDrawing.cs b/demos/Aetheris.CodeNativeBracket/BracketDrawing.cs
new file mode 100644
index 00000000..8311103a
--- /dev/null
+++ b/demos/Aetheris.CodeNativeBracket/BracketDrawing.cs
@@ -0,0 +1,108 @@
+using Aetheris.Kernel.Firmament.Drawing;
+using static Aetheris.CodeNativeBracket.BracketDimensions;
+
+namespace Aetheris.CodeNativeBracket;
+
+/// <summary>Authored drawing for this family only. Views remain compiler projections of the exported body.</summary>
+internal static class BracketDrawing
+{
+ public static DrawingIr Complete(DrawingIr projected, BracketDimensions p, IReadOnlyList<int> coveredFaces, IReadOnlySet<string> holeRims, string holeIdentity)
+ {
+ var original = projected.Pages.Single();
+ var scale = Math.Min(98d / p.Width, 76d / p.Height);
+ var top = Place(original.Views.Single(v => v.Identity == "TOP"), 43, 35, scale);
+ var edge = Place(original.Views.Single(v => v.Identity == "EDGE"), 43, 135, scale);
+ var iso = Place(original.Views.Single(v => v.Identity == "ISO"), 183, 89, .75);
+ // Edge projection alone cannot supply a cylinder/cone's apparent contour.
+ // Author this family's hidden bore silhouette, replacing only the actual
+ // associated rim edges (whose side projections otherwise look like stubs).
+ var centerX = edge.GeometryBounds.X + p.HoleX * scale;
+ var shaftRadius = p.ShaftDiameter / 2d * scale; var entryRadius = p.EntryDiameter / 2d * scale;
+ var shoulder = edge.GeometryBounds.Y + (entryRadius - shaftRadius); // 90-degree included angle
+ var boreLines = new[] { -1d, 1d }.Select(side => new DrawingProjectedPrimitiveIr("H1-hidden-" + side, DrawingPrimitiveKind.Hidden,
+ [new(centerX + side * shaftRadius, edge.GeometryBounds.Bottom), new(centerX + side * shaftRadius, shoulder),
+ new(centerX + side * entryRadius, edge.GeometryBounds.Y)], null, 0)).ToArray();
+ edge = edge with { Primitives = edge.Primitives.Where(line => line.SourceEdgeIdentity is null || !holeRims.Contains(line.SourceEdgeIdentity)).Concat(boreLines).ToArray() };
+ var annotations = new List<DrawingAnnotationIr>();
+ DrawingPoint2 Top(double x, double y) => new(top.GeometryBounds.X + x * scale, top.GeometryBounds.Bottom - y * scale);
+ DrawingAnnotationIr Label(string id, string text, double x, double y, double width, DrawingPoint2 anchor, params DrawingPoint2[] leader)
+ {
+ var candidate = new DrawingAnnotationCandidateIr(id, new(x, y, width, 5), leader, "authored", 0, 0, []);
+ return new(id, id, "TOP", DrawingAnnotationKind.Note, text, anchor, candidate, [candidate], "Authored bracket dimensions from typed specification");
+ }
+ void Horizontal(string id, double length, DrawingPoint2 a, DrawingPoint2 b, double y)
+ {
+ annotations.Add(Label(id, F(length) + " ±0.1", (a.X + b.X) / 2 - 11, y - 6, 24, a) with
+ { Kind = DrawingAnnotationKind.LinearDimension, DimensionLines = [new(a, new(a.X, y + 2)), new(b, new(b.X, y + 2)), new(new(a.X, y), new(b.X, y), true, true)] });
+ }
+ void Vertical(string id, double length, DrawingPoint2 a, DrawingPoint2 b, double x)
+ {
+ annotations.Add(Label(id, F(length) + " ±0.1", id == "overall-height" ? x - 24 : x + 3, (a.Y + b.Y) / 2 - 3, 23, a) with
+ { Kind = DrawingAnnotationKind.LinearDimension, DimensionLines = [new(a, new(x - 2, a.Y)), new(b, new(x - 2, b.Y)), new(new(x, a.Y), new(x, b.Y), true, true)] });
+ }
+ Horizontal("overall-width", p.Width, Top(0, 0), Top(p.Width, 0), top.GeometryBounds.Bottom + 12);
+ Vertical("overall-height", p.Height, Top(0, 0), Top(0, p.Height), top.GeometryBounds.X - 10);
+ Horizontal("leg-width", p.LegWidth, Top(0, p.Height), Top(p.LegWidth, p.Height), top.GeometryBounds.Y - 9);
+ Vertical("leg-height", p.LegHeight, Top(p.Width, 0), Top(p.Width, p.LegHeight), top.GeometryBounds.Right + 10);
+ var hole = Top(p.HoleX, p.HoleY);
+ top = top with { Primitives = top.Primitives.Concat(new[]
+ {
+ new DrawingProjectedPrimitiveIr("H1-center-x", DrawingPrimitiveKind.CenterMark, [new(hole.X - 5, hole.Y), new(hole.X + 5, hole.Y)], null, 0),
+ new DrawingProjectedPrimitiveIr("H1-center-y", DrawingPrimitiveKind.CenterMark, [new(hole.X, hole.Y - 5), new(hole.X, hole.Y + 5)], null, 0)
+ }).ToArray() };
+ annotations.Add(Label("hole-id", "H1", hole.X + 7, hole.Y - 5, 8, hole));
+ var zero = Top(0, 0);
+ annotations.Add(Label("coordinate-origin", "O (X0, Y0)", zero.X - 30, zero.Y + 3, 26, zero, zero, new(zero.X - 3, zero.Y + 5), new(zero.X - 6, zero.Y + 5)));
+ var plane = Top(p.LegWidth / 2, p.Height * .6);
+ annotations.Add(Label("datum-a", "DATUM A", plane.X + 15, plane.Y - 3, 24, plane, plane, new(plane.X + 15, plane.Y)) with { Kind = DrawingAnnotationKind.Datum });
+ Vertical("thickness", p.Thickness, new(edge.GeometryBounds.Right, edge.GeometryBounds.Y), new(edge.GeometryBounds.Right, edge.GeometryBounds.Bottom), edge.GeometryBounds.Right + 10);
+ var tables = new DrawingTableIr[]
+ {
+ new("H1 CENTER FROM O / mm", ["ID", "X ±0.1", "Y ±0.1"], [["H1", F(p.HoleX), F(p.HoleY)]], "dimensions", "Authored coordinate intervals", DrawingTableKind.HoleCoordinates, new(180, 32, 104, 14)),
+ new("H1 COUNTERSUNK THROUGH HOLE", ["THRU Ø ±0.1", "CSK Ø ±0.1", "Angle ±0.5°"], [[F(p.ShaftDiameter), F(p.EntryDiameter), "90°"]], "dimensions", "TOP entry, included cone angle", DrawingTableKind.Design, new(180, 59, 104, 14))
+ };
+ var notes = new[]
+ {
+ "ALL DIMENSIONS mm. DO NOT SCALE.",
+ "O: lower-left TOP vertex. +X right, +Y up.",
+ "Six straight edges. Unspecified angles 90° ±0.5°.",
+ "Uniform thickness; hole axis normal to A.",
+ "CSK enters DATUM A (TOP); shaft is THRU.",
+ "X/Y are independent ± limits, not GD&T position.",
+ "Process capability / inspection approval pending."
+ };
+ var page = original with
+ {
+ Views = [top, edge, iso], Annotations = annotations, Tables = tables, Notes = notes,
+ LocatedNotes = notes.Select((text, i) => new DrawingNoteIr("note-" + i, text, new(10, 159 + i * 5.4, 106, 5), new(1, "D1"))).ToArray()
+ };
+ // Paper-space checks guard the authored layout as the parameters change.
+ var labels = annotations.Select(a => a.SelectedCandidate.Body).ToArray();
+ if (labels.Any(r => r.X < 7 || r.Right > 290 || r.Y < 15 || r.Bottom > 157)) throw new InvalidOperationException("Bracket drawing labels do not fit the authored sheet.");
+ if (labels.Where((a, i) => labels.Skip(i + 1).Any(a.Intersects)).Any()) throw new InvalidOperationException("Bracket drawing labels overlap.");
+ return projected with
+ {
+ Pages = [page],
+ LayoutEvidence = new(annotations.Count, 0, 0, 0, new Dictionary<string, int> { ["authored"] = annotations.Count }, 0, 0),
+ DefinitionEvidence = new(true, true, true, false, "AuthoredSixEdgeLWithNormalCountersink",
+ coveredFaces, ["Process capability and independent human approval are unqualified."],
+ new Dictionary<string, double> { ["width"] = p.Width, ["height"] = p.Height, ["legWidth"] = p.LegWidth, ["legHeight"] = p.LegHeight, ["thickness"] = p.Thickness },
+ [new("H1", p.HoleX, p.HoleY, p.ShaftDiameter, "THRU; CSK " + F(p.EntryDiameter) + " x 90deg on A", "H1", [holeIdentity])], .1)
+ { AngularToleranceDegrees = .5, ToleranceScreenScope = "Authored dimensions; no claim of machine/process qualification." }
+ };
+ }
+
+ private static DrawingViewIr Place(DrawingViewIr view, double left, double top, double scale)
+ {
+ var ratio = scale / view.Scale;
+ DrawingPoint2 Move(DrawingPoint2 p) => new(left + (p.X - view.GeometryBounds.X) * ratio, top + (p.Y - view.GeometryBounds.Y) * ratio);
+ var bounds = new DrawingRect(left, top, view.GeometryBounds.Width * ratio, view.GeometryBounds.Height * ratio);
+ return view with
+ {
+ GeometryBounds = bounds, Viewport = new(left - 5, top - 7, bounds.Width + 10, bounds.Height + 10), Scale = scale,
+ Primitives = view.Primitives.Select(p => p with { Points = p.Points.Select(Move).ToArray() }).ToArray(),
+ SemanticAnchors = view.SemanticAnchors.ToDictionary(a => a.Key, a => Move(a.Value)),
+ Camera = view.Camera is { } c ? c with { OriginX = Move(new(c.OriginX, c.OriginY)).X, OriginY = Move(new(c.OriginX, c.OriginY)).Y } : null
+ };
+ }
+}
diff --git a/demos/Aetheris.CodeNativeBracket/Program.cs b/demos/Aetheris.CodeNativeBracket/Program.cs
new file mode 100644
index 00000000..2e559f6c
--- /dev/null
+++ b/demos/Aetheris.CodeNativeBracket/Program.cs
@@ -0,0 +1,142 @@
+using System.Globalization;
+using System.Reflection;
+using System.Security.Cryptography;
+using System.Text.Json;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Brep.Verification;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament;
+using Aetheris.Kernel.Firmament.Assembly;
+using Aetheris.Kernel.Firmament.Drawing;
+using Aetheris.Kernel.Firmament.Export;
+
+namespace Aetheris.CodeNativeBracket;
+
+public static class Program
+{
+ private static int Main(string[] args)
+ {
+ try
+ {
+ if (args.Length > 1 || args.Any(arg => arg.StartsWith('-')))
+ throw new ArgumentException("Usage: Aetheris.CodeNativeBracket [output-directory]");
+ var output = Path.GetFullPath(args.FirstOrDefault() ?? "artifacts/local/demos/code-native-bracket");
+ MakeBracket(new(), Path.Combine(output, "nominal"));
+ MakeBracket(new(Width: 100, Height: 75, LegWidth: 25, LegHeight: 24, Thickness: 15, HoleX: 70, HoleY: 12, ShaftDiameter: 8, EntryDiameter: 14), Path.Combine(output, "variant"));
+ Console.WriteLine($"Rehearsal artifacts: {output}");
+ return 0;
+ }
+ catch (Exception exception) { Console.Error.WriteLine(exception.Message); return 1; }
+ }
+
+ public static void MakeBracket(BracketDimensions dimensions, string output)
+ {
+ var maxRadius = (dimensions.EntryDiameter + .1) / 2;
+ var lean = (dimensions.Thickness + .1) * Math.Tan(.5 * Math.PI / 180d);
+ var minimumWeb = Math.Min(Math.Min(dimensions.HoleY - .1 - maxRadius, dimensions.LegHeight - .1 - dimensions.HoleY - .1 - maxRadius),
+ Math.Min(dimensions.HoleX - .1 - maxRadius, dimensions.Width - .1 - dimensions.HoleX - .1 - maxRadius)) - lean;
+ var deepestEntry = (dimensions.EntryDiameter + .1 - (dimensions.ShaftDiameter - .1)) / (2 * Math.Tan(89.5 * Math.PI / 360d));
+ if (minimumWeb <= 0 || dimensions.Thickness - .1 <= deepestEntry || dimensions.ShaftDiameter <= .1)
+ throw new InvalidOperationException("Bracket drawing limits permit breakout or no shaft. Revise dimensions before exporting.");
+ Directory.CreateDirectory(output);
+ var source = dimensions.Source(false);
+ var path = Path.Combine(output, "bracket.firmament");
+ File.WriteAllText(path, source);
+ var compilation = FirmamentBuildAndExport.CompileSource(source);
+ if (!compilation.IsSuccess) throw new InvalidOperationException(string.Join("\n", compilation.Diagnostics.Select(d => d.Message)));
+ var product = compilation.Value;
+ var imported = Step242Importer.ImportBody(product.StepText);
+ if (!imported.IsSuccess) throw new InvalidOperationException("Rehearsal STEP reimport failed.");
+ var body = imported.Value;
+ if (!BrepExportPreflight.Validate(body).IsValid) throw new InvalidOperationException("STEP failed export preflight.");
+ var mass = BrepMassProperties.Evaluate(body);
+ if (!mass.IsEnclosed || !mass.IsOrientationConsistent || Math.Abs(mass.AbsoluteVolume - dimensions.Volume) > Math.Min(mass.ErrorBound ?? 0, dimensions.Volume * 2e-5))
+ throw new InvalidOperationException("Reimported geometry failed independent bounded volume/enclosure verification.");
+ var tessellation = BrepDisplayTessellator.Tessellate(body);
+ if (!tessellation.IsSuccess) throw new InvalidOperationException("GLB tessellation failed.");
+ var positions = new List<double>(); var normals = new List<double>(); var indices = new List<int>();
+ foreach (var face in tessellation.Value.FacePatches)
+ {
+ var offset = positions.Count / 3;
+ positions.AddRange(face.Positions.SelectMany(p => new[] { p.X, p.Y, p.Z }));
+ normals.AddRange(face.Normals.SelectMany(p => new[] { p.X, p.Y, p.Z }));
+ indices.AddRange(face.TriangleIndices.Select(i => i + offset));
+ }
+ var display = new AssemblyDisplayMeshDocument("aetheris/display-mesh/1", "Bracket", "mm",
+ [new("bracket-definition", "bracket", positions.ToArray(), normals.ToArray(), indices.ToArray())],
+ [new("bracket", "Bracket", null, "bracket-definition", [1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])]);
+ foreach (var artifact in ProductArtifactExporter.Export(new("Bracket", product.StepText, display), ["step", "glb"], output))
+ File.WriteAllBytes(Path.Combine(output, artifact.FileName), artifact.Bytes);
+
+ // Authored views use the existing compiler projection and title block.
+ // This small family supplies its own dimensions, not a general recognizer.
+ var drawingPath = Path.Combine(output, "bracket-drawing.firmament");
+ File.WriteAllText(drawingPath, dimensions.Source(true));
+ var drawing = FirmamentDrawingCompiler.Compile(drawingPath, Path.Combine(output, "drawing-base"),
+ new(new("Codex (AI)", "2026-10-21"), new(), new()));
+ if (!drawing.IsSuccess) throw new InvalidOperationException(string.Join("\n", drawing.Diagnostics));
+ var holeRims = body.Topology.Edges.Where(e => body.TryGetEdgeCurveGeometry(e.Id, out var curve) && curve?.Circle3 is { } circle
+ && Math.Abs(circle.Center.X - dimensions.HoleX) < 1e-7 && Math.Abs(circle.Center.Y - dimensions.HoleY) < 1e-7)
+ .Select(e => "edge:" + e.Id.Value).ToHashSet(StringComparer.Ordinal);
+ var defined = BracketDrawing.Complete(drawing.Artifacts!.Drawing, dimensions, body.Topology.Faces.Select(f => f.Id.Value).ToArray(), holeRims, product.Features!.Single().FeatureId);
+ File.WriteAllText(Path.Combine(output, "Bracket.svg"), DrawingSvgRenderer.Render(defined));
+ DrawingVectorPdfWriter.Write(defined, Path.Combine(output, "Bracket.pdf"));
+ DrawingPptxWriter.WriteDrawing(defined, Path.Combine(output, "Bracket.pptx"), false);
+ File.WriteAllText(Path.Combine(output, "Bracket.drawing.json"), JsonSerializer.Serialize(defined, JsonOptions));
+ var hashes = Directory.GetFiles(output).Where(p => Path.GetExtension(p) is ".step" or ".glb" or ".pdf" or ".svg")
+ .ToDictionary(p => Path.GetFileName(p)!, p => Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(p))).ToLowerInvariant());
+ File.WriteAllText(Path.Combine(output, "qualification.json"), JsonSerializer.Serialize(new
+ {
+ dimensions, exactConstructionVolume = dimensions.Volume,
+ independentMass = new { mass.AbsoluteVolume, mass.EvaluationMethod, mass.ErrorBound, mass.IsEnclosed, mass.IsOrientationConsistent },
+ pmi = Step242SemanticPmiInspector.Inspect(product.StepText),
+ bodyFaces = body.Topology.Faces.Count(), triangleCount = indices.Count / 3,
+ nominalDrawingDefinition = "Authored L-bracket dimensions; independently reconstruct from PDF before demo publication.",
+ processCapabilityVerified = false, hashes,
+ toleranceScreen = new { minimumWebMillimetres = minimumWeb, maximumEntryDepthMillimetres = deepestEntry,
+ scope = "Independent Cartesian/size limits and axis lean on ideal orthogonal stock; stock form and machine/process capability unqualified." }
+ }, JsonOptions));
+ }
+
+ internal static readonly JsonSerializerOptions JsonOptions = new() { WriteIndented = true };
+}
+
+public sealed record BracketDimensions(double Width = 80, double Height = 60, double LegWidth = 20, double LegHeight = 20,
+ double Thickness = 12, double HoleX = 60, double HoleY = 10, double ShaftDiameter = 6, double EntryDiameter = 12)
+{
+ public double Volume => (Width * LegHeight + LegWidth * (Height - LegHeight)) * Thickness
+ - Math.PI * ShaftDiameter * ShaftDiameter / 4d * Thickness
+ - Math.PI * (EntryDiameter - ShaftDiameter) / 2d *
+ (EntryDiameter * EntryDiameter + EntryDiameter * ShaftDiameter - 2 * ShaftDiameter * ShaftDiameter) / 12d;
+
+ public string Source(bool includeDrawing)
+ {
+ using var reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("bracket-library.firmament")!);
+ var library = reader.ReadToEnd();
+ var source = "Model CodeNativeBracket {\nunits: mm\n" + library + FormattableString.Invariant($$"""
+
+ Static dimensions: BracketDimensions = BracketDimensions {
+ width: {{Width}}mm; height: {{Height}}mm; legWidth: {{LegWidth}}mm; legHeight: {{LegHeight}}mm
+ thickness: {{Thickness}}mm; holeX: {{HoleX}}mm; holeY: {{HoleY}}mm
+ shaftDiameter: {{ShaftDiameter}}mm; entryDiameter: {{EntryDiameter}}mm
+ }
+ Struct Bracket = BracketTemplate<spec: dimensions>
+ """);
+ if (includeDrawing) source += "\n" + """
+ Drawing BracketProduction {
+ source: CodeNativeBracket
+ title: "PARAMETRIC MACHINED L BRACKET"
+ partNumber: "CND-BRACKET"
+ revision: 1.0.0
+ material: "6061-T6 aluminium"
+ orientation: Landscape
+ View TOP { direction: +Z; hiddenLines: Wireframe; pmi: [] }
+ View EDGE { direction: -Y; hiddenLines: VisibleAndHidden; pmi: [] }
+ View ISO { direction: [1, -1, 1]; projection: Isometric; hiddenLines: VisibleOnly; pmi: [] }
+ }
+ """;
+ return source + "\n}\n";
+ }
+ public static string F(double value) => value.ToString("0.###", CultureInfo.InvariantCulture);
+}
diff --git a/demos/Aetheris.CodeNativeBracket/Run-Rehearsal.ps1 b/demos/Aetheris.CodeNativeBracket/Run-Rehearsal.ps1
new file mode 100644
index 00000000..26d14d74
--- /dev/null
+++ b/demos/Aetheris.CodeNativeBracket/Run-Rehearsal.ps1
@@ -0,0 +1,25 @@
+param(
+ [string]$OutputDirectory = 'artifacts/local/demos/code-native-bracket',
+ [string]$Python = 'python'
+)
+$ErrorActionPreference = 'Stop'
+$repository = (Resolve-Path (Join-Path $PSScriptRoot '../..')).Path
+Push-Location $repository
+try {
+ & dotnet build Aetheris.CLI -c Release -m:1 -nr:false -p:UseSharedCompilation=false
+ if ($LASTEXITCODE -ne 0) { throw 'CLI build failed.' }
+ & dotnet build demos/Aetheris.CodeNativeBracket -c Release -m:1 -nr:false -p:UseSharedCompilation=false
+ if ($LASTEXITCODE -ne 0) { throw 'Bracket runner build failed.' }
+ & dotnet demos/Aetheris.CodeNativeBracket/bin/Release/net10.0/Aetheris.CodeNativeBracket.dll $OutputDirectory
+ if ($LASTEXITCODE -ne 0) { throw 'Artifact generation failed.' }
+ foreach ($case in @('nominal', 'variant')) {
+ $caseDirectory = Join-Path $OutputDirectory $case
+ & $Python fixtures/Regression/ComposeHoleFamilies/reconstruct_bracket_pdf.py `
+ --pdf (Join-Path $caseDirectory 'Bracket.pdf') --reference-step (Join-Path $caseDirectory 'Bracket.step') `
+ --out-dir (Join-Path $caseDirectory 'pdf-reconstruction') --cli Aetheris.CLI/bin/Release/net10.0/aetheris.dll
+ if ($LASTEXITCODE -ne 0) { throw "PDF-only reconstruction failed: $case" }
+ & dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll validate (Join-Path $caseDirectory 'bracket.firmament') --json
+ if ($LASTEXITCODE -ne 0) { throw "Admission failed: $case" }
+ }
+}
+finally { Pop-Location }
diff --git a/demos/README.md b/demos/README.md
index 98906697..61a2f3c2 100644
--- a/demos/README.md
+++ b/demos/README.md
@@ -2,4 +2,7 @@
Demos are runnable narrative demonstrations of an Aetheris capability. Keep the owning project, authored assets, runner, and explanation together.
+The [code-native bracket rehearsal](../docs/public/code-native-bracket.md) generates
+a typed parametric L bracket, STEP/GLB/PDF artifacts and PDF-only reconstruction evidence.
+
Use [`samples/`](../samples/README.md) for external-consumer integration examples. Regression-only Firmament source belongs under [`fixtures/`](../fixtures/README.md). The `.firm` extension is local to `Aetheris.PmiInjectionDemo`'s overlay template/output and is not a general Firmament document type. Per-run demo output belongs under ignored `artifacts/local/demos/`.
diff --git a/docs/public/code-native-bracket.md b/docs/public/code-native-bracket.md
new file mode 100644
index 00000000..1fae58ac
--- /dev/null
+++ b/docs/public/code-native-bracket.md
@@ -0,0 +1,85 @@
+# Rehearse a code-native part build
+
+This local demo builds one parametric machined L bracket, exports STEP AP242,
+GLB, a dimensioned PDF, SVG and PPTX, and reconstructs the nominal solid from
+the PDF alone. It does not push to GitHub or modify a demo repository.
+
+The small C# entry point calls `MakeBracket(dimensions, outputDirectory)` for
+two specifications. A typed Firmament Record and Template own the part: two
+`Rect2` guides, a six-edge trace loop, an extrusion and a countersunk through
+hole. The C# wrapper calls the existing compiler and exporters. There is no
+Assembly wrapper or alternate geometry implementation.
+
+## Run locally
+
+From the Aetheris repository root, with .NET 10 and Python's `pypdf` installed:
+
+```powershell
+dotnet build Aetheris.CLI -c Release -m:1 -nr:false -p:UseSharedCompilation=false
+dotnet build demos/Aetheris.CodeNativeBracket -c Release -m:1 -nr:false -p:UseSharedCompilation=false
+dotnet demos/Aetheris.CodeNativeBracket/bin/Release/net10.0/Aetheris.CodeNativeBracket.dll
+python fixtures/Regression/ComposeHoleFamilies/reconstruct_bracket_pdf.py --pdf artifacts/local/demos/code-native-bracket/nominal/Bracket.pdf --reference-step artifacts/local/demos/code-native-bracket/nominal/Bracket.step --out-dir artifacts/local/demos/code-native-bracket/nominal/pdf-reconstruction --cli Aetheris.CLI/bin/Release/net10.0/aetheris.dll
+python fixtures/Regression/ComposeHoleFamilies/reconstruct_bracket_pdf.py --pdf artifacts/local/demos/code-native-bracket/variant/Bracket.pdf --reference-step artifacts/local/demos/code-native-bracket/variant/Bracket.step --out-dir artifacts/local/demos/code-native-bracket/variant/pdf-reconstruction --cli Aetheris.CLI/bin/Release/net10.0/aetheris.dll
+```
+
+The same commands work in a Linux shell. Alternatively run
+`pwsh demos/Aetheris.CodeNativeBracket/Run-Rehearsal.ps1`.
+The default output root is ignored `artifacts/local/demos/code-native-bracket`;
+the executable accepts an explicit output directory as its only argument.
+
+| Input | Nominal | Resized variant |
+| --- | ---: | ---: |
+| Overall X / Y / Z (mm) | 80 / 60 / 12 | 100 / 75 / 15 |
+| Vertical / horizontal leg widths (mm) | 20 / 20 | 25 / 24 |
+| Hole X / Y from O (mm) | 60 / 10 | 70 / 12 |
+| Shaft / countersink entry diameter (mm) | 6 / 12 | 8 / 14 |
+| Countersink included angle | 90° | 90° |
+
+Each output directory contains the instantiated geometry source, the authored
+drawing source, exact STEP, display GLB with supported semantic PMI, the final
+PDF/SVG/PPTX, Drawing IR and a compact qualification/hash report. The intermediate
+`drawing-base` sheets are the compiler's projections before this family's authored
+dimension layout; use the final `Bracket.pdf` for review.
+
+AP242 and GLB carry the supported semantic datum and shaft-diameter PMI. The
+outline dimensions, countersink entry/angle and their additional drawing limits
+are authored on the PDF; this demo does not claim unsupported STEP PMI kinds were
+projected or that all drawing requirements are encoded in AP242.
+
+## What the drawing proves
+
+Five controlling dimensions define the six straight outline edges and uniform
+thickness. The marked origin O establishes X0/Y0; the hole schedule states its
+Cartesian coordinates and limits. A separate schedule specifies through diameter,
+countersink diameter and included angle. The drawing identifies the top entry
+plane A and normal hole axis. Nominal reconstruction does not require measuring
+the picture, consulting the source or opening the STEP.
+
+The independent reader consumes only printed PDF text. It freezes a new Path-based
+Firmament model before opening the reference STEP. Qualification then compares
+bounds, topology counts, vertices, cylinder/cone supports and independently
+evaluated volumes. Missing size, origin, coordinate limits, hole row, countersink
+angle/limits, through extent, axis orientation or outline-angle definition must
+make the reader reject (nine negative mutations per sheet). This is a
+bounded reconstruction witness for this drawing convention, not general PDF/OCR.
+
+The linear limits are ±0.1 mm; specified and otherwise nominally right angles
+have ±0.5° limits. A conservative screen rejects limits permitting entry breakout
+or eliminating the shaft, using Cartesian/size limits and hole-axis lean on
+ideal orthogonal stock. It does not qualify stock form, all angular stacks,
+machining process capability or inspection. Material is explicitly 6061-T6
+aluminium. Drawn-by credits Codex (AI); checked/approved names and dates remain
+blank. These are engineering-review artifacts, not signed manufacturing release.
+
+The automatic drawing planner still supports its documented rectangular-plate
+family. This bracket uses authored dimensions over compiler-projected views;
+successful bracket export does not expand automatic drawing recognition.
+
+## Boundary before a public CI demo
+
+Use current source or a subsequently qualified release: published Preview 3
+predates composed-profile countersinks. Pin the Aetheris revision and .NET SDK,
+run admission/tests, generate artifacts, run both PDF reconstruction witnesses,
+then upload the STEP/GLB/PDF and qualification report. Parameter changes should
+produce reviewable source diffs and rebuilt artifacts. A hosted GitHub Actions
+run is a separate qualification step; this rehearsal does not claim one occurred.
diff --git a/docs/public/drawings.md b/docs/public/drawings.md
index e448538c..7513979d 100644
--- a/docs/public/drawings.md
+++ b/docs/public/drawings.md
@@ -31,6 +31,11 @@ families require an authored complete drawing until their dimension planners are
qualified. They fail automatic generation with `drawing-definition-incomplete`;
a sampled bounding box is never used to claim complete dimensions.
+The [code-native bracket rehearsal](code-native-bracket.md) demonstrates the
+authored route for a traced L outline with a countersunk through hole. Its final
+PDF is independently reconstructed and compared with STEP for two parameter sets.
+That bounded authoring helper does not extend the automatic recognition family.
+
A qualified plate receives:
- Exact controlling width and height dimensions, and thickness on an aligned edge
diff --git a/docs/public/firmament/geometry.md b/docs/public/firmament/geometry.md
index 48d9eda5..5428658b 100644
--- a/docs/public/firmament/geometry.md
+++ b/docs/public/firmament/geometry.md
@@ -18,7 +18,29 @@ Use named features and selectors, never raw internal B-rep IDs in native authori
A face-local `Hole<Shaft>` or `Hole<Counterbore>` on a `Box` may cross the edge of its entry face: a through hole drilled near an edge leaves a notch, and it builds as one. Only exact tangency is rejected, because the wall there would have zero thickness along a line; the diagnostic gives the threshold in your own terms (for example, "Put Center X below 19mm to keep a wall on that side, or above it to cut through the +X face"). Countersunk and drill-point holes, whose entries are conical, are not yet supported when they break out, and say so.
-`HoleDiameter` on a `Hole<Counterbore>` targets the shaft `Diameter`; `CounterboreDiameter` remains a distinct feature field and has no separate public PMI record kind in Preview 3. Pattern generation supports geometry as a semantic whole; authored names for generated instances are not a stable public instance-selector family in Preview 3.
+`HoleDiameter` on `Hole<Counterbore>` and `Hole<Countersink>` targets the shaft `Diameter`; `CounterboreDiameter` remains a distinct feature field and has no separate public PMI record kind in Preview 3. Pattern generation supports geometry as a semantic whole; authored names for generated instances are not a stable public instance-selector family in Preview 3.
+
+### Circular hole families on composed profiles (current source)
+
+A traced L profile or other admitted line/arc composition can carry
+`Hole<Shaft>`, `Hole<Counterbore>` and `Hole<Countersink>`. Through holes enter on
+`+Z`, or a validated coplanar `Span<Plane>`. Counterbore steps remain cylindrical;
+countersinks use exact conical walls and circular trims. Both require a positive
+shaft interval and strict interior material around the entry. Entry height is
+resolved at the authored center. Unrelated bosses cannot lift a counterbore or
+countersink above its plate, and a pocket-floor entry must fit the exposed floor. The planner checks
+actual composed material through the cavity depth, so a nearby pocket or slot
+cannot silently clip the entry. Cavities must be disjoint; breakout, touching
+cavities, unsupported blind ends and oriented support adapters reject explicitly.
+
+`HoleDiameter` attaches to the shaft wall patches, excluding the larger recess
+and cone. AP242 preserves every shaft patch association. The GLB presentation
+adapter displays all patches when they form one connected analytic cylindrical
+wall; different axes and disconnected walls still require a multi-target
+presentation. This does not change the engineering body.
+
+See the [local bracket rehearsal](../code-native-bracket.md) for a typed
+Template, two-Rect2 traced L, countersink and PDF-only reconstruction witness.
## Boss
diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.md
index 1e19b4d8..b4ab73b8 100644
--- a/docs/public/firmament/syntax.md
+++ b/docs/public/firmament/syntax.md
@@ -698,6 +698,26 @@ uses `counterboreDiameter` and `counterboreDepth`; `Hole<Countersink>` uses
are errors. Compiler completion and bound-field inspection project the same
variant applicability from the shared schema.
+Profile-composed bodies admit all three hole variants on `+Z` (or an admitted
+`Span<Plane>` on that same top support), with `end: ThroughAll`. Counterbores
+require positive shaft length below their recess; countersinks require positive
+shaft length below the cone. The entry resolves against material at the hole
+center, so a taller boss elsewhere does not lift it; an exposed pocket floor
+can be an entry only when the whole mouth fits that floor. The entire entry footprint must stay in actual
+composed material, including any pockets and slots. Intersecting/tangent entry
+footprints and wall breakouts reject explicitly. A countersink is an exact cone,
+not a stack of cylindrical approximations. Arbitrary oriented Compose hole
+supports and blind counterbore/countersink ends remain outside this adapter.
+
+A disjoint top-perimeter chamfer may coexist with these cavities. Its corridor
+cannot cross a counterbore shoulder or shaft-to-cone transition; an overlapping
+cavity/edge-finish corridor rejects instead of changing either feature. A named
+Profile perimeter uses that Profile's material support, rather than an unrelated
+boss's globally highest face.
+Composed-body fillets remain rejected: the standalone Profile fillet planner
+constructs an extrusion and is not an adapter for retaining an existing stack's
+cavities. Primitive and standalone Profile fillet support is unchanged.
+
| Intent | Current vocabulary | Placement / termination |
| --- | --- | --- |
| Drill a hole | `Hole<Shaft>`, `Hole<Counterbore>`, `Hole<Countersink>` | `on`, `center`, `end: ThroughAll` or a bounded blind end. |
diff --git a/docs/public/reference/known-issues.md b/docs/public/reference/known-issues.md
index 56dc6991..dd18a844 100644
--- a/docs/public/reference/known-issues.md
+++ b/docs/public/reference/known-issues.md
@@ -3,7 +3,8 @@
- Release binaries are qualified for Windows x64 only. Framework tests on other platforms are not a binary-support promise.
- `inlineSTEP` FEA supports the documented single-body imported class and stable imported face identities. Arbitrary imported containment and multi-root assembly-like STEP are rejected explicitly; some OCCT B-spline containment cases remain outside the qualified class.
- The generic tessellated mass verifier can report `Unavailable` for some valid combined analytic Boss/Pocket/hole models when a face cannot be triangulated. STEP reimport, manifold checks, analytic surface inventory, bounds, and route-specific analytic volume remain available; do not interpret an unavailable tessellation estimate as a topology failure.
-- Compose-host Countersink is outside the current section-stack feature family. Model-domain Countersink remains supported. Sheet Metal Counterbore and Countersink are rejected because those formed-opening semantics are not implemented.
+- The published Preview 3 binary predates composed-profile Countersink. Current source admits bounded +Z through counterbore/countersink entries with complete disjoint footprints and positive shaft length. Oriented Compose hole adapters, entry breakouts and chamfer corridors crossing a cavity transition remain explicitly rejected. Sheet Metal Counterbore and Countersink are rejected because those formed-opening semantics are not implemented.
+- Composed-body fillets require a cavity-preserving adapter over the existing body. The standalone Profile fillet planner constructs a new extrusion; the compiler rejects applying it to Compose rather than losing existing material features. Disjoint composed perimeter chamfers are supported within their station/corridor limits.
- Imported STEP analysis currently reports millimetres as the qualified public length unit but does not preserve the source unit entity in imported topology metadata. Use millimetre AP242 input for Preview 3 workflows.
- Standard Library material resolution is qualified for Firmament FEA and authored Sheet Metal. Ordinary prismatic CAD STEP export does not yet persist a general solid-material designation; do not infer one from the geometry artifact.
- Cadmata may emit one Three.js `Clock` deprecation warning in the browser developer console. It does not affect loading, navigation, selection, PMI interaction, or model switching.
diff --git a/docs/release/COMPOSED-HOLE-FAMILIES-AND-BRACKET-REHEARSAL.md b/docs/release/COMPOSED-HOLE-FAMILIES-AND-BRACKET-REHEARSAL.md
new file mode 100644
index 00000000..bdf5ae24
--- /dev/null
+++ b/docs/release/COMPOSED-HOLE-FAMILIES-AND-BRACKET-REHEARSAL.md
@@ -0,0 +1,167 @@
+# Composed hole families and local bracket rehearsal
+
+Date: 2026-10-21. Starting revision: `1933f805`.
+
+## Scope and outcome
+
+The bounded production path is a single XY profile-composed part with disjoint
+normal through shaft, counterbore or countersink holes. Countersinks now lower to
+exact conical walls in the existing section-stack planner. Counterbores and
+countersinks resolve their actual local material support; another boss cannot
+move their entries into empty space. Unsupported intent still rejects.
+
+The local rehearsal builds two specifications of one L-bracket Template, using
+two Rect2 guides, a six-edge trace loop and extrusion. It exports STEP AP242,
+GLB and authored PDF/SVG/PPTX drawings. A PDF-only reader independently rebuilds
+both parts using Path construction and compares their actual STEP geometry.
+No demo repository was modified and no hosted Actions run was performed.
+
+Final gate: **Success for the bounded composed-hole family and local rehearsal.**
+General composed-body fillets and the other boundaries below are not claimed as
+implemented.
+
+## Reproductions and repairs
+
+| Finding | Starting behavior | Repair / qualified behavior |
+| --- | --- | --- |
+| Countersink on traced L / Compose | `compose-hole-unsupported-variant-or-end` | Typed circular cavity, exact cone/cylinder walls and circular trims; no Boolean fallback. |
+| Plain composed counterbore | Already worked on constant-height L stock | Retained; full STEP output matches the starting revision byte for byte on the existing witness. |
+| Counterbore beside taller boss, A4 mounting block | Recess operations were placed at the body's global maximum Z, above their local plate. The successful STEP omitted both recesses. | Normalize actual host material before drilling; resolve a contiguous local interval and exposed entry footprint. A4 recesses now enter at Z=12, independently of the Z=18 boss. |
+| Counterbore/countersink on pocket floor | No reliable local support admission | Fit the complete entry disk in the exposed floor. A small floor rejects; a sufficiently large floor admits. |
+| Named base perimeter beside boss | Chamfer planner selected the globally highest slab | Resolve the named Profile's support. Preserve continuing boss material and subtract it from the exposed cap. Reject a corridor intersecting continuing material. |
+| Missing materialized feature walls | Correspondence diagnostic could coexist with an emitted body | The feature owner now rejects a missing shaft, recess or slot wall immediately. |
+| Nearby pockets, slots, cavities | Base-outline checks did not prove the actual cavity corridor | Reuse exact section disk containment throughout the cavity interval; reject collisions, tangencies, disconnected spans and unsupported boundary-distance proofs. |
+| Wrong-variant relief fields | Compose owner could consume irrelevant fields | Use shared schema variant applicability; an inapplicable field cannot disappear. |
+| Normal Compose export evidence | Result could omit its existing runtime body/correspondence | Retain both there, report actual surface counts and correct stack kind. |
+| Shaft diameter PMI | A composed feature's larger recess/cone could join its diameter target | Follow semantic shaft-wall ownership, preserving all shaft patches and their associations. Contradictory values keep their targets for geometry/requirement diagnostics. |
+| GLB PMI for partitioned shaft | Multi-face presentation rejected even one physical shaft | Admit a connected set on one analytic cylinder; highlight every patch and retain every face association. Different axes/supports still reject. |
+| Semicolon PMI fields | Punctuation reached the line/regex value reader | Existing structural parser owns field spans; no new parser route. |
+| `PlusMinus(0.1mm)` in direct PMI | Only the two-argument call was recognized | Structurally read one/two length arguments; retain finite, nonnegative, unit and arity checks. |
+| Authored `Wireframe` | Accepted but mapped to `VisibleOnly` | Preserve the requested enum. Suppress analytic patch seams rather than manufacturing edges in drawing projection. |
+| Six-face display qualification test | A time-bounded partial API sometimes returned five faces under load | Use complete deterministic tessellation for the complete-display assertion; partial-display policy is unchanged. |
+
+## Geometry and ownership
+
+The existing parser owner binds hole declarations into typed composition metadata.
+The section-stack owner proves host/material admission, plans exact walls and
+trims, publishes semantic descendants and materializes one closed body. The
+materializer does not choose a second interpretation. The conical entry's extra
+void volume is integrated analytically. Linear outer chamfer transport uses its
+exact quadratic section-area integral, retaining disjoint cavity volumes.
+
+No new whole-document dispatch, source macro system, field schema, diagnostic
+allowlist or global mutable parser state was added. PMI field parsing removes an
+old regex consumer in favor of existing token spans. New regex use is confined
+to the independent PDF/STEP verification script, not the compiler.
+
+The GLB change is presentation over AP242 associations. It does not move body
+vertices. The authored drawing helper supplies this family's dimensions and
+normal-hole hidden contours through the shared Drawing IR; PDF, SVG and PPTX
+use the same sheet. The automatic drawing recognition family is unchanged.
+
+## Compatibility and intentional correction
+
+An isolated build of the starting revision's Firmament sources was compared
+with the repaired implementation using the same unchanged dependencies.
+
+These five complete STEP artifacts were byte-identical:
+
+1. `profile-compose-l-bracket.firmament`.
+2. `profile-compose-l-bracket-external-modify-counterbore.firmament`.
+3. `profile-compose-reflex-chamfer-with-counterbore.firmament`.
+4. The canonical standalone single-edge fillet.
+5. The canonical primitive counterbore.
+
+The A4 mounting block intentionally changes: its old cylinder inventory contained
+only radius 3 mm; the corrected body also contains the requested radius 5.5 mm
+recesses. Its named base chamfer now acts on that base's support. Preserving the
+old omitted/wrongly placed features would preserve a defect, not source intent.
+The new L countersink is rejected by the reference revision and accepted now.
+No fixture was edited to turn a failing geometry comparison green.
+
+## Rehearsal and drawing evidence
+
+| Specification | Nominal | Resized variant |
+| --- | ---: | ---: |
+| Overall X/Y/Z, mm | 80 / 60 / 12 | 100 / 75 / 15 |
+| Leg widths, mm | 20 / 20 | 25 / 24 |
+| H1 X/Y from O, mm | 60 / 10 | 70 / 12 |
+| Shaft / entry diameter, mm | 6 / 12 | 8 / 14 |
+| Included cone angle | 90° | 90° |
+
+Five controlling dimensions, marked O/X0/Y0, independent coordinate limits,
+through diameter, countersink entry diameter/angle, entry plane A and hole-axis
+orientation define the nominal part. Limits are ±0.1 mm and ±0.5°. The local
+screen covers Cartesian/size limits and axis lean on ideal orthogonal stock;
+machine/process capability, stock form and general angular stacks remain
+unqualified. Checked/approved signoffs are blank.
+
+For each final PDF, the independent reader freezes a fresh Path-based source
+before reading any reference geometry. Both reconstructions match bounds,
+topology counts, all topology vertices, analytic cylinder/cone supports and
+the independently evaluated reference volume. Nine incomplete-document
+mutations reject for each size: missing dimension, origin, coordinate limits,
+hole row, countersink angle limits/value, through extent, axis orientation or
+outline angle definition.
+
+Exact construction volume and numerical trimmed-face mass estimates are reported
+separately. A tessellation estimate is never labeled exact. The final PDFs were
+rendered and visually inspected. AP242/GLB preserve supported datum and shaft-size
+PMI; additional drawing requirements are not claimed as unsupported AP242 records.
+
+## Qualification
+
+Qualified on Windows with .NET SDK 10.0.401, through the real compiler/export path:
+
+| Lane | Result |
+| --- | --- |
+| Release solution build, serial / no shared compilation | Pass, 0 errors |
+| Focused composed-hole, support, drawing and round-trip tests | 91 passed |
+| Fast Core lane (`Category!=SlowCorpus`) | 1,088 passed |
+| Full solution lane, including SlowCorpus | 5,914 passed, 20 test assemblies, 0 failures, 0 skipped |
+| STEP compatibility controls | Five byte-identical outputs |
+| Nominal + resized PDF-only reconstruction | Both pass; nine negative mutations each |
+| Final PDF rendering and inspection | Both sheets inspected |
+| Code-quality / whitespace review | Complete; `git diff --check` passes |
+
+The final code/test/fixture/runner hashes are recorded with the ignored evidence.
+The first full run exposed the real A4 defect and the timing-sensitive display
+assertion; both were repaired and the full gate was rerun successfully. No
+geometry baseline was rewritten. The final complete rerun also covers the last
+chamfer-volume and authored hidden-contour changes.
+
+Builds use `-m:1 -nr:false -p:UseSharedCompilation=false`; test lanes run serially.
+Task-owned reusable MSBuild hosts from an early launcher invocation were reaped.
+Normal qualification hosts exit when their lanes finish; no background service
+or startup hook was created.
+
+Raw evidence defaults to ignored `artifacts/local/compose-hole-rehearsal/`;
+final user artifacts are under `artifacts/local/demos/code-native-bracket/`.
+Automatic approval review blocked recursive deletion of the private comparison
+builds/cache, stating only “blocked by policy.” Those approximately 230 MiB remain
+local. `artifacts/local/compose-hole-rehearsal/Cleanup-ComparisonBuilds.ps1` is a
+reviewable cleanup script; its default invocation only previews verified paths.
+STEP/hash evidence and deliverables are outside its cleanup targets.
+
+Reproduction commands and the runner are documented in
+[the public rehearsal guide](../public/code-native-bracket.md).
+
+## Explicit remaining boundaries
+
+- Composed-body fillets still require an adapter that retains existing material
+ intervals, caps and cavities. The standalone Profile fillet planner constructs
+ a fresh extrusion; removing its Compose guard would lose requested geometry.
+ The rejection now explains this precise coupling. Existing primitive and
+ standalone Profile fillet capabilities remain unchanged.
+- Oriented Compose hole supports, blind counterbore/countersink ends, entry
+ breakouts/tangencies and intersecting cavities are not admitted here.
+- A perimeter-chamfer corridor cannot cross a shaft/recess or shaft/cone station.
+- Exact disk containment remains bounded to line/circular-arc boundaries; an
+ unavailable distance proof rejects instead of treating NaN as “inside.”
+- Compose retains its existing expansion/source-span representation; this pass
+ does not claim a new general expansion source map or complete PMI vocabulary.
+- Generic automatic drawings and general surface-silhouette extraction are not
+ expanded. This is a qualified authored bracket drawing, not a claim that all
+ imported parts can be fully dimensioned automatically.
+- Hosted GitHub Actions qualification is the next deployment/rehearsal boundary.
+ The target demo repository has deliberately remained untouched.
diff --git a/fixtures/Regression/ComposeHoleFamilies/bracket-library.firmament b/fixtures/Regression/ComposeHoleFamilies/bracket-library.firmament
new file mode 100644
index 00000000..e9666733
--- /dev/null
+++ b/fixtures/Regression/ComposeHoleFamilies/bracket-library.firmament
@@ -0,0 +1,47 @@
+// Reusable single-part family. The runner supplies one typed specification.
+Record BracketDimensions {
+ width: Length
+ height: Length
+ legWidth: Length
+ legHeight: Length
+ thickness: Length
+ holeX: Length
+ holeY: Length
+ shaftDiameter: Length
+ entryDiameter: Length
+}
+
+Template<spec: BracketDimensions> Struct BracketTemplate {
+ Require Positive => spec.width > spec.legWidth && spec.height > spec.legHeight && spec.legWidth > 0mm && spec.legHeight > 0mm && spec.thickness > 0mm
+ Concept Struct Layout on XY {
+ Rect2 Horizontal { center: [spec.width / 2, spec.legHeight / 2]; size: [spec.width, spec.legHeight] }
+ Rect2 Vertical { center: [spec.legWidth / 2, spec.height / 2]; size: [spec.legWidth, spec.height] }
+ Point2 Notch { position: [spec.legWidth, spec.legHeight] }
+ }
+ Profile Outline using Layout { Loop Outer {
+ Horizontal.Bottom as South
+ |> Horizontal.Right as East
+ |> Horizontal.Top to Notch as Inner
+ |> Vertical.Right to Vertical.TopRight as Upright
+ |> Vertical.Top as North
+ |> Vertical.Left to Horizontal.BottomLeft as West
+ |> Close
+ } }
+ Compose Body {
+ Base Stock { profile: Outline; from: 0mm; to: spec.thickness; role: Stock }
+ }
+ Modify Body {
+ Hole<Countersink> Mount {
+ on: +Z
+ center: Point2(spec.holeX, spec.holeY)
+ diameter: spec.shaftDiameter
+ countersinkDiameter: spec.entryDiameter
+ countersinkAngle: 90deg
+ end: ThroughAll
+ }
+ }
+ Pmi {
+ Datum A { target: face(+Z) }
+ HoleDiameter ShaftSize { target: Mount; value: spec.shaftDiameter; tolerance: PlusMinus(0.1mm) }
+ }
+}
diff --git a/fixtures/Regression/ComposeHoleFamilies/l-bracket-countersink.firmament b/fixtures/Regression/ComposeHoleFamilies/l-bracket-countersink.firmament
new file mode 100644
index 00000000..2f1b1fed
--- /dev/null
+++ b/fixtures/Regression/ComposeHoleFamilies/l-bracket-countersink.firmament
@@ -0,0 +1,30 @@
+Model ProfileComposeLBracket {
+ Units: mm
+
+ // Two guides deliberately overlap. The named Notch point and the Rect2
+ // corners form a six-segment counter-clockwise L boundary.
+ Concept Struct Layout On XY {
+ Rect2 Horizontal { Center: [0mm, -10mm]; Size: [80mm, 20mm] }
+ Rect2 Vertical { Center: [-30mm, 10mm]; Size: [20mm, 60mm] }
+ Point2 Notch { Position: [-20mm, 0mm] }
+ }
+
+ Profile Bracket Using Layout { Loop Outer {
+ Horizontal.Bottom As South
+ |> Horizontal.Right As East
+ |> Horizontal.Top To Notch As Inner
+ |> Vertical.Right To Vertical.TopRight As Upright
+ |> Vertical.Top As North
+ |> Vertical.Left To Horizontal.BottomLeft As West
+ |> Close
+ } }
+
+ Struct BracketBody {
+ Compose BracketBody {
+ Base Stock { Profile: Bracket; From: 0mm; To: 12mm; Role: Stock }
+ }
+ }
+ Modify BracketBody {
+ Hole<Countersink> Mount { on: +Z; center: Point2(20mm, -10mm); diameter: 6mm; countersinkDiameter: 12mm; countersinkAngle: 90deg; end: ThroughAll }
+ }
+}
diff --git a/fixtures/Regression/ComposeHoleFamilies/reconstruct_bracket_pdf.py b/fixtures/Regression/ComposeHoleFamilies/reconstruct_bracket_pdf.py
new file mode 100644
index 00000000..f6e4c99d
--- /dev/null
+++ b/fixtures/Regression/ComposeHoleFamilies/reconstruct_bracket_pdf.py
@@ -0,0 +1,161 @@
+#!/usr/bin/env python3
+"""Rebuild the authored bracket from PDF text only, then optionally compare STEP.
+
+Bounded drawing convention: five controlling dimensions in printed view order
+(width, height, leg width, leg height, thickness), origin O, and H1's two tables.
+No source, Drawing IR or reference STEP is read until reconstruction is frozen.
+Requires pypdf and the real Aetheris CLI. Does not update any baseline.
+"""
+import argparse
+import hashlib
+import json
+import math
+from pathlib import Path
+import re
+import subprocess
+from pypdf import PdfReader
+
+NUMBER = r"\d+(?:\.\d+)?"
+
+
+def definition(text):
+ sizes = re.findall(rf"(?m)^({NUMBER}) ±({NUMBER})", text)
+ if len(sizes) != 5 or any(float(t) <= 0 for _, t in sizes):
+ raise ValueError("Five controlling dimensions with positive limits are required.")
+ required = ["O (X0, Y0)", "O: lower-left TOP vertex. +X right, +Y up.",
+ "Six straight edges.", "Uniform thickness; hole axis normal to A.",
+ "CSK enters DATUM A (TOP); shaft is THRU.", "ALL DIMENSIONS mm."]
+ if any(value not in text for value in required):
+ raise ValueError("Missing origin, boundary, units, entry or axis/extent definition.")
+ center = re.search(rf"H1 CENTER FROM O / mm\s+ID X ±({NUMBER}) Y ±({NUMBER})\s+H1 ({NUMBER}) ({NUMBER})", text)
+ hole = re.search(rf"H1 COUNTERSUNK THROUGH HOLE\s+THRU Ø ±({NUMBER}) CSK Ø ±({NUMBER}) Angle ±({NUMBER})°\s+({NUMBER}) ({NUMBER}) ({NUMBER})°", text)
+ angles = re.search(rf"Unspecified angles 90° ±({NUMBER})°", text)
+ if not angles or float(angles[1]) <= 0:
+ raise ValueError("The six-edge outline has no right-angle definition/limits.")
+ if not center or not hole:
+ raise ValueError("Missing hole location, size, countersink or limits.")
+ if any(float(v) <= 0 for v in (*center.groups()[:2], *hole.groups()[:3])):
+ raise ValueError("Coordinate, diameter and angle limits must be positive.")
+ w, h, lw, lh, t = [float(v) for v, _ in sizes]
+ x, y = map(float, center.groups()[2:])
+ d, entry, angle = map(float, hole.groups()[3:])
+ if not (0 < lw < w and 0 < lh < h and t > 0 and 0 < d < entry and 0 < angle < 180):
+ raise ValueError("Invalid nominal bracket dimensions.")
+ depth = (entry - d) / (2 * math.tan(math.radians(angle / 2)))
+ if depth >= t:
+ raise ValueError("No positive cylindrical shaft remains.")
+ return dict(width=w, height=h, legWidth=lw, legHeight=lh, thickness=t, holeX=x, holeY=y,
+ shaftDiameter=d, entryDiameter=entry, includedAngle=angle,
+ linearLimits=[float(limit) for _, limit in sizes],
+ centerLimits=list(map(float, center.groups()[:2])), holeLimits=list(map(float, hole.groups()[:3])),
+ generalAngle=90, generalAngleTolerance=float(angles[1]))
+
+
+def reconstruct(p):
+ # An independent Path construction, not the original pair of Rect2 guides.
+ w, h, lw, lh, t, x, y, d, e, a = (p[k] for k in (
+ 'width', 'height', 'legWidth', 'legHeight', 'thickness', 'holeX', 'holeY', 'shaftDiameter', 'entryDiameter', 'includedAngle'))
+ return f"""// Independently reconstructed from the visible PDF only.
+Model ReconstructedBracket {{
+ units: mm
+ Path Boundary {{
+ start: Point2(0mm, 0mm); heading: 0deg
+ Line South {{ length: {w}mm }}
+ Line East {{ turn: 90deg; length: {lh}mm }}
+ Line Inner {{ turn: 90deg; length: {w-lw}mm }}
+ Line Upright {{ turn: -90deg; length: {h-lh}mm }}
+ Line North {{ turn: 90deg; length: {lw}mm }}
+ Close West
+ }}
+ Profile Outline from Boundary
+ Struct Part {{ Compose Body {{ Base Stock {{ profile: Outline; from: 0mm; to: {t}mm }} }} }}
+ Modify Body {{ Hole<Countersink> H1 {{
+ on: +Z; center: Point2({x}mm, {y}mm); diameter: {d}mm
+ countersinkDiameter: {e}mm; countersinkAngle: {a}deg; end: ThroughAll
+ }} }}
+}}
+"""
+
+
+def geometry(path):
+ """Independent canonical STEP witness: topology vertices and analytic supports."""
+ entities = dict((int(i), v) for i, v in re.findall(r"(?m)^#(\d+)=(.*);\s*$", path.read_text(encoding='utf-8')))
+ def ref(value): return [int(v) for v in re.findall(r'#(\d+)', value)]
+ def vector(value): return [float(v) for v in value[value.rfind('(') + 1:].rstrip(')').split(',')]
+ def placement(value):
+ p, z, x = ref(entities[ref(value)[0]])
+ return vector(entities[p]), vector(entities[z]), vector(entities[x])
+ vertices = sorted(vector(entities[ref(v)[0]]) for v in entities.values() if v.startswith('VERTEX_POINT('))
+ supports = []
+ for v in entities.values():
+ kind = v.partition('(')[0]
+ if kind not in ('CYLINDRICAL_SURFACE', 'CONICAL_SURFACE'):
+ continue
+ station, axis, _ = placement(v)
+ measures = [float(n) for n in v.rstrip(')').split(',')[2:]]
+ supports.append([kind, station, axis, measures])
+ return dict(vertices=vertices, supports=sorted(supports))
+
+
+def close(a, b):
+ if isinstance(a, (list, tuple)):
+ return len(a) == len(b) and all(close(x, y) for x, y in zip(a, b))
+ if isinstance(a, dict): return a.keys() == b.keys() and all(close(a[k], b[k]) for k in a)
+ return abs(a-b) <= 1e-8 if isinstance(a, (float, int)) else a == b
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--pdf', type=Path, required=True)
+ parser.add_argument('--out-dir', type=Path, required=True)
+ parser.add_argument('--cli', type=Path, required=True)
+ parser.add_argument('--reference-step', type=Path)
+ args = parser.parse_args()
+ text = '\n'.join(page.extract_text() for page in PdfReader(args.pdf).pages)
+ p = definition(text)
+ mutants = {
+ 'missing_size': re.sub(rf'(?m)^{NUMBER} ±{NUMBER}', '', text, count=1),
+ 'missing_origin': text.replace('O (X0, Y0)', ''),
+ 'missing_coordinate_limits': text.replace('X ±0.1', 'X'),
+ 'missing_hole_row': re.sub(rf'(?m)^H1 {NUMBER} {NUMBER}', '', text),
+ 'missing_countersink_angle': text.replace('Angle ±0.5°', 'Angle'),
+ 'missing_through_extent': text.replace('shaft is THRU.', 'shaft.'),
+ 'missing_axis_orientation': text.replace('hole axis normal to A.', 'hole.'),
+ 'missing_outline_angles': text.replace('Unspecified angles 90° ±0.5°.', ''),
+ 'missing_cone_angle_value': re.sub(rf'(?m)^({NUMBER} {NUMBER}) 90°', r'\1', text)
+ }
+ for name, mutant in mutants.items():
+ try: definition(mutant)
+ except ValueError: continue
+ raise AssertionError('Incomplete PDF was accepted: ' + name)
+ args.out_dir.mkdir(parents=True, exist_ok=True)
+ source = args.out_dir / 'reconstructed.firmament'
+ source.write_text(reconstruct(p), encoding='utf-8', newline='')
+ frozen_hash = hashlib.sha256(source.read_bytes()).hexdigest()
+ result = {'pdfOnlyDefinition': p, 'negativeCasesRejected': list(mutants), 'reconstructionSha256': frozen_hash}
+ (args.out_dir / 'pdf-definition.json').write_text(json.dumps(result, indent=2), encoding='utf-8')
+ cli = ['dotnet', str(args.cli.resolve())] if args.cli.suffix == '.dll' else [str(args.cli.resolve())]
+ def run(*arguments):
+ process = subprocess.run(cli + list(map(str, arguments)), capture_output=True, text=True, encoding='utf-8')
+ if process.returncode: raise RuntimeError(process.stdout + process.stderr)
+ return json.loads(process.stdout)
+ rebuilt = args.out_dir / 'reconstructed.step'
+ run('build', source, '--out', rebuilt, '--json')
+ if args.reference_step:
+ # Original geometry is intentionally read only after the PDF source was frozen.
+ expected = run('inspect', args.reference_step, '--json')['summary']
+ actual = run('inspect', rebuilt, '--json')['summary']
+ for key in ('bodyCount', 'shellCount', 'faceCount', 'edgeCount', 'vertexCount', 'surfaceFamilies', 'boundingBox'):
+ assert close(expected[key], actual[key]), (key, expected[key], actual[key])
+ assert close(geometry(args.reference_step), geometry(rebuilt)), 'STEP vertices or analytic cylinder/cone supports differ.'
+ ma = run('verify', args.reference_step, '--json', '--evidence-dir', args.out_dir / 'reference-verification')['brepMassProperties']
+ mb = run('verify', rebuilt, '--json', '--evidence-dir', args.out_dir / 'rebuilt-verification')['brepMassProperties']
+ assert abs(ma['absoluteVolume'] - mb['absoluteVolume']) <= 1e-8
+ assert hashlib.sha256(source.read_bytes()).hexdigest() == frozen_hash
+ result.update(referenceReadAfterFreeze=True, matchingGeometry=True, referenceVolume=ma['absoluteVolume'], rebuiltVolume=mb['absoluteVolume'])
+ (args.out_dir / 'pdf-qualification.json').write_text(json.dumps(result, indent=2), encoding='utf-8')
+ print(json.dumps(result, indent=2))
+
+
+if __name__ == '__main__':
+ main()