Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add ClosedBoundary2 authoring and CLI inspection
Yuechen Li7d0394b47b0a
diff --git a/Aetheris.CLI.Tests/NamedSetCliTests.cs b/Aetheris.CLI.Tests/NamedSetCliTests.csindex c2092569..df432549 100644--- a/Aetheris.CLI.Tests/NamedSetCliTests.cs+++ b/Aetheris.CLI.Tests/NamedSetCliTests.cs@@ -37,6 +37,23 @@ public sealed class NamedSetCliTestsAssert.Contains("firmament-feature-footprint-outside-span:Mounts.UpperRight:MountingArea", stdout.ToString(), StringComparison.Ordinal);}+ [Fact]+ public void Inspect_ReportsClosedBoundaryFamilyAndStableGuides()+ {+ var stdout = new StringWriter(); var stderr = new StringWriter();+ var exit = Aetheris.CLI.CliRunner.Run(["inspect", Fixture("Canonical", "Boundary2", "closed-boundary-family.firmament"), "--json"], stdout, stderr);+ Assert.Equal(0, exit); Assert.Equal(string.Empty, stderr.ToString());+ using var json = JsonDocument.Parse(stdout.ToString());+ var boundaries = json.RootElement.GetProperty("boundaries").EnumerateArray().ToArray();+ Assert.Equal(15, boundaries.Length);+ Assert.All(boundaries, x => Assert.Equal("ClosedBoundary2", x.GetProperty("capability").GetString()));+ var rounded = boundaries.Single(x => x.GetProperty("shapeId").GetString() == "MountingRegion");+ Assert.Equal("RoundedRect2", rounded.GetProperty("shapeType").GetString());+ Assert.Contains("TopRightCorner", rounded.GetProperty("generatedGuides").EnumerateArray().Select(x => x.GetString()));+ var hex = boundaries.Single(x => x.GetProperty("shapeId").GetString() == "Hex");+ Assert.Equal(6d, hex.GetProperty("dimensions").GetProperty("VertexCount").GetDouble());+ }+private static string Fixture(params string[] parts) =>Path.GetFullPath(Path.Combine([AppContext.BaseDirectory, "../../../../fixtures", .. parts]));}diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 33ccb004..837c3b56 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -1497,6 +1497,21 @@ Model CanonicalPanel {polygon.GeneratedEdges,polygon.SourceSpan}).ToArray() ?? [],+ boundaries = document?.Boundaries?.Select(boundary => new+ {+ shapeId = boundary.Name,+ boundary.ShapeType,+ boundary.Variant,+ boundary.Capability,+ center = new[] { boundary.CenterX, boundary.CenterY },+ rotationDegrees = boundary.RotationDegrees,+ boundary.Dimensions,+ area = boundary.Area,+ perimeter = boundary.Perimeter,+ generatedGuides = boundary.GeneratedPoints.Concat(boundary.GeneratedEdges),+ exactCarrier = boundary.ExactCarrier,+ provenance = boundary.SourceSpan+ }).ToArray() ?? [],patterns = document?.StaticAuthoring?.Patterns?.Select(pattern => new{pattern.Name,diff --git a/Aetheris.Kernel.Firmament.Tests/ClosedBoundary2X1Tests.cs b/Aetheris.Kernel.Firmament.Tests/ClosedBoundary2X1Tests.csnew file mode 100644index 00000000..01d4ea62--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/ClosedBoundary2X1Tests.cs@@ -0,0 +1,179 @@+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.Materializer;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class ClosedBoundary2X1Tests+{+ public static TheoryData<string, string, int> LinearFamilies => new()+ {+ { "Rect2 Shape { Center: [0mm,0mm] Size: [40mm,20mm] }", "Rect2", 4 },+ { "Square2 Shape { Center: [0mm,0mm] Size: 20mm }", "Square2", 4 },+ { "Triangle2<Equilateral> Shape { Center: [0mm,0mm] Side: 20mm }", "Triangle2", 3 },+ { "Triangle2<Isosceles> Shape { Center: [0mm,0mm] Base: 20mm Height: 15mm }", "Triangle2", 3 },+ { "Triangle2<Right> Shape { Origin: [0mm,0mm] Legs: [20mm,15mm] }", "Triangle2", 3 },+ { "Triangle2<Explicit> Shape { A: [0mm,0mm] B: [20mm,0mm] C: [0mm,15mm] }", "Triangle2", 3 },+ { "RegularPolygon2<6> Shape { Center: [0mm,0mm] AcrossFlats: 32mm Rotation: 30deg }", "RegularPolygon2", 6 },+ { "Polygon2<Parallelogram> Shape { Center: [0mm,0mm] Base: 30mm Height: 20mm Shear: 8mm }", "Polygon2", 4 },+ { "Polygon2<Trapezoid> Shape { Center: [0mm,0mm] BottomWidth: 30mm TopWidth: 20mm Height: 15mm }", "Polygon2", 4 },+ };++ [Theory]+ [MemberData(nameof(LinearFamilies))]+ public void LinearFamilies_BindThroughTraceLoopWithStableMetadata(string shape, string type, int segments)+ {+ var source = Source(shape);+ var parse = FirmamentV2Parser.Parse(source);+ var profile = ProfileAuthoringParser.ResolveNamedProfile(source, "Boundary", out var diagnostics);++ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));+ var boundary = Assert.Single(parse.Document!.Boundaries!);+ Assert.Equal("ClosedBoundary2", boundary.Capability);+ Assert.Equal(type, boundary.ShapeType);+ Assert.True(boundary.Area > 0);+ Assert.True(boundary.Perimeter > 0);+ Assert.NotEmpty(boundary.GeneratedEdges);+ Assert.NotNull(profile);+ Assert.Empty(diagnostics);+ Assert.Equal(segments, profile.Loops.Single().Segments.Count);+ }++ [Theory]+ [InlineData("Slot2 Shape { Center: [0mm,0mm] Length: 50mm Width: 12mm }", 4)]+ [InlineData("RoundedRect2 Shape { Center: [0mm,0mm] Size: [50mm,30mm] Radius: 6mm }", 8)]+ public void LineArcFamilies_PreserveExactCircularSpans(string shape, int segments)+ {+ var source = Source(shape); var profile = ProfileAuthoringParser.ResolveNamedProfile(source, "Boundary", out var diagnostics);+ Assert.NotNull(profile); Assert.Empty(diagnostics); Assert.Equal(segments, profile.Loops.Single().Segments.Count);+ Assert.Contains(profile.Loops.Single().Segments, x => x.Geometry is LineArcCircularArc2D);+ var export = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(export.IsSuccess, string.Join(Environment.NewLine, export.Diagnostics.Select(x => x.Message)));+ Assert.Contains("CIRCLE", export.Value.StepText, StringComparison.Ordinal);+ }++ [Fact]+ public void CircleAndEllipse_AreSingleAnalyticBoundariesAndExportAnalytically()+ {+ var circleSource = Source("Circle2 Shape { Center: [0mm,0mm] Diameter: 20mm }");+ var ellipseSource = Source("Ellipse2 Shape { Center: [0mm,0mm] AxisLengths: [40mm,20mm] Rotation: 15deg }");+ var circle = ProfileAuthoringParser.ResolveNamedProfile(circleSource, "Boundary", out var circleDiagnostics);+ var ellipse = ProfileAuthoringParser.ResolveNamedProfile(ellipseSource, "Boundary", out var ellipseDiagnostics);+ Assert.Empty(circleDiagnostics); Assert.Empty(ellipseDiagnostics);+ Assert.IsType<LineArcFullCircle2D>(Assert.Single(circle!.Loops.Single().Segments).Geometry);+ Assert.IsType<LineArcFullEllipse2D>(Assert.Single(ellipse!.Loops.Single().Segments).Geometry);+ var circleExport = FirmamentBuildAndExport.CompileSource(circleSource);+ var ellipseExport = FirmamentBuildAndExport.CompileSource(ellipseSource);+ Assert.True(circleExport.IsSuccess, string.Join(Environment.NewLine, circleExport.Diagnostics.Select(x => x.Message)));+ Assert.True(ellipseExport.IsSuccess, string.Join(Environment.NewLine, ellipseExport.Diagnostics.Select(x => x.Message)));+ Assert.Contains("CIRCLE", circleExport.Value.StepText, StringComparison.Ordinal);+ Assert.Contains("ELLIPSE", ellipseExport.Value.StepText, StringComparison.Ordinal);+ Assert.Contains("SURFACE_OF_LINEAR_EXTRUSION", ellipseExport.Value.StepText, StringComparison.Ordinal);+ var reimport = Step242Importer.ImportBody(ellipseExport.Value.StepText);+ Assert.True(reimport.IsSuccess, string.Join(Environment.NewLine, reimport.Diagnostics.Select(x => x.Message)));+ Assert.Contains(reimport.Value.Geometry.Curves, x => x.Value.Kind == CurveGeometryKind.Ellipse3);+ }++ [Fact]+ public void ExplicitPolygon_PreservesSetNamesAndRejectsSelfIntersection()+ {+ const string set = "Static Vertices: Set<Point2> { A => Point2(0mm,0mm) B => Point2(30mm,0mm) Nose => Point2(35mm,12mm) C => Point2(20mm,25mm) D => Point2(0mm,18mm) }";+ var source = Source(set + " Polygon2<Explicit> Shape { Vertices: Vertices }");+ var parse = FirmamentV2Parser.Parse(source); var boundary = Assert.Single(parse.Document!.Boundaries!);+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));+ Assert.Equal(["A", "B", "Nose", "C", "D"], boundary.GeneratedPoints);+ Assert.Equal(["A_B", "B_Nose", "Nose_C", "C_D", "D_A"], boundary.GeneratedEdges);++ var invalid = FirmamentV2Parser.Parse(Source("Static V: Set<Point2> { A => Point2(0mm,0mm) B => Point2(10mm,10mm) C => Point2(0mm,10mm) D => Point2(10mm,0mm) } Polygon2<Explicit> Shape { Vertices: V }"));+ Assert.False(invalid.IsSuccess);+ Assert.Contains("firmament-boundary2-explicit-self-intersection:Shape", invalid.Diagnostics);+ }++ [Fact]+ public void ThreeFamilies_AuthorPlaneSpanBoundariesWithoutShapeSpecificBackend()+ {+ var source = """+ Concept Struct Supports { Top: Plane { Origin: [0mm,0mm,0mm] Normal: [0,0,1] Up: [0,1,0] } }+ Construction Plane TopSupport { Trace: Supports.Top }+ RoundedRect2 Rounded { Center: [0mm,0mm] Size: [60mm,40mm] Radius: 8mm }+ Circle2 Disk { Center: [0mm,0mm] Diameter: 30mm }+ RegularPolygon2<6> Hex { Center: [0mm,0mm] AcrossFlats: 32mm }+ Profile RoundedProfile { Loop Outer { Rounded |> TraceLoop } }+ Profile DiskProfile { Loop Outer { Disk |> TraceLoop } }+ Profile HexProfile { Loop Outer { Hex |> TraceLoop } }+ Span<Plane> RoundedArea { On: TopSupport Boundary: RoundedProfile }+ Span<Plane> DiskArea { On: TopSupport Boundary: DiskProfile }+ Span<Plane> HexArea { On: TopSupport Boundary: HexProfile }+ """;+ var inspection = ProfileAuthoringParser.InspectGeometricSpans(source);+ Assert.Empty(inspection.Diagnostics);+ Assert.Equal(["RoundedProfile", "DiskProfile", "HexProfile"], inspection.Spans.Select(x => x.BoundaryProfile));+ }++ [Fact]+ public void RoundedRectanglePlaneSpan_UsesCurvedCornerForPatternContainment()+ {+ var valid = FirmamentBuildAndExport.CompileSource(RoundedPattern((35, 17)));+ var invalid = FirmamentBuildAndExport.CompileSource(RoundedPattern((39, 21)));+ Assert.True(valid.IsSuccess, string.Join(Environment.NewLine, valid.Diagnostics.Select(x => x.Message)));+ Assert.False(invalid.IsSuccess);+ Assert.Contains(invalid.Diagnostics, x => x.Message.StartsWith("firmament-feature-footprint-outside-span:Mounts.NearCorner:MountingArea", StringComparison.Ordinal));+ }++ [Theory]+ [InlineData("Rect2 Shape { Center: [0mm,0mm] Size: [-1mm,2mm] }", "firmament-boundary2-invalid-dimensions:Shape")]+ [InlineData("Square2 Shape { Center: [0mm,0mm] Size: 0mm }", "firmament-boundary2-invalid-dimensions:Shape")]+ [InlineData("Slot2 Shape { Center: [0mm,0mm] Length: 10mm Width: 12mm }", "firmament-boundary2-invalid-dimensions:Shape")]+ [InlineData("RoundedRect2 Shape { Center: [0mm,0mm] Size: [20mm,10mm] Radius: 6mm }", "firmament-boundary2-invalid-dimensions:Shape")]+ [InlineData("RegularPolygon2<2> Shape { Center: [0mm,0mm] Circumradius: 10mm }", "firmament-boundary2-regular-count-out-of-range:Shape")]+ public void InvalidFamilies_ReportTypedDiagnostics(string shape, string diagnostic)+ {+ var parse = FirmamentV2Parser.Parse(Source(shape));+ Assert.False(parse.IsSuccess); Assert.Contains(diagnostic, parse.Diagnostics);+ }++ [Theory]+ [InlineData("rect-negative-size.firmament")]+ [InlineData("square-zero-size.firmament")]+ [InlineData("triangle-degenerate.firmament")]+ [InlineData("slot-impossible.firmament")]+ [InlineData("rounded-radius-too-large.firmament")]+ [InlineData("explicit-too-few.firmament")]+ [InlineData("explicit-duplicate.firmament")]+ [InlineData("explicit-self-intersection.firmament")]+ [InlineData("regular-count-too-small.firmament")]+ [InlineData("regular-invalid-size.firmament")]+ public void InvalidFixtures_AreRecognizedAndRejected(string file)+ {+ var path = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../fixtures/Invalid/Boundary2", file));+ var parse = FirmamentV2Parser.Parse(File.ReadAllText(path));+ Assert.False(parse.IsSuccess);+ Assert.Contains(parse.Diagnostics, x => x.StartsWith("firmament-boundary2-", StringComparison.Ordinal));+ }++ private static string Source(string declarations) => $$"""+ Model BoundaryFamily {+ Units: mm+ {{declarations}}+ Profile Boundary { Loop Outer { Shape |> TraceLoop } }+ Struct Part { Extrude Solid { Profile: Boundary From: 0mm To: 5mm } }+ }+ """;++ private static string RoundedPattern((double X, double Y) nearCorner) => $$"""+ Model RoundedPattern {+ Units: mm+ Feature Drill(Center: Point2) -> Hole<Shaft> { return Hole<Shaft> { On: MountingArea Center: Center Diameter: 2mm End: ThroughAll } }+ Static Points: Set<Point2> { Center => Point2(0mm,0mm) NearCorner => Point2({{nearCorner.X}}mm,{{nearCorner.Y}}mm) }+ Concept Struct Supports { Top: Plane { Origin: [0mm,0mm,5mm] Normal: [0,0,1] Up: [0,1,0] } }+ Construction Plane TopSupport { Trace: Supports.Top }+ Rect2 Stock { Center: [0mm,0mm] Size: [100mm,70mm] }+ RoundedRect2 Region { Center: [0mm,0mm] Size: [80mm,44mm] Radius: 8mm }+ Profile StockProfile { Loop Outer { Stock |> TraceLoop } }+ Profile RegionProfile { Loop Outer { Region |> TraceLoop } }+ Span<Plane> MountingArea { On: TopSupport Boundary: RegionProfile }+ Struct Part { Compose Plate { Base StockBody { Profile: StockProfile From: 0mm To: 5mm Role: Stock } Pattern Mounts Over Points { point => Drill(Center: point) } } }+ }+ """;+}diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2NamedSetTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2NamedSetTests.csindex f06854c2..5b952bcf 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentV2NamedSetTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2NamedSetTests.cs@@ -112,7 +112,7 @@ public sealed class FirmamentV2NamedSetTests{var source = File.ReadAllText(Fixture("Canonical", "Set", "mounting-points.firmament"));var expansionDiagnostics = new List<string>();- var expansion = Polygon2RhombusAuthoring.Expand(source, expansionDiagnostics);+ var expansion = ClosedBoundary2Authoring.Expand(source, expansionDiagnostics);Assert.NotNull(expansion);var featureExpansion = FirmamentV2FeatureExpansion.Expand(expansion.Source, expansionDiagnostics);Assert.NotNull(featureExpansion);diff --git a/Aetheris.Kernel.Firmament.Tests/ProfilePipelineX1Tests.cs b/Aetheris.Kernel.Firmament.Tests/ProfilePipelineX1Tests.csindex 6c9119d7..3ba666f1 100644--- a/Aetheris.Kernel.Firmament.Tests/ProfilePipelineX1Tests.cs+++ b/Aetheris.Kernel.Firmament.Tests/ProfilePipelineX1Tests.cs@@ -175,7 +175,6 @@ public sealed class ProfilePipelineX1Tests[InlineData("Stock.Bottom |> Stock.Top |> Close", "firmament-profile-pipeline-disconnected:Stock.Top")][InlineData("Stock.Bottom |> Stock.Right |> Stock.Top |> Stock.Left |> Stock.Bottom |> Close", "firmament-profile-pipeline-identity-collision:Bottom")][InlineData("Stock.Bottom |> Material |> Close", "firmament-pipeline-stage-type:Material")]- [InlineData("Stock |> TraceLoop", "firmament-profile-traceloop-not-loop:Stock")][InlineData("Stock.Bottom |> Stock.Right |> Close", "firmament-pipeline-close-open:Outer")]public void InvalidPipeline_ReportsTypedDiagnostic(string expression, string expected){diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex e20d95c6..b3835443 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -281,7 +281,13 @@ public static class FirmamentBuildAndExport// parser admission alone is insufficient because the profile/composition// materializers read source declarations directly.var staticDiagnostics = new List<string>();- var featureExpansion = FirmamentV2FeatureExpansion.Expand(sourceText, staticDiagnostics);+ var boundaryExpansion = ClosedBoundary2Authoring.Expand(sourceText, staticDiagnostics);+ if (boundaryExpansion is null)+ {+ return KernelResult<FirmamentStepExportResult>.Failure(staticDiagnostics.Select(diagnostic => new Kernel.Core.Diagnostics.KernelDiagnostic(+ Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, diagnostic, "FirmamentV2.ClosedBoundary2")).ToArray());+ }+ var featureExpansion = FirmamentV2FeatureExpansion.Expand(boundaryExpansion.Source, staticDiagnostics);if (featureExpansion is null){return KernelResult<FirmamentStepExportResult>.Failure(staticDiagnostics.Select(diagnostic => new Kernel.Core.Diagnostics.KernelDiagnostic(diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalSymbolTable.cs b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalSymbolTable.csindex 54e6084b..c31a83a9 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalSymbolTable.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalSymbolTable.cs@@ -11,6 +11,7 @@ public enum FirmamentV2CanonicalSymbolKindStaticArray,StaticSet,Polygon2,+ ClosedBoundary2,Template,Pattern,Require,@@ -99,6 +100,7 @@ internal static class FirmamentV2CanonicalSymbolBinderforeach (var profile in document.Profiles ?? []) Add(profile.Name, FirmamentV2CanonicalSymbolKind.Profile, profile.SourceSpan);foreach (var polygon in document.Polygons ?? []) Add(polygon.Name, FirmamentV2CanonicalSymbolKind.Polygon2, polygon.SourceSpan);+ foreach (var boundary in (document.Boundaries ?? []).Where(x => x.ShapeType != "Polygon2")) Add(boundary.Name, FirmamentV2CanonicalSymbolKind.ClosedBoundary2, boundary.SourceSpan);foreach (var compose in document.Composes ?? []) Add(compose.Name, FirmamentV2CanonicalSymbolKind.Compose, compose.SourceSpan);foreach (var boss in document.Bosses ?? []) Add(boss.Name, FirmamentV2CanonicalSymbolKind.Boss, boss.SourceSpan);foreach (var pocket in document.Pockets ?? []) Add(pocket.Name, FirmamentV2CanonicalSymbolKind.Pocket, pocket.SourceSpan);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.csnew file mode 100644index 00000000..72308877--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs@@ -0,0 +1,240 @@+using System.Globalization;+using System.Text;+using System.Text.RegularExpressions;++namespace Aetheris.Kernel.Firmament.FirmamentV2;++/// <summary>+/// Bounded lowering for Firmament's canonical ClosedBoundary2 family. Declarations remain+/// inspectable semantic facts while geometry is erased to the existing Profile frontend.+/// </summary>+internal static class ClosedBoundary2Authoring+{+ internal const string Prefix = "firmament-boundary2-";+ private const double Tol = 1e-9;+ private static readonly Regex Header = new(+ @"\b(?:(?<plain>Rect2|Square2|Circle2|Ellipse2|Slot2|RoundedRect2)|(?<family>Triangle2|Polygon2)\s*<\s*(?<variant>[A-Za-z_]\w*)\s*>|RegularPolygon2\s*<\s*(?<count>[-+]?\d+)\s*>)\s+(?<name>[A-Za-z_]\w*)\s*\{",+ RegexOptions.CultureInvariant);++ internal sealed record Result(string Source, IReadOnlyList<FirmamentV2ClosedBoundary2Decl> Boundaries)+ {+ public IReadOnlyList<FirmamentV2Polygon2Decl> Polygons => Boundaries.Where(x => x.ShapeType == "Polygon2")+ .Select(x => new FirmamentV2Polygon2Decl(x.Name, x.Variant!, x.CenterX, x.CenterY,+ x.Dimensions.GetValueOrDefault("DiagonalX"), x.Dimensions.GetValueOrDefault("DiagonalY"),+ x.GeneratedPoints, x.GeneratedEdges, x.SourceSpan)).ToArray();+ }++ private sealed record Shape(FirmamentV2ClosedBoundary2Decl Declaration, string? LoweredSource,+ IReadOnlyDictionary<string, string> MemberMap, string TraceExpression, int Start, int Length);++ public static Result? Expand(string source, List<string> diagnostics)+ {+ var shapes = new List<Shape>(); var names = new HashSet<string>(StringComparer.Ordinal);+ foreach (Match header in Header.Matches(source))+ {+ var open = source.IndexOf('{', header.Index); var close = Matching(source, open); var name = header.Groups["name"].Value;+ if (close < 0) { diagnostics.Add(Prefix + "malformed:" + name); continue; }+ if (!names.Add(name)) { diagnostics.Add(Prefix + "duplicate-name:" + name); continue; }+ var shape = Bind(source, header, source[(open + 1)..close], close, diagnostics);+ if (shape is not null) shapes.Add(shape);+ }+ if (diagnostics.Any(x => x.StartsWith(Prefix, StringComparison.Ordinal) || x.StartsWith("firmament-polygon2-", StringComparison.Ordinal))) return null;+ var changes = new List<(int Start, int Length, string Text)>();+ foreach (var shape in shapes)+ {+ if (shape.LoweredSource is not null) changes.Add((shape.Start, shape.Length, shape.LoweredSource));+ foreach (Match trace in Regex.Matches(source, $@"\b{Regex.Escape(shape.Declaration.Name)}\s*\|>\s*TraceLoop\b", RegexOptions.CultureInvariant))+ if (!Inside(trace.Index, shapes)) changes.Add((trace.Index, trace.Length, shape.TraceExpression));+ foreach (var member in shape.MemberMap)+ foreach (Match reference in Regex.Matches(source, $@"\b{Regex.Escape(shape.Declaration.Name)}\s*\.\s*{Regex.Escape(member.Key)}\b", RegexOptions.CultureInvariant))+ if (!Inside(reference.Index, shapes)) changes.Add((reference.Index, reference.Length, member.Value));+ }+ foreach (var change in changes.OrderByDescending(x => x.Start)) source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);+ return new(source, shapes.Select(x => x.Declaration).ToArray());+ }++ private static Shape? Bind(string source, Match header, string body, int close, List<string> diagnostics)+ {+ var name = header.Groups["name"].Value;+ var type = header.Groups["plain"].Success ? header.Groups["plain"].Value : header.Groups["family"].Success ? header.Groups["family"].Value : "RegularPolygon2";+ var variant = header.Groups["variant"].Success ? header.Groups["variant"].Value : header.Groups["count"].Success ? header.Groups["count"].Value : null;+ var rotation = Angle(body, "Rotation", 0d, out var rotationOk); if (!rotationOk) return Invalid(name, "invalid-rotation", diagnostics);+ var span = new FirmamentV2SourceSpan(header.Index, close - header.Index + 1);+ if (type == "Rect2")+ {+ if (!Point(body, "Center", out var c) || !Vector(body, "Size", out var size)) return null; // legacy/template Rect2 is bound after static specialization+ if (!Positive(size.X, size.Y)) return Invalid(name, "invalid-dimensions", diagnostics);+ return Math.Abs(rotation) <= Tol ? ExistingRect(name, c, size.X, size.Y, span)+ : Linear(name, type, null, c, rotation, Rectangle(c, size.X, size.Y, rotation), ["BottomLeft", "BottomRight", "TopRight", "TopLeft"], ["Bottom", "Right", "Top", "Left"], span, new Dictionary<string, double> { ["Width"] = size.X, ["Height"] = size.Y });+ }+ if (type == "Square2")+ {+ if (!Point(body, "Center", out var c) || !Length(body, "Size", out var size) || size <= 0) return Invalid(name, "invalid-dimensions", diagnostics);+ return Linear(name, type, null, c, rotation, Rectangle(c, size, size, rotation), ["BottomLeft", "BottomRight", "TopRight", "TopLeft"], ["Bottom", "Right", "Top", "Left"], span, new Dictionary<string, double> { ["Size"] = size });+ }+ return type switch+ {+ "Triangle2" => Triangle(name, variant!, body, rotation, span, diagnostics),+ "Circle2" => Circle(source, name, body, rotation, span, diagnostics),+ "Ellipse2" => Ellipse(name, body, rotation, span, diagnostics),+ "Slot2" => Slot(name, body, rotation, span, diagnostics),+ "RoundedRect2" => RoundedRect(name, body, rotation, span, diagnostics),+ "Polygon2" => Polygon(source, name, variant!, body, rotation, span, diagnostics),+ _ => RegularPolygon(name, variant!, body, rotation, span, diagnostics)+ };+ }++ private static Shape ExistingRect(string name, (double X, double Y) c, double w, double h, FirmamentV2SourceSpan span)+ {+ var points = new[] { "BottomLeft", "BottomRight", "TopRight", "TopLeft" }; var edges = new[] { "Bottom", "Right", "Top", "Left" };+ var map = points.Concat(edges).ToDictionary(x => x, x => name + "." + x, StringComparer.Ordinal);+ return Make(name, "Rect2", null, c, 0, new Dictionary<string, double> { ["Width"] = w, ["Height"] = h }, points, edges, "Line", span, null, map, string.Join(" |> ", edges.Select(x => name + "." + x)) + " |> Close", w * h, 2 * (w + h));+ }++ private static Shape? Triangle(string name, string variant, string body, double rotation, FirmamentV2SourceSpan span, List<string> diagnostics)+ {+ (double X, double Y) c; IReadOnlyList<(double X, double Y)> vertices; var dimensions = new Dictionary<string, double>();+ switch (variant)+ {+ case "Equilateral":+ if (!Point(body, "Center", out c) || !Length(body, "Side", out var side) || side <= 0) return Invalid(name, "invalid-dimensions", diagnostics);+ var h = side * Math.Sqrt(3) / 2; vertices = [Rotate((c.X, c.Y + 2 * h / 3), c, rotation), Rotate((c.X - side / 2, c.Y - h / 3), c, rotation), Rotate((c.X + side / 2, c.Y - h / 3), c, rotation)]; dimensions["Side"] = side; break;+ case "Isosceles":+ if (!Point(body, "Center", out c) || !Length(body, "Base", out var b) || !Length(body, "Height", out var ih) || !Positive(b, ih)) return Invalid(name, "invalid-dimensions", diagnostics);+ vertices = [Rotate((c.X, c.Y + 2 * ih / 3), c, rotation), Rotate((c.X - b / 2, c.Y - ih / 3), c, rotation), Rotate((c.X + b / 2, c.Y - ih / 3), c, rotation)]; dimensions["Base"] = b; dimensions["Height"] = ih; break;+ case "Right":+ if (!Point(body, "Origin", out c) || !Vector(body, "Legs", out var legs) || !Positive(legs.X, legs.Y)) return Invalid(name, "invalid-dimensions", diagnostics);+ vertices = [c, Rotate((c.X + legs.X, c.Y), c, rotation), Rotate((c.X, c.Y + legs.Y), c, rotation)]; dimensions["LegX"] = legs.X; dimensions["LegY"] = legs.Y; break;+ case "Explicit":+ if (!Point(body, "A", out var a) || !Point(body, "B", out var bb) || !Point(body, "C", out var cc)) return Invalid(name, "invalid-dimensions", diagnostics);+ vertices = [a, bb, cc]; c = Centroid(vertices); rotation = 0; break;+ default: diagnostics.Add(Prefix + "variant-unsupported:" + name + ":" + variant); return null;+ }+ if (Math.Abs(SignedArea(vertices)) <= Tol || HasDuplicate(vertices)) return Invalid(name, "degenerate:" + variant, diagnostics);+ if (SignedArea(vertices) < 0) vertices = vertices.Reverse().ToArray();+ return Linear(name, "Triangle2", variant, c, rotation, vertices, ["A", "B", "C"], ["AB", "BC", "CA"], span, dimensions);+ }++ private static Shape? Circle(string source, string name, string body, double rotation, FirmamentV2SourceSpan span, List<string> diagnostics)+ {+ var inline = Point(body, "Center", out var c); var centerRef = Identifier(body, "Center");+ if (!inline && (centerRef is null || !ResolvePoint(source, centerRef, out c))) return null; // legacy/template Circle2 remains on its existing binder path+ var hasRadius = Length(body, "Radius", out var radius); var hasDiameter = Length(body, "Diameter", out var diameter);+ if (hasRadius == hasDiameter || (radius = hasRadius ? radius : diameter / 2) <= 0) return Invalid(name, "invalid-dimensions", diagnostics);+ var lowered = inline || hasDiameter ? $"Point2 {name}_Center {{ Position: [{N(c.X)}, {N(c.Y)}] }}\nCircle2Guide {name}_Curve {{ Center: {name}_Center; Radius: {N(radius)} }}" : null;+ var guide = lowered is null ? name : name + "_Curve"; var map = new Dictionary<string, string>(StringComparer.Ordinal) { ["Center"] = inline || hasDiameter ? name + "_Center" : centerRef! };+ return Make(name, "Circle2", null, c, rotation, new Dictionary<string, double> { ["Radius"] = radius, ["Diameter"] = 2 * radius }, ["Center"], ["Boundary"], "Circle", span, lowered, map, guide + " |> TraceLoop", Math.PI * radius * radius, 2 * Math.PI * radius);+ }++ private static Shape? Ellipse(string name, string body, double rotation, FirmamentV2SourceSpan span, List<string> diagnostics)+ {+ if (!Point(body, "Center", out var c) || !(Vector(body, "AxisLengths", out var axes) || Vector(body, "Axes", out axes)) || !Positive(axes.X, axes.Y)) return Invalid(name, "invalid-dimensions", diagnostics);+ var major = Math.Max(axes.X, axes.Y) / 2; var minor = Math.Min(axes.X, axes.Y) / 2; if (axes.Y > axes.X) rotation += 90;+ var majorPositive = Rotate((c.X + major, c.Y), c, rotation); var majorNegative = Rotate((c.X - major, c.Y), c, rotation);+ var minorPositive = Rotate((c.X, c.Y + minor), c, rotation); var minorNegative = Rotate((c.X, c.Y - minor), c, rotation);+ var lowered = $"Point2 {name}_Center {{ Position: [{N(c.X)}, {N(c.Y)}] }}\nPoint2 {name}_MajorPositive {{ Position: [{N(majorPositive.X)}, {N(majorPositive.Y)}] }}\nPoint2 {name}_MajorNegative {{ Position: [{N(majorNegative.X)}, {N(majorNegative.Y)}] }}\nPoint2 {name}_MinorPositive {{ Position: [{N(minorPositive.X)}, {N(minorPositive.Y)}] }}\nPoint2 {name}_MinorNegative {{ Position: [{N(minorNegative.X)}, {N(minorNegative.Y)}] }}\nEllipse2Guide {name}_Curve {{ Center: {name}_Center; SemiAxes: [{N(major)}, {N(minor)}]; Rotation: {Ndeg(rotation)} }}";+ return Make(name, "Ellipse2", null, c, rotation, new Dictionary<string, double> { ["MajorAxisLength"] = 2 * major, ["MinorAxisLength"] = 2 * minor }, ["Center", "MajorPositive", "MajorNegative", "MinorPositive", "MinorNegative"], ["Boundary"], "Ellipse", span, lowered,+ new Dictionary<string, string> { ["Center"] = name + "_Center", ["MajorPositive"] = name + "_MajorPositive", ["MajorNegative"] = name + "_MajorNegative", ["MinorPositive"] = name + "_MinorPositive", ["MinorNegative"] = name + "_MinorNegative", ["Boundary"] = name + "_Curve" }, name + "_Curve |> TraceLoop", Math.PI * major * minor, EllipsePerimeter(major, minor));+ }++ private static Shape? Slot(string name, string body, double rotation, FirmamentV2SourceSpan span, List<string> diagnostics)+ {+ if (!Point(body, "Center", out var c) || !Length(body, "Length", out var length) || !Length(body, "Width", out var width) || width <= 0 || length < width) return Invalid(name, "invalid-dimensions", diagnostics);+ var straight = length - width; var r = width / 2; var start = Rotate((c.X - straight / 2, c.Y - r), c, rotation);+ if (straight <= Tol)+ {+ var lowerCircle = $"Point2 {name}_Center {{ Position: [{N(c.X)}, {N(c.Y)}] }}\nCircle2Guide {name}_Curve {{ Center: {name}_Center; Radius: {N(r)} }}";+ return Make(name, "Slot2", null, c, rotation, new Dictionary<string, double> { ["OverallLength"] = length, ["Width"] = width }, ["Center"], ["Boundary"], "Circle", span, lowerCircle,+ new Dictionary<string, string> { ["Center"] = name + "_Center", ["Boundary"] = name + "_Curve" }, name + "_Curve |> TraceLoop", Math.PI * r * r, 2 * Math.PI * r);+ }+ var path = $"Concept Path {name}_Path {{ Start: Point2({N(start.X)}, {N(start.Y)}) Heading: {Ndeg(rotation)} Line Top {{ Length: {N(straight)} }} Arc EndArc {{ Radius: {N(r)}; Turn: 180deg }} Line Bottom {{ Length: {N(straight)} }} Arc StartArc {{ Radius: {N(r)}; Turn: 180deg }} }}";+ var guides = new[] { "Top", "EndArc", "Bottom", "StartArc" }; var map = guides.ToDictionary(x => x, x => name + "_Path." + x, StringComparer.Ordinal);+ return Make(name, "Slot2", null, c, rotation, new Dictionary<string, double> { ["OverallLength"] = length, ["Width"] = width }, [], guides, "Line+Circle", span, path, map, name + "_Path |> TraceLoop", width * straight + Math.PI * r * r, 2 * straight + 2 * Math.PI * r);+ }++ private static Shape? RoundedRect(string name, string body, double rotation, FirmamentV2SourceSpan span, List<string> diagnostics)+ {+ if (!Point(body, "Center", out var c) || !Vector(body, "Size", out var size) || !Length(body, "Radius", out var r) || !Positive(size.X, size.Y) || r < 0 || r > Math.Min(size.X, size.Y) / 2) return Invalid(name, "invalid-dimensions", diagnostics);+ if (r <= Tol) return Linear(name, "RoundedRect2", null, c, rotation, Rectangle(c, size.X, size.Y, rotation), ["BottomLeft", "BottomRight", "TopRight", "TopLeft"], ["Bottom", "Right", "Top", "Left"], span, new Dictionary<string, double> { ["Width"] = size.X, ["Height"] = size.Y, ["Radius"] = 0 });+ var start = Rotate((c.X - size.X / 2 + r, c.Y - size.Y / 2), c, rotation);+ var path = $"Concept Path {name}_Path {{ Start: Point2({N(start.X)}, {N(start.Y)}) Heading: {Ndeg(rotation)} Line Bottom {{ Length: {N(size.X - 2 * r)} }} Arc BottomRightCorner {{ Radius: {N(r)}; Turn: 90deg }} Line Right {{ Length: {N(size.Y - 2 * r)} }} Arc TopRightCorner {{ Radius: {N(r)}; Turn: 90deg }} Line Top {{ Length: {N(size.X - 2 * r)} }} Arc TopLeftCorner {{ Radius: {N(r)}; Turn: 90deg }} Line Left {{ Length: {N(size.Y - 2 * r)} }} Arc BottomLeftCorner {{ Radius: {N(r)}; Turn: 90deg }} }}";+ var guides = new[] { "Bottom", "BottomRightCorner", "Right", "TopRightCorner", "Top", "TopLeftCorner", "Left", "BottomLeftCorner" }; var map = guides.ToDictionary(x => x, x => name + "_Path." + x, StringComparer.Ordinal);+ var area = size.X * size.Y - (4 - Math.PI) * r * r; var perimeter = 2 * (size.X + size.Y - 4 * r) + 2 * Math.PI * r;+ return Make(name, "RoundedRect2", null, c, rotation, new Dictionary<string, double> { ["Width"] = size.X, ["Height"] = size.Y, ["Radius"] = r }, [], guides, "Line+Circle", span, path, map, name + "_Path |> TraceLoop", area, perimeter);+ }++ private static Shape? Polygon(string source, string name, string variant, string body, double rotation, FirmamentV2SourceSpan span, List<string> diagnostics)+ {+ IReadOnlyList<(double X, double Y)> vertices; IReadOnlyList<string> pointNames; Dictionary<string, double> dimensions = []; (double X, double Y) c;+ switch (variant)+ {+ case "Rhombus":+ if (!Point(body, "Center", out c) || !Vector(body, "Diagonals", out var d) || !Positive(d.X, d.Y)) { diagnostics.Add("firmament-polygon2-invalid-geometry:" + name); return null; }+ vertices = [Rotate((c.X, c.Y - d.Y / 2), c, rotation), Rotate((c.X + d.X / 2, c.Y), c, rotation), Rotate((c.X, c.Y + d.Y / 2), c, rotation), Rotate((c.X - d.X / 2, c.Y), c, rotation)]; pointNames = ["South", "East", "North", "West"]; dimensions["DiagonalX"] = d.X; dimensions["DiagonalY"] = d.Y; break;+ case "Parallelogram":+ if (!Point(body, "Center", out c) || !Length(body, "Base", out var b) || !Length(body, "Height", out var h) || !Length(body, "Shear", out var shear) || !Positive(b, h)) return Invalid(name, "invalid-dimensions", diagnostics);+ vertices = new (double X, double Y)[] { (-b / 2 - shear / 2, -h / 2), (b / 2 - shear / 2, -h / 2), (b / 2 + shear / 2, h / 2), (-b / 2 + shear / 2, h / 2) }.Select(p => Rotate((p.X + c.X, p.Y + c.Y), c, rotation)).ToArray(); pointNames = ["BottomLeft", "BottomRight", "TopRight", "TopLeft"]; dimensions["Base"] = b; dimensions["Height"] = h; dimensions["Shear"] = shear; break;+ case "Trapezoid":+ if (!Point(body, "Center", out c) || !Length(body, "BottomWidth", out var bw) || !Length(body, "TopWidth", out var tw) || !Length(body, "Height", out var th) || !Positive(bw, tw, th)) return Invalid(name, "invalid-dimensions", diagnostics);+ vertices = new (double X, double Y)[] { (-bw / 2, -th / 2), (bw / 2, -th / 2), (tw / 2, th / 2), (-tw / 2, th / 2) }.Select(p => Rotate((p.X + c.X, p.Y + c.Y), c, rotation)).ToArray(); pointNames = ["BottomLeft", "BottomRight", "TopRight", "TopLeft"]; dimensions["BottomWidth"] = bw; dimensions["TopWidth"] = tw; dimensions["Height"] = th; break;+ case "Explicit":+ var setName = Identifier(body, "Vertices");+ if (setName is null || !PointSet(source, setName, out pointNames, out vertices) || vertices.Count < 3) return Invalid(name, "explicit-too-few-vertices", diagnostics);+ if (HasDuplicate(vertices)) return Invalid(name, "explicit-duplicate-vertex", diagnostics); if (SelfIntersects(vertices)) return Invalid(name, "explicit-self-intersection", diagnostics); if (Math.Abs(SignedArea(vertices)) <= Tol) return Invalid(name, "explicit-degenerate-area", diagnostics);+ c = PolygonCentroid(vertices); rotation = 0; break;+ default: diagnostics.Add("firmament-polygon2-variant-unsupported:" + name + ":" + variant); return null;+ }+ if (SignedArea(vertices) < 0) { vertices = vertices.Reverse().ToArray(); pointNames = pointNames.Reverse().ToArray(); }+ var edgeNames = Enumerable.Range(0, vertices.Count).Select(i => pointNames[i] + "_" + pointNames[(i + 1) % vertices.Count]).ToArray();+ return Linear(name, "Polygon2", variant, c, rotation, vertices, pointNames, edgeNames, span, dimensions);+ }++ private static Shape? RegularPolygon(string name, string countText, string body, double rotation, FirmamentV2SourceSpan span, List<string> diagnostics)+ {+ if (!int.TryParse(countText, NumberStyles.Integer, CultureInfo.InvariantCulture, out var count) || count is < 3 or > 1024) return Invalid(name, "regular-count-out-of-range", diagnostics);+ if (!Point(body, "Center", out var c)) return Invalid(name, "invalid-center", diagnostics); double radius; var dimensions = new Dictionary<string, double> { ["VertexCount"] = count };+ if (Length(body, "Circumradius", out radius) && radius > 0) dimensions["Circumradius"] = radius;+ else if (Length(body, "AcrossFlats", out var flats) && flats > 0) { radius = flats / (2 * Math.Cos(Math.PI / count)); dimensions["AcrossFlats"] = flats; }+ else return Invalid(name, "invalid-size-parameter", diagnostics);+ var vertices = Enumerable.Range(0, count).Select(i => { var a = (rotation + 360d * i / count) * Math.PI / 180d; return (c.X + radius * Math.Cos(a), c.Y + radius * Math.Sin(a)); }).ToArray();+ return Linear(name, "RegularPolygon2", countText, c, rotation, vertices, Enumerable.Range(0, count).Select(i => "Vertex" + i).ToArray(), Enumerable.Range(0, count).Select(i => "Edge" + i).ToArray(), span, dimensions);+ }++ private static Shape Linear(string name, string type, string? variant, (double X, double Y) c, double rotation, IReadOnlyList<(double X, double Y)> vertices, IReadOnlyList<string> pointNames, IReadOnlyList<string> edgeNames, FirmamentV2SourceSpan span, IReadOnlyDictionary<string, double> dimensions)+ {+ var text = new StringBuilder(); var generatedPoints = new List<string>(); var generatedEdges = new List<string>(); var map = new Dictionary<string, string>(StringComparer.Ordinal);+ for (var i = 0; i < vertices.Count; i++) { var id = name + "_" + pointNames[i]; generatedPoints.Add(id); map[pointNames[i]] = id; text.Append("Point2 ").Append(id).Append(" { Position: [").Append(N(vertices[i].X)).Append(", ").Append(N(vertices[i].Y)).AppendLine("] }"); }+ for (var i = 0; i < vertices.Count; i++) { var id = name + "_" + edgeNames[i]; generatedEdges.Add(id); map[edgeNames[i]] = id; text.Append("Line2 ").Append(id).Append(" { From: ").Append(generatedPoints[i]).Append("; To: ").Append(generatedPoints[(i + 1) % vertices.Count]).AppendLine(" }"); }+ var area = Math.Abs(SignedArea(vertices)); var perimeter = Enumerable.Range(0, vertices.Count).Sum(i => Distance(vertices[i], vertices[(i + 1) % vertices.Count]));+ var trace = string.Join(" |> ", generatedEdges.Select((edge, i) => edge + " As " + edgeNames[i])) + " |> Close";+ return Make(name, type, variant, c, rotation, dimensions, pointNames, edgeNames, "Line", span, text.ToString(), map, trace, area, perimeter);+ }++ private static Shape Make(string name, string type, string? variant, (double X, double Y) c, double rotation, IReadOnlyDictionary<string, double> dimensions, IReadOnlyList<string> points, IReadOnlyList<string> edges, string carrier, FirmamentV2SourceSpan span, string? lower, IReadOnlyDictionary<string, string> map, string trace, double area, double perimeter) =>+ new(new(name, type, variant, "ClosedBoundary2", c.X, c.Y, rotation, dimensions, points, edges, carrier, area, perimeter, span), lower, map, trace, span.Start, span.Length);+ private static Shape? Invalid(string name, string reason, List<string> diagnostics) { diagnostics.Add(Prefix + reason + ":" + name); return null; }+ private static bool Inside(int index, IReadOnlyList<Shape> shapes) => shapes.Any(x => index > x.Start && index < x.Start + x.Length);+ private static IReadOnlyList<(double X, double Y)> Rectangle((double X, double Y) c, double w, double h, double r) => [Rotate((c.X - w / 2, c.Y - h / 2), c, r), Rotate((c.X + w / 2, c.Y - h / 2), c, r), Rotate((c.X + w / 2, c.Y + h / 2), c, r), Rotate((c.X - w / 2, c.Y + h / 2), c, r)];+ private static (double X, double Y) Rotate((double X, double Y) p, (double X, double Y) c, double degrees) { var a = degrees * Math.PI / 180; var x = p.X - c.X; var y = p.Y - c.Y; return (c.X + x * Math.Cos(a) - y * Math.Sin(a), c.Y + x * Math.Sin(a) + y * Math.Cos(a)); }+ private static bool Positive(params double[] values) => values.All(x => double.IsFinite(x) && x > 0);+ private static double SignedArea(IReadOnlyList<(double X, double Y)> p) => Enumerable.Range(0, p.Count).Sum(i => p[i].X * p[(i + 1) % p.Count].Y - p[(i + 1) % p.Count].X * p[i].Y) / 2;+ private static (double X, double Y) Centroid(IReadOnlyList<(double X, double Y)> p) => (p.Average(x => x.X), p.Average(x => x.Y));+ private static (double X, double Y) PolygonCentroid(IReadOnlyList<(double X, double Y)> p) { var a = SignedArea(p); var cx = 0d; var cy = 0d; for (var i = 0; i < p.Count; i++) { var q = p[(i + 1) % p.Count]; var cross = p[i].X * q.Y - q.X * p[i].Y; cx += (p[i].X + q.X) * cross; cy += (p[i].Y + q.Y) * cross; } return (cx / (6 * a), cy / (6 * a)); }+ private static bool HasDuplicate(IReadOnlyList<(double X, double Y)> p) => p.SelectMany((a, i) => p.Skip(i + 1).Select(b => Distance(a, b))).Any(x => x <= Tol);+ private static bool SelfIntersects(IReadOnlyList<(double X, double Y)> p) { for (var i = 0; i < p.Count; i++) for (var j = i + 1; j < p.Count; j++) { if (j == i + 1 || i == 0 && j == p.Count - 1) continue; if (Intersects(p[i], p[(i + 1) % p.Count], p[j], p[(j + 1) % p.Count])) return true; } return false; }+ private static bool Intersects((double X, double Y) a, (double X, double Y) b, (double X, double Y) c, (double X, double Y) d) => Cross(a, b, c) * Cross(a, b, d) < -Tol && Cross(c, d, a) * Cross(c, d, b) < -Tol;+ private static double Cross((double X, double Y) a, (double X, double Y) b, (double X, double Y) c) => (b.X - a.X) * (c.Y - a.Y) - (b.Y - a.Y) * (c.X - a.X);+ private static double Distance((double X, double Y) a, (double X, double Y) b) => Math.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y));+ private static double EllipsePerimeter(double a, double b) => Math.PI * (3 * (a + b) - Math.Sqrt((3 * a + b) * (a + 3 * b)));+ private static bool Point(string body, string field, out (double X, double Y) value) { var m = Regex.Match(body, $@"\b{field}\s*:\s*(?:\[|Point2\s*\()\s*(?<x>[-+.\deE]+)mm\s*,\s*(?<y>[-+.\deE]+)mm\s*(?:\]|\))", RegexOptions.CultureInvariant); value = default; return m.Success && Number(m.Groups["x"].Value, out value.X) && Number(m.Groups["y"].Value, out value.Y); }+ private static bool Vector(string body, string field, out (double X, double Y) value) => Point(body, field, out value);+ private static bool Length(string body, string field, out double value) { var m = Regex.Match(body, $@"\b{field}\s*:\s*(?<v>[-+.\deE]+)mm\b", RegexOptions.CultureInvariant); return Number(m.Groups["v"].Value, out value); }+ private static double Angle(string body, string field, double fallback, out bool valid) { var m = Regex.Match(body, $@"\b{field}\s*:\s*(?<v>[-+.\deE]+)deg\b", RegexOptions.CultureInvariant); if (!m.Success) { valid = true; return fallback; } valid = Number(m.Groups["v"].Value, out var value); return value; }+ private static string? Identifier(string body, string field) { var m = Regex.Match(body, $@"\b{field}\s*:\s*(?<v>[A-Za-z_]\w*)\b", RegexOptions.CultureInvariant); return m.Success ? m.Groups["v"].Value : null; }+ private static bool ResolvePoint(string source, string name, out (double X, double Y) p) { var m = Regex.Match(source, $@"\bPoint2\s+{Regex.Escape(name)}\s*\{{\s*Position\s*:\s*(?:\[|Point2\s*\()\s*(?<x>[-+.\deE]+)mm\s*,\s*(?<y>[-+.\deE]+)mm", RegexOptions.CultureInvariant); p = default; return m.Success && Number(m.Groups["x"].Value, out p.X) && Number(m.Groups["y"].Value, out p.Y); }+ private static bool PointSet(string source, string name, out IReadOnlyList<string> names, out IReadOnlyList<(double X, double Y)> points) { names = []; points = []; var h = Regex.Match(source, $@"\bStatic\s+{Regex.Escape(name)}\s*:\s*Set\s*<\s*Point2\s*>\s*\{{", RegexOptions.CultureInvariant); if (!h.Success) return false; var open = source.IndexOf('{', h.Index); var close = Matching(source, open); if (close < 0) return false; var ns = new List<string>(); var ps = new List<(double, double)>(); foreach (Match e in Regex.Matches(source[(open + 1)..close], @"\b(?<n>[A-Za-z_]\w*)\s*=>\s*Point2\s*\(\s*(?<x>[-+.\deE]+)mm\s*,\s*(?<y>[-+.\deE]+)mm\s*\)", RegexOptions.CultureInvariant)) if (Number(e.Groups["x"].Value, out var x) && Number(e.Groups["y"].Value, out var y)) { ns.Add(e.Groups["n"].Value); ps.Add((x, y)); } names = ns; points = ps; return true; }+ private static bool Number(string text, out double value) => double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out value) && double.IsFinite(value);+ private static string N(double value) => (Math.Abs(value) < 1e-13 ? 0d : value).ToString("R", CultureInfo.InvariantCulture) + "mm";+ private static string Ndeg(double value) => value.ToString("R", CultureInfo.InvariantCulture) + "deg";+ private static int Matching(string source, int open) { var depth = 0; for (var i = open; i >= 0 && i < source.Length; i++) { if (source[i] == '{') depth++; else if (source[i] == '}' && --depth == 0) return i; } return -1; }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.csindex 8daf6e32..a8f26b6d 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs@@ -3,7 +3,7 @@ using Aetheris.Surfacing;namespace Aetheris.Kernel.Firmament.FirmamentV2;-public sealed record FirmamentV2Document(string ModelName, string Units, IReadOnlyList<FirmamentV2SolidBinding> Solids, IReadOnlyList<FirmamentV2ModifyBlock>? ModifyBlocks = null, IReadOnlyList<FirmamentV2TemplateDecl>? Templates = null, IReadOnlyList<FirmamentV2PmiDecl>? Pmi = null, IReadOnlyList<FirmamentV2RecognizedRegion>? RecognizedRegions = null, IReadOnlyList<FirmamentV2ReplacementDecl>? Replacements = null, IReadOnlyList<FirmamentV2LetDeclaration>? Lets = null, IReadOnlyList<FirmamentV2BoundLet>? BoundLets = null, IReadOnlyList<FirmamentV2LetRecordDeclaration>? LetRecords = null, IReadOnlyList<FirmamentV2BoundLetRecord>? BoundLetRecords = null, IReadOnlyList<FirmamentV2ManufacturingConceptDeclaration>? ManufacturingConcepts = null, IReadOnlyList<FirmamentV2FeatureConceptDeclaration>? FeatureConcepts = null, FirmamentV2PmiBlock? PmiBlock = null, FirmamentV2BoundPmiBlock? BoundPmi = null, ConceptIrDocument? ConceptIr = null, IReadOnlyList<FirmamentV2LatticeFillDecl>? LatticeFills = null, IReadOnlyList<FirmamentV2StandaloneLatticeFillDecl>? StandaloneLatticeFills = null, IReadOnlyList<FirmamentV2ProfileDecl>? Profiles = null, IReadOnlyList<FirmamentV2ComposeDecl>? Composes = null, IReadOnlyList<FirmamentV2SelectionDecl>? Selections = null, FirmamentV2StaticAuthoringDocument? StaticAuthoring = null, FirmamentV2CanonicalSymbolTable? SymbolTable = null, IReadOnlyList<FirmamentV2VolumeAssertion>? VolumeAssertions = null, IReadOnlyList<ConceptIrTemplateInstantiation>? TemplateInstantiations = null, IReadOnlyList<PanelIr>? Panels = null, IReadOnlyList<FirmamentV2BossDecl>? Bosses = null, IReadOnlyList<FirmamentV2PocketDecl>? Pockets = null, IReadOnlyList<FirmamentV2FeatureDefinition>? FeatureDefinitions = null, IReadOnlyList<FirmamentV2FeatureInvocation>? FeatureInvocations = null, FirmamentV2FeatureExpansionMetrics? FeatureExpansion = null, IReadOnlyList<FirmamentV2Polygon2Decl>? Polygons = null)+public sealed record FirmamentV2Document(string ModelName, string Units, IReadOnlyList<FirmamentV2SolidBinding> Solids, IReadOnlyList<FirmamentV2ModifyBlock>? ModifyBlocks = null, IReadOnlyList<FirmamentV2TemplateDecl>? Templates = null, IReadOnlyList<FirmamentV2PmiDecl>? Pmi = null, IReadOnlyList<FirmamentV2RecognizedRegion>? RecognizedRegions = null, IReadOnlyList<FirmamentV2ReplacementDecl>? Replacements = null, IReadOnlyList<FirmamentV2LetDeclaration>? Lets = null, IReadOnlyList<FirmamentV2BoundLet>? BoundLets = null, IReadOnlyList<FirmamentV2LetRecordDeclaration>? LetRecords = null, IReadOnlyList<FirmamentV2BoundLetRecord>? BoundLetRecords = null, IReadOnlyList<FirmamentV2ManufacturingConceptDeclaration>? ManufacturingConcepts = null, IReadOnlyList<FirmamentV2FeatureConceptDeclaration>? FeatureConcepts = null, FirmamentV2PmiBlock? PmiBlock = null, FirmamentV2BoundPmiBlock? BoundPmi = null, ConceptIrDocument? ConceptIr = null, IReadOnlyList<FirmamentV2LatticeFillDecl>? LatticeFills = null, IReadOnlyList<FirmamentV2StandaloneLatticeFillDecl>? StandaloneLatticeFills = null, IReadOnlyList<FirmamentV2ProfileDecl>? Profiles = null, IReadOnlyList<FirmamentV2ComposeDecl>? Composes = null, IReadOnlyList<FirmamentV2SelectionDecl>? Selections = null, FirmamentV2StaticAuthoringDocument? StaticAuthoring = null, FirmamentV2CanonicalSymbolTable? SymbolTable = null, IReadOnlyList<FirmamentV2VolumeAssertion>? VolumeAssertions = null, IReadOnlyList<ConceptIrTemplateInstantiation>? TemplateInstantiations = null, IReadOnlyList<PanelIr>? Panels = null, IReadOnlyList<FirmamentV2BossDecl>? Bosses = null, IReadOnlyList<FirmamentV2PocketDecl>? Pockets = null, IReadOnlyList<FirmamentV2FeatureDefinition>? FeatureDefinitions = null, IReadOnlyList<FirmamentV2FeatureInvocation>? FeatureInvocations = null, FirmamentV2FeatureExpansionMetrics? FeatureExpansion = null, IReadOnlyList<FirmamentV2Polygon2Decl>? Polygons = null, IReadOnlyList<FirmamentV2ClosedBoundary2Decl>? Boundaries = null){public FirmamentV2SolidBinding Solid => Solids[^1];public FirmamentV2SideHoleIntent? SideHoleIntent => ModifyBlocks?.SelectMany(m => m.Regions.Select(r =>@@ -116,6 +116,23 @@ public sealed record FirmamentV2Polygon2Decl(IReadOnlyList<string> GeneratedEdges,FirmamentV2SourceSpan SourceSpan);+/// <summary>One qualified, deterministic, oriented boundary before its syntax is erased.</summary>+public sealed record FirmamentV2ClosedBoundary2Decl(+ string Name,+ string ShapeType,+ string? Variant,+ string Capability,+ double CenterX,+ double CenterY,+ double RotationDegrees,+ IReadOnlyDictionary<string, double> Dimensions,+ IReadOnlyList<string> GeneratedPoints,+ IReadOnlyList<string> GeneratedEdges,+ string ExactCarrier,+ double Area,+ double Perimeter,+ FirmamentV2SourceSpan SourceSpan);+public sealed record FirmamentV2FeatureParameter(string Name, string Type, string? DefaultExpression = null);public sealed record FirmamentV2FeatureDefinition(string Name, IReadOnlyList<FirmamentV2FeatureParameter> Parameters,string ReturnType, FirmamentV2SourceSpan SourceSpan, string Scope, string Evaluation);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.csindex c3b10177..6b0d6e94 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs@@ -305,7 +305,7 @@ public static class FirmamentV2ParsersourceText=ProfileModificationTemplateLibrary.Source+Environment.NewLine+Regex.Replace(sourceText,@"\bUse\s+Profile\.Modifications\s*;",string.Empty,RegexOptions.CultureInvariant);var diagnostics = new List<string> { "firmament-v2-parser-invoked" };var source = StripLineComments(sourceText);- var polygonExpansion = Polygon2RhombusAuthoring.Expand(source, diagnostics);+ var polygonExpansion = ClosedBoundary2Authoring.Expand(source, diagnostics);if (polygonExpansion is null){diagnostics.Add("firmament-v2-parse-failed");@@ -372,7 +372,7 @@ public static class FirmamentV2Parservar panelDocument = new FirmamentV2Document(panelCompilation.ModelName, "mm", [],TemplateInstantiations: templateExpansion.Instantiations, Panels: panelCompilation.Panels,FeatureDefinitions: featureExpansion.Definitions, FeatureInvocations: featureExpansion.Invocations,- FeatureExpansion: featureExpansion.Metrics, Polygons: polygonExpansion.Polygons);+ FeatureExpansion: featureExpansion.Metrics, Polygons: polygonExpansion.Polygons, Boundaries: polygonExpansion.Boundaries);return FirmamentV2ParseResult.Success(panelDocument, diagnostics.Distinct(StringComparer.Ordinal).Order().ToArray());}@@ -508,10 +508,10 @@ public static class FirmamentV2Parserprivate static FirmamentV2ParseResult WithPolygonMetadata(FirmamentV2ParseResult result,- Polygon2RhombusAuthoring.Result expansion) =>+ ClosedBoundary2Authoring.Result expansion) =>result.Document is null? result- : result with { Document = result.Document with { Polygons = expansion.Polygons } };+ : result with { Document = result.Document with { Polygons = expansion.Polygons, Boundaries = expansion.Boundaries } };private static bool IsV2AdmissionCandidate(string source) =>ModelRegex.IsMatch(source)@@ -960,7 +960,7 @@ public static class FirmamentV2Parservar known = new HashSet<string>(StringComparer.Ordinal){- "Box", "Cylinder", "Cone", "Sphere", "Torus", "RoundedBox", "Frustum", "StandardPart", "ExactCoaxialPart", "Concept", "Struct", "Construction", "Profile", "Span", "Compose", "Boss", "Pocket", "EdgeFinish",+ "Box", "Cylinder", "Cone", "Sphere", "Torus", "RoundedBox", "Frustum", "StandardPart", "ExactCoaxialPart", "Point2", "Line2", "Rect2", "Circle2", "Circle2Guide", "Ellipse2Guide", "Concept", "Struct", "Construction", "Profile", "Span", "Compose", "Boss", "Pocket", "EdgeFinish","Record", "Static", "Template", "template", "ProfileDelta", "Selection", "InlineStep", "Recognize", "Replace", "Pmi", "Modify", "Match", "Require", "Assert"};var compatibilityOnly = new HashSet<string>(StringComparer.Ordinal)diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Polygon2RhombusAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Polygon2RhombusAuthoring.csdeleted file mode 100644index e7714b21..00000000--- a/Aetheris.Kernel.Firmament/FirmamentV2/Polygon2RhombusAuthoring.cs+++ /dev/null@@ -1,84 +0,0 @@-using System.Globalization;-using System.Text.RegularExpressions;--namespace Aetheris.Kernel.Firmament.FirmamentV2;--/// <summary>-/// Bounded source lowering for the built-in Polygon2<Rhombus> shape. The parameter is-/// a closed shape variant, not a user-defined generic. Lowering reuses ordinary Point2,-/// Line2, Profile pipeline, validation, and materialization paths.-/// </summary>-internal static class Polygon2RhombusAuthoring-{- internal const string Prefix = "firmament-polygon2-";- internal sealed record Result(string Source, IReadOnlyList<FirmamentV2Polygon2Decl> Polygons);-- public static Result? Expand(string source, List<string> diagnostics)- {- var changes = new List<(int Start, int Length, string Text)>();- var polygons = new List<FirmamentV2Polygon2Decl>();- var names = new HashSet<string>(StringComparer.Ordinal);- foreach (Match header in Regex.Matches(source,- @"\bPolygon2\s*<\s*(?<variant>[A-Za-z_]\w*)\s*>\s+(?<name>[A-Za-z_]\w*)\s*\{",- RegexOptions.CultureInvariant))- {- var open = source.IndexOf('{', header.Index); var close = Matching(source, open);- var name = header.Groups["name"].Value; var variant = header.Groups["variant"].Value;- if (close < 0) { diagnostics.Add(Prefix + "malformed:" + name); continue; }- if (!string.Equals(variant, "Rhombus", StringComparison.Ordinal)) { diagnostics.Add(Prefix + "variant-unsupported:" + name + ":" + variant); continue; }- if (!names.Add(name)) { diagnostics.Add(Prefix + "duplicate-name:" + name); continue; }- var body = source[(open + 1)..close];- var center = Regex.Match(body, @"\bCenter\s*:\s*(?:\[|Point2\s*\()\s*(?<x>[-+.\deE]+)mm\s*,\s*(?<y>[-+.\deE]+)mm\s*(?:\]|\))", RegexOptions.CultureInvariant);- var diagonals = Regex.Match(body, @"\bDiagonals\s*:\s*\[\s*(?<x>[-+.\deE]+)mm\s*,\s*(?<y>[-+.\deE]+)mm\s*\]", RegexOptions.CultureInvariant);- if (!center.Success || !diagonals.Success- || !TryNumber(center, "x", out var centerX) || !TryNumber(center, "y", out var centerY)- || !TryNumber(diagonals, "x", out var diagonalX) || !TryNumber(diagonals, "y", out var diagonalY)- || diagonalX <= 0d || diagonalY <= 0d)- { diagnostics.Add(Prefix + "invalid-geometry:" + name); continue; }- var generatedPoints = new[] { name + "_South", name + "_East", name + "_North", name + "_West" };- var generatedEdges = new[] { name + "_SouthEast", name + "_EastNorth", name + "_NorthWest", name + "_WestSouth" };- changes.Add((header.Index, close - header.Index + 1, Lower(name, centerX, centerY, diagonalX, diagonalY)));- polygons.Add(new(name, "Rhombus", centerX, centerY, diagonalX, diagonalY, generatedPoints, generatedEdges,- new(header.Index, close - header.Index + 1)));- }- if (diagnostics.Any(item => item.StartsWith(Prefix, StringComparison.Ordinal))) return null;- foreach (var polygon in polygons)- {- var trace = $@"\b{Regex.Escape(polygon.Name)}\s*\|>\s*TraceLoop\b";- foreach (Match match in Regex.Matches(source, trace, RegexOptions.CultureInvariant))- changes.Add((match.Index, match.Length, string.Join(" |> ", polygon.GeneratedEdges) + " |> Close"));- }- var containers = changes.Where(change => change.Text.StartsWith("Point2 ", StringComparison.Ordinal)).ToArray();- foreach (var change in changes.Where(change => !containers.Any(container => container.Start < change.Start && change.Start < container.Start + container.Length)).OrderByDescending(change => change.Start))- source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);- return new(source, polygons);- }-- private static string Lower(string name, double x, double y, double dx, double dy)- {- static string N(double value) => value.ToString("R", CultureInfo.InvariantCulture) + "mm";- var south = (X: x, Y: y - dy / 2d); var east = (X: x + dx / 2d, Y: y);- var north = (X: x, Y: y + dy / 2d); var west = (X: x - dx / 2d, Y: y);- return $$"""- Point2 {{name}}_South { Position: [{{N(south.X)}}, {{N(south.Y)}}] }- Point2 {{name}}_East { Position: [{{N(east.X)}}, {{N(east.Y)}}] }- Point2 {{name}}_North { Position: [{{N(north.X)}}, {{N(north.Y)}}] }- Point2 {{name}}_West { Position: [{{N(west.X)}}, {{N(west.Y)}}] }- Line2 {{name}}_SouthEast { From: {{name}}_South; To: {{name}}_East }- Line2 {{name}}_EastNorth { From: {{name}}_East; To: {{name}}_North }- Line2 {{name}}_NorthWest { From: {{name}}_North; To: {{name}}_West }- Line2 {{name}}_WestSouth { From: {{name}}_West; To: {{name}}_South }- """;- }-- private static bool TryNumber(Match match, string group, out double value) =>- double.TryParse(match.Groups[group].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out value) && double.IsFinite(value);-- private static int Matching(string source, int open)- {- var depth = 0;- for (var index = open; index < source.Length; index++)- { if (source[index] == '{') depth++; else if (source[index] == '}' && --depth == 0) return index; }- return -1;- }-}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.csindex 5c4eb30e..2374488f 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs@@ -16,6 +16,8 @@ public static class ProfileAuthoringParserprivate static readonly Regex Point = new(@"\bPoint2\s+(?<n>[A-Za-z_]\w*)\s*\{\s*Position\s*:\s*(?:\[|Point2\s*\()\s*(?<x>[-+.\deE]+)mm\s*,\s*(?<y>[-+.\deE]+)mm\s*(?:\]|\))", RegexOptions.Singleline | RegexOptions.CultureInvariant);private static readonly Regex Line = new(@"\bLine2\s+(?<n>[A-Za-z_]\w*)\s*\{\s*From\s*:\s*(?<a>[\w.]+)\s*;?\s*To\s*:\s*(?<b>[\w.]+)", RegexOptions.Singleline | RegexOptions.CultureInvariant);private static readonly Regex Circle = new(@"\bCircle2\s+(?<n>[A-Za-z_]\w*)\s*\{\s*Center\s*:\s*(?<c>[\w.]+)\s*;?\s*Radius\s*:\s*(?<r>[-+.\deE]+)mm", RegexOptions.Singleline | RegexOptions.CultureInvariant);+ private static readonly Regex CircleGuide = new(@"\bCircle2Guide\s+(?<n>[A-Za-z_]\w*)\s*\{\s*Center\s*:\s*(?<c>[\w.]+)\s*;?\s*Radius\s*:\s*(?<r>[-+.\deE]+)mm", RegexOptions.Singleline | RegexOptions.CultureInvariant);+ private static readonly Regex EllipseGuide = new(@"\bEllipse2Guide\s+(?<n>[A-Za-z_]\w*)\s*\{\s*Center\s*:\s*(?<c>[\w.]+)\s*;?\s*SemiAxes\s*:\s*\[\s*(?<a>[-+.\deE]+)mm\s*,\s*(?<b>[-+.\deE]+)mm\s*\]\s*;?\s*Rotation\s*:\s*(?<r>[-+.\deE]+)deg", RegexOptions.Singleline | RegexOptions.CultureInvariant);private static readonly Regex Rect = new(@"\bRect2\s+(?<n>[A-Za-z_]\w*)\s*\{\s*Center\s*:\s*(?:\[|Point2\s*\()\s*(?<x>[-+.\deE]+)mm\s*,\s*(?<y>[-+.\deE]+)mm\s*(?:\]|\))\s*;?\s*Size\s*:\s*\[(?<w>[-+.\deE]+)mm\s*,\s*(?<h>[-+.\deE]+)mm\]", RegexOptions.Singleline | RegexOptions.CultureInvariant);private static readonly Regex ConstructionPlaneDeclaration = new(@"\bConstruction\s+Plane\s+(?<name>\w+)\s*\{\s*Trace\s*:\s*(?<trace>[\w.]+)\s*;?\s*\}", RegexOptions.Singleline | RegexOptions.CultureInvariant);private static readonly Regex Segment = new(@"\bSegment\s+(?<n>\w+)\s*\{\s*Trace\s*:\s*(?<trace>[\w.]+)\s*;?\s*From\s*:\s*(?<from>[\w.]+)\s*;?\s*To\s*:\s*(?<to>[\w.]+)(?:\s*;?\s*Sweep\s*:\s*(?<sweep>Clockwise|CounterClockwise))?", RegexOptions.Singleline | RegexOptions.CultureInvariant);@@ -206,7 +208,7 @@ public static class ProfileAuthoringParser}private static string ExpandBuiltInPolygons(string source, List<string> diagnostics) =>- Polygon2RhombusAuthoring.Expand(source, diagnostics)?.Source ?? source;+ ClosedBoundary2Authoring.Expand(source, diagnostics)?.Source ?? source;internal static ConstructionPlane? ResolveNamedConstructionPlane(string source, string frame, List<string> diagnostics)=> ResolveConstructionPlane(source, frame, diagnostics);@@ -241,12 +243,18 @@ public static class ProfileAuthoringParserguides[$"{name}.Top"] = new LineArcLineSegment2D(tr, tl); guides[$"{name}.Left"] = new LineArcLineSegment2D(tl, bl);}}- foreach (Match match in Circle.Matches(source))+ foreach (Match match in Circle.Matches(source).Cast<Match>().Concat(CircleGuide.Matches(source).Cast<Match>())){if (!points.TryGetValue(match.Groups["c"].Value, out var center) || !TryNumber(match.Groups["r"].Value, out var radius) || radius <= 0) { diagnostics.Add($"profile-layout-unresolved-circle:{match.Groups["n"].Value}"); continue; }// A circle remains a guide; segments choose its directed arc below.guides[match.Groups["n"].Value] = new LineArcFullCircle2D(center, radius);}+ foreach (Match match in EllipseGuide.Matches(source))+ {+ if (!points.TryGetValue(match.Groups["c"].Value, out var center) || !TryNumber(match.Groups["a"].Value, out var major) || !TryNumber(match.Groups["b"].Value, out var minor) || !TryNumber(match.Groups["r"].Value, out var rotation) || major <= 0 || minor <= 0 || minor > major)+ { diagnostics.Add($"profile-layout-unresolved-ellipse:{match.Groups["n"].Value}"); continue; }+ guides[match.Groups["n"].Value] = new LineArcFullEllipse2D(center, major, minor, rotation * Math.PI / 180d);+ }if (applySpans) ApplyGeometricSpans(source, points, guides, diagnostics, addGuides: true);}@@ -692,6 +700,8 @@ public static class ProfileAuthoringParservar stages = ParsePipelineStages(match.Groups["expression"].Value);if (stages.Count == 2 && stages[1].Kind == PipelineStageKind.TraceLoop){+ if (guides.TryGetValue(stages[0].Reference!, out var closedGuide) && closedGuide is LineArcFullCircle2D or LineArcFullEllipse2D)+ return [PipelineSegment(profile, loopName, "Boundary", closedGuide, $"concept:{profile.Frame ?? "XY"}.{stages[0].Reference}", stages[0].Reference!, false, 0, match.Index)];if (!paths.TryGetValue(stages[0].Reference!, out var path)){diagnostics.Add($"firmament-profile-traceloop-not-loop:{stages[0].Reference}");diff --git a/Aetheris.Kernel.Firmament/Materializer/LineArcProfileExtrudeEmitter.cs b/Aetheris.Kernel.Firmament/Materializer/LineArcProfileExtrudeEmitter.csindex bce8a6c3..ea34a036 100644--- a/Aetheris.Kernel.Firmament/Materializer/LineArcProfileExtrudeEmitter.cs+++ b/Aetheris.Kernel.Firmament/Materializer/LineArcProfileExtrudeEmitter.cs@@ -6,6 +6,8 @@ public abstract record LineArcProfileCurve2D;public sealed record LineArcLineSegment2D((double X, double Y) Start, (double X, double Y) End) : LineArcProfileCurve2D;public sealed record LineArcCircularArc2D((double X, double Y) Center, double Radius, double StartAngleRadians, double SweepAngleRadians) : LineArcProfileCurve2D;public sealed record LineArcFullCircle2D((double X, double Y) Center, double Radius) : LineArcProfileCurve2D;+/// <summary>Exact full planar ellipse; RotationRadians locates its major axis in local XY.</summary>+public sealed record LineArcFullEllipse2D((double X, double Y) Center, double MajorRadius, double MinorRadius, double RotationRadians) : LineArcProfileCurve2D;public sealed record LineArcProfileLoop2D(IReadOnlyList<LineArcProfileCurve2D> Curves, bool IsHole);/// <summary>Local profile and local depth interval. Height-only callers retain the historic centered interval.</summary>diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.csindex 266b7cf5..7896976b 100644--- a/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs@@ -127,6 +127,8 @@ public static class PrismaticSectionStackCompiler{LineArcLineSegment2D line => line.Start.X * line.End.Y - line.End.X * line.Start.Y,LineArcCircularArc2D arc => ArcArea(arc),+ LineArcFullCircle2D circle => 2d * Math.PI * circle.Radius * circle.Radius,+ LineArcFullEllipse2D ellipse => 2d * Math.PI * ellipse.MajorRadius * ellipse.MinorRadius,_ => 0d};return sum / 2d;diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileExtrusionBRepPlan.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileExtrusionBRepPlan.csindex 1f73539f..ed0a3b58 100644--- a/Aetheris.Kernel.Firmament/Materializer/ProfileExtrusionBRepPlan.cs+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileExtrusionBRepPlan.cs@@ -153,6 +153,20 @@ public static class ProfileExtrusionBRepPlannersideSurface = SurfaceGeometry.FromCylinder(new CylinderSurface(sv0.WorldPoint, frame.AxisZ, circle.Radius, frame.AxisX));break;}+ case LineArcFullEllipse2D ellipse:+ {+ sv0 = Vertex(ellipse.Center, false, segmentSource); sv1 = sv0; ev0 = Vertex(ellipse.Center, true, segmentSource); ev1 = ev0;+ var trim = new ParameterInterval(0, 2 * Math.PI);+ var localAxis = new Vector3D(Math.Cos(ellipse.RotationRadians), Math.Sin(ellipse.RotationRadians), 0);+ var axis = Direction3D.Create(frame.ToWorldDirection(localAxis));+ var startEllipse = CurveGeometry.FromEllipse(new Ellipse3Curve(sv0.WorldPoint, frame.AxisZ, ellipse.MajorRadius, ellipse.MinorRadius, axis));+ var endEllipse = CurveGeometry.FromEllipse(new Ellipse3Curve(ev0.WorldPoint, frame.AxisZ, ellipse.MajorRadius, ellipse.MinorRadius, axis));+ startEdge = Edge(prefix + ":edge:local-start", sv0, sv0, Curve(prefix + ":curve:local-start", startEllipse, trim, segmentSource), segmentSource, ProfileExtrusionPlanRole.LocalStartBoundary);+ endEdge = Edge(prefix + ":edge:local-end", ev0, ev0, Curve(prefix + ":curve:local-end", endEllipse, trim, segmentSource), segmentSource, ProfileExtrusionPlanRole.LocalEndBoundary);+ startLongitudinal = Vertical(ellipse.Center, sv0, ev0, segmentSource); endLongitudinal = startLongitudinal;+ sideSurface = SurfaceGeometry.FromLinearExtrusion(new LinearExtrusionSurface(startEllipse, frame.AxisZ.ToVector() * (end - start)));+ break;+ }default: throw new InvalidOperationException("ProfileExtrusionUnsupportedCurve");}// Loop winding is authored in local Profile coordinates (outer CCW, inner CW).@@ -226,7 +240,8 @@ public static class ProfileExtrusionBRepPlannercase LineArcLineSegment2D line when Distance(line.Start, line.End) <= Tol: d.Add("ProfileExtrusionPlanInvalid: zero length line"); return false;case LineArcCircularArc2D arc when !double.IsFinite(arc.Radius) || arc.Radius <= Tol || Math.Abs(arc.SweepAngleRadians) <= Tol: d.Add("ProfileExtrusionUnsupportedCurve: invalid arc"); return false;case LineArcFullCircle2D circle when !double.IsFinite(circle.Radius) || circle.Radius <= Tol: d.Add("ProfileExtrusionUnsupportedCurve: invalid circle"); return false;- case not (LineArcLineSegment2D or LineArcCircularArc2D or LineArcFullCircle2D): d.Add("ProfileExtrusionUnsupportedCurve"); return false;+ case LineArcFullEllipse2D ellipse when !double.IsFinite(ellipse.MajorRadius) || !double.IsFinite(ellipse.MinorRadius) || ellipse.MajorRadius <= Tol || ellipse.MinorRadius <= Tol || ellipse.MinorRadius > ellipse.MajorRadius: d.Add("ProfileExtrusionUnsupportedCurve: invalid ellipse"); return false;+ case not (LineArcLineSegment2D or LineArcCircularArc2D or LineArcFullCircle2D or LineArcFullEllipse2D): d.Add("ProfileExtrusionUnsupportedCurve"); return false;}}return true;diff --git a/Aetheris.Kernel.Firmament/Materializer/ResolvedProfile2D.cs b/Aetheris.Kernel.Firmament/Materializer/ResolvedProfile2D.csindex ec25b9ab..e32ecf6b 100644--- a/Aetheris.Kernel.Firmament/Materializer/ResolvedProfile2D.cs+++ b/Aetheris.Kernel.Firmament/Materializer/ResolvedProfile2D.cs@@ -31,11 +31,11 @@ public static class ResolvedProfile2DValidatorvar names = new HashSet<string>(StringComparer.Ordinal);foreach (var loop in profile.Loops){- if (loop.Segments.Count == 0 || (loop.Segments.Count < 3 && !(loop.Segments.Count == 1 && loop.Segments[0].Geometry is LineArcFullCircle2D))) d.Add($"profile:{profile.Name}: loop '{loop.Name}' requires a closed boundary");+ if (loop.Segments.Count == 0 || (loop.Segments.Count < 3 && !(loop.Segments.Count == 1 && loop.Segments[0].Geometry is LineArcFullCircle2D or LineArcFullEllipse2D))) d.Add($"profile:{profile.Name}: loop '{loop.Name}' requires a closed boundary");for (var i=0;i<loop.Segments.Count;i++){var s=loop.Segments[i]; if(!names.Add(s.Name))d.Add($"profile:{profile.Name}: duplicate segment '{s.Name}'");- if (s.Geometry is LineArcFullCircle2D && loop.Segments.Count == 1) continue;+ if (s.Geometry is LineArcFullCircle2D or LineArcFullEllipse2D && loop.Segments.Count == 1) continue;if(!Endpoints(s.Geometry,out var start,out var end)){d.Add($"profile:{profile.Name}: unsupported unbounded segment '{s.Name}'");continue;}if(Distance(start,end)<=Tol)d.Add($"profile:{profile.Name}: zero-length segment '{s.Name}'");var next=loop.Segments[(i+1)%loop.Segments.Count]; if(Endpoints(next.Geometry,out var ns,out _)&&Distance(end,ns)>Tol)d.Add($"profile:{profile.Name}: endpoint mismatch '{s.Name}' -> '{next.Name}'");@@ -47,7 +47,9 @@ public static class ResolvedProfile2DValidatorif (!Adjacent(i,j,loop.Segments.Count) && a.Geometry is LineArcLineSegment2D && b.Geometry is LineArcLineSegment2D && Endpoints(a.Geometry,out var as_,out var ae) && Endpoints(b.Geometry,out var bs,out var be) && ProperIntersection(as_,ae,bs,be)) d.Add($"profile:{profile.Name}: self-intersection '{a.Name}' / '{b.Name}'");}}- var area=outer.Segments.Sum(s=>Endpoints(s.Geometry,out var a,out var b)?a.X*b.Y-b.X*a.Y:0)/2d;+ var area=outer.Segments.Count == 1 && outer.Segments[0].Geometry is LineArcFullCircle2D circle ? Math.PI * circle.Radius * circle.Radius+ : outer.Segments.Count == 1 && outer.Segments[0].Geometry is LineArcFullEllipse2D ellipse ? Math.PI * ellipse.MajorRadius * ellipse.MinorRadius+ : outer.Segments.Sum(s=>Endpoints(s.Geometry,out var a,out var b)?a.X*b.Y-b.X*a.Y:0)/2d;if(area<=Tol)d.Add($"profile:{profile.Name}: outer winding must be CounterClockwise with nonzero area");return new(d.Count==0,area,d);}diff --git a/docs/public/README.md b/docs/public/README.mdindex c47760cd..3617f7c7 100644--- a/docs/public/README.md+++ b/docs/public/README.md@@ -4,7 +4,7 @@ This directory is the only authoritative in-repository guide to behavior shippedStart with [Getting Started](getting-started.md), then use these guides:-- Firmament: [overview](firmament/overview.md), [language style](firmament/language-style.md), [syntax](firmament/syntax.md), [geometry](firmament/geometry.md), [bounded mathematical sculpting](firmament/sculpting.md), [Section chains](firmament/section-chains.md), [PlasticShell](firmament/plastic-shell.md), [Circular Sweep](firmament/sweep.md), [Formed Wire](firmament/wire-form.md), [Structural members and weldments](firmament/structural.md), [Semantic piping and local autorouting](firmament/piping.md), [Paperclip Template](firmament/paperclip.md), [Templates](firmament/templates.md), [materials](firmament/materials.md), [PMI](firmament/pmi.md), [Sheet Metal](firmament/sheet-metal.md), [FEA](firmament/fea.md), and [STEP import](firmament/step-import.md)+- Firmament: [overview](firmament/overview.md), [language style](firmament/language-style.md), [syntax](firmament/syntax.md), [geometry](firmament/geometry.md), [closed 2D boundaries](firmament/boundaries.md), [bounded mathematical sculpting](firmament/sculpting.md), [Section chains](firmament/section-chains.md), [PlasticShell](firmament/plastic-shell.md), [Circular Sweep](firmament/sweep.md), [Formed Wire](firmament/wire-form.md), [Structural members and weldments](firmament/structural.md), [Semantic piping and local autorouting](firmament/piping.md), [Paperclip Template](firmament/paperclip.md), [Templates](firmament/templates.md), [materials](firmament/materials.md), [PMI](firmament/pmi.md), [Sheet Metal](firmament/sheet-metal.md), [FEA](firmament/fea.md), and [STEP import](firmament/step-import.md)- Non-manufacturing work: [Virtual Sculpture and Sol 1](virtual-sculpture.md)- Standard Library: [product-family index, invocation, authoring, and compatibility](standard-library/README.md)- Interoperability: [Forge Host Protocol v1](forge/interop.md)diff --git a/docs/public/firmament/boundaries.md b/docs/public/firmament/boundaries.mdnew file mode 100644index 00000000..31409762--- /dev/null+++ b/docs/public/firmament/boundaries.md@@ -0,0 +1,59 @@+# Closed 2D boundaries++`ClosedBoundary2` is the semantic contract for one deterministic, oriented, non-self-intersecting 2D boundary. It is not a public inheritance hierarchy or a sketch solver. Canonical declarations lower through the existing `Point2`, `Line2`, circular/elliptical curve, `Profile`, AIR, and STEP path.++Use the most semantic available noun:++| Type | Intended use | Primary dimensions | Stable guides |+| --- | --- | --- | --- |+| `Rect2` | rectangle | `Center`, `Size: [width, height]` | `Bottom`, `Right`, `Top`, `Left`; four corners |+| `Square2` | structurally equal sides | `Center`, scalar `Size` | same edge/corner vocabulary as `Rect2` |+| `Triangle2<Equilateral>` | equal-sided triangle | `Center`, `Side` | `A`, `B`, `C`; `AB`, `BC`, `CA` |+| `Triangle2<Isosceles>` | centered isosceles triangle | `Center`, `Base`, `Height` | `A`, `B`, `C`; `AB`, `BC`, `CA` |+| `Triangle2<Right>` | right triangle | right-angle `Origin`, `Legs` | `A`, `B`, `C`; `AB`, `BC`, `CA` |+| `Triangle2<Explicit>` | directly named triangle | `A`, `B`, `C` | `A`, `B`, `C`; `AB`, `BC`, `CA` |+| `Circle2` | circular boundary | `Center`, exactly one of `Diameter` or `Radius` | `Center`, one analytic `Boundary` |+| `Ellipse2` | elliptical boundary | `Center`, full `AxisLengths` | center/extrema and one analytic `Boundary` |+| `Slot2` | straight engineering slot | `Center`, overall `Length`, `Width` | `Top`, `EndArc`, `Bottom`, `StartArc` |+| `RoundedRect2` | rounded rectangular region | `Center`, `Size`, `Radius` | four lines and four named corner arcs |+| `Polygon2<Rhombus>` | diagonal-defined rhombus | `Center`, full `Diagonals` | four compass vertices and derived edges |+| `Polygon2<Parallelogram>` | sheared parallel-sided boundary | `Center`, `Base`, `Height`, `Shear` | four corners and derived edges |+| `Polygon2<Trapezoid>` | centered parallel-sided taper | `Center`, `BottomWidth`, `TopWidth`, `Height` | four corners and derived edges |+| `Polygon2<Explicit>` | arbitrary linear boundary | named `Set<Point2>` | authored vertex names and derived `A_B` edges |+| `RegularPolygon2<N>` | regular polygon | `Center`, `Circumradius` or `AcrossFlats` | `Vertex0...`, `Edge0...` |++Every form is consumed identically inside a profile:++```firmament+RoundedRect2 Panel { Center: [0mm, 0mm] Size: [100mm, 60mm] Radius: 8mm }+Profile PanelProfile { Loop Outer { Panel |> TraceLoop } }+```++Compact declarations for the complete family:++```firmament+Rect2 Plate { Center: [0mm,0mm] Size: [100mm,60mm] }+Square2 Pad { Center: [0mm,0mm] Size: 40mm }+Triangle2<Equilateral> TriEq { Center: [0mm,0mm] Side: 40mm }+Triangle2<Isosceles> TriIso { Center: [0mm,0mm] Base: 40mm Height: 30mm }+Triangle2<Right> TriRight { Origin: [0mm,0mm] Legs: [30mm,40mm] }+Triangle2<Explicit> TriAny { A: [0mm,0mm] B: [30mm,0mm] C: [0mm,20mm] }+Circle2 HoleBoundary { Center: [0mm,0mm] Diameter: 20mm }+Ellipse2 Opening { Center: [0mm,0mm] AxisLengths: [40mm,20mm] }+Slot2 CableSlot { Center: [0mm,0mm] Length: 50mm Width: 12mm }+RoundedRect2 Panel { Center: [0mm,0mm] Size: [100mm,60mm] Radius: 8mm }+Polygon2<Rhombus> Diamond { Center: [0mm,0mm] Diagonals: [50mm,32mm] }+Polygon2<Parallelogram> Leaning { Center: [0mm,0mm] Base: 40mm Height: 24mm Shear: 10mm }+Polygon2<Trapezoid> Tapered { Center: [0mm,0mm] BottomWidth: 44mm TopWidth: 28mm Height: 24mm }+Static Vertices: Set<Point2> { A => Point2(0mm,0mm) B => Point2(30mm,0mm) C => Point2(20mm,20mm) D => Point2(0mm,15mm) }+Polygon2<Explicit> Outline { Vertices: Vertices }+RegularPolygon2<6> Hex { Center: [0mm,0mm] AcrossFlats: 32mm Rotation: 30deg }+```++`Rotation: Angle` rotates a shape in its local XY plane. Placement remains owned by the existing `Concept Struct ... On XY` / `Profile ... Using ...` frame architecture; the shape declarations do not introduce a second frame system.++`Slot2.Length` is the overall end-to-end length and must be at least `Width`; equality lowers deterministically to one circular boundary. `Ellipse2.AxisLengths` are full lengths, not semi-axes. `RoundedRect2` accepts radius zero as rectangle-equivalent geometry. All sizes must be finite and positive, and rounded radius cannot exceed half the smaller size.++`RegularPolygon2<N>` is a bounded built-in structural parameter (`3 <= N <= 1024`), not general const generics. `Polygon2<T>` admits only the documented constrained variants. Add another named polygon variant only when it supplies meaningful geometric constraints or substantially better engineering dimensions than `Polygon2<Explicit>`.++`Polygon2<Explicit>` preserves the source order and names of its `Set<Point2>` entries, rejects duplicates, degenerate area, and self-intersection, and derives stable edge identities from adjacent names.diff --git a/docs/release/GEOM-BOUNDARY2-X1.md b/docs/release/GEOM-BOUNDARY2-X1.mdnew file mode 100644index 00000000..5208f23c--- /dev/null+++ b/docs/release/GEOM-BOUNDARY2-X1.md@@ -0,0 +1,94 @@+# GEOM-BOUNDARY2-X1 — canonical 2D boundary families++## Executive verdict++**Accepted.** Firmament can express the common closed 2D boundary families directly, expose stable semantic guides, and pass them through `TraceLoop` without manual point/line/arc reconstruction. The constructors erase into the existing Profile/AIR/BRep/STEP path; no second sketch kernel or profile representation was introduced.++## Audit++Before X1, the repository had three relevant but uneven surfaces:++- `Rect2` was a semantic construction helper with virtual corner and edge guides, but it did not itself satisfy `Shape |> TraceLoop`.+- `Circle2` was an analytic curve guide used by explicit profile segments; it was not a directly traceable closed boundary and required a separately authored center point.+- `Polygon2<Rhombus>` was the only retained closed-shape declaration. Its bounded source expansion produced four ordinary `Point2` and `Line2` guides and rewrote `TraceLoop` into the existing profile pipeline.+- `Concept Path` already owned exact connected line/arc construction, traversal identity, and provenance. `ProfileAuthoringParser` already owned winding, closure, `Span<T>`, and resolution to `ResolvedProfile2D`.+- The material AIR admitted line segments, circular arcs, and full circles. Core BRep/STEP already admitted `Ellipse3` and `LinearExtrusionSurface`, but the profile AIR had no full-ellipse carrier.++The narrow common contract is therefore retained semantic metadata plus exactly one deterministic closed oriented curve chain that can be erased into `ResolvedProfile2D`. `ClosedBoundary2` does not own feature semantics, compound profiles, booleans, arbitrary constraints, or materialization.++Existing frame authority remains `Concept Struct ... On XY`, `Construction Plane`, and `Profile ... Using ...`. Shapes add only a uniform local `Rotation`; they do not add an `On`/frame subsystem. Outer-loop traversal is counter-clockwise. `TraceLoop` retains generated guide names as profile span names and provenance.++## Qualified shape matrix++| Shape | Qualified | Exact carrier | Stable guides | `TraceLoop` | `Span<Plane>` | STEP |+| --- | --- | --- | --- | --- | --- | --- |+| `Rect2` | yes | lines | 4 edges + 4 corners | yes | profile boundary | analytic planar/linear |+| `Square2` | yes | lines | 4 edges + 4 corners | yes | profile boundary | analytic planar/linear |+| `Triangle2<Equilateral/Isosceles/Right/Explicit>` | yes | lines | `A/B/C`, `AB/BC/CA` | yes | profile boundary | analytic planar/linear |+| `Circle2` | yes | one full circle | `Center`, `Boundary` | yes | profile boundary | circle/cylinder |+| `Ellipse2` | yes | one full ellipse | center, four extrema, `Boundary` | yes | profile boundary | ellipse + linear extrusion |+| `Slot2` | yes | 2 lines + 2 circles | named lines/caps | yes | profile boundary | line/circle/cylinder |+| `RoundedRect2` | yes | 4 lines + 4 circles | named lines/corners | yes | profile boundary | line/circle/cylinder |+| `Polygon2<Rhombus>` | yes, compatible | lines | compass vertices + derived edges | yes | profile boundary | analytic planar/linear |+| `Polygon2<Parallelogram>` | yes | lines | corners + derived edges | yes | profile boundary | analytic planar/linear |+| `Polygon2<Trapezoid>` | yes | lines | corners + derived edges | yes | profile boundary | analytic planar/linear |+| `Polygon2<Explicit>` | yes | lines | Set names + derived edges | yes | profile boundary | analytic planar/linear |+| `RegularPolygon2<N>` | yes, `3..1024` | lines | ordinal vertices/edges | yes | profile boundary | analytic planar/linear |++`Polygon2<Kite>` was intentionally not admitted: the proposed diagonal/intersection parameterization did not justify another public variant in X1. A regular kite is better expressed by its more semantic family where one exists; an arbitrary one uses `Polygon2<Explicit>`.++## Taxonomy and parameter doctrine++Rectangle, square, circle, ellipse, slot, and rounded rectangle remain separate public nouns because each structurally encodes different invariants and engineering dimensions. `Polygon2<T>` is reserved for bounded polygon variants whose constraints or dimensions are materially better than an explicit vertex set. This prevents both a giant `Shape2<Kind>` field switch and a named-shape encyclopedia.++`RegularPolygon2<N>` is a compiler-known structural shape parameter. The binder admits an integer literal only, validates `3 <= N <= 1024`, generates a finite deterministic vertex/edge sequence, and erases it before AIR. It introduces no user-defined const parameter, arithmetic over type parameters, or general metaprogramming facility.++## Before / after++Rectangle:++```firmament+// Before: Bottom |> Right |> Top |> Left |> Close+Rect2 Plate { Center: [0mm,0mm] Size: [100mm,60mm] }+Profile PlateProfile { Loop Outer { Plate |> TraceLoop } }+```++Slot:++```firmament+// Before: two points/lines, two circle guides, four directed segments+Slot2 CableSlot { Center: [0mm,0mm] Length: 50mm Width: 12mm }+Profile SlotProfile { Loop Outer { CableSlot |> TraceLoop } }+```++Explicit polygon:++```firmament+Static Vertices: Set<Point2> { A => Point2(0mm,0mm) B => Point2(30mm,0mm) C => Point2(20mm,20mm) D => Point2(0mm,15mm) }+Polygon2<Explicit> Outline { Vertices: Vertices }+Profile OutlineProfile { Loop Outer { Outline |> TraceLoop } }+```++## Inspection, validation, and compatibility++`aetheris inspect --json` now reports `boundaries` with shape ID/type/variant, `ClosedBoundary2` capability, center, rotation, dimensions, analytic area/perimeter, generated guides, exact carrier, and source provenance. The legacy `polygons` projection remains for `Polygon2` consumers, including byte-stable `Polygon2<Rhombus>` behavior.++Canonical families validate positive dimensions and non-degenerate orientation. Slot length is overall length and must be at least width. Rounded radius is inclusive from zero through half the smaller dimension. Explicit polygons preserve Set order/names and reject fewer than three points, duplicates/zero edges, self-intersection, and zero area. Regular polygons reject counts outside `3..1024` and missing/nonpositive size forms.++The canonical fixture is `fixtures/Canonical/Boundary2/closed-boundary-family.firmament`; typed negative witnesses are under `fixtures/Invalid/Boundary2/`. Candidate LANG-BURN replacements are the manual rectangle loops in Feature/PMI/Integration fixtures and the record-array slot pattern; no burn-in rewrite was performed in X1.++## Validation++- Release solution build: passed.+- Full solution: 3,373 passed (the intentionally empty FrictionLab test assembly reports no discoverable tests).+- Full Firmament suite: 1,407 passed.+- Full CLI suite: 419 passed.+- Focused ClosedBoundary2/guide/TraceLoop/area/perimeter/invalid/analytic STEP tests: passed.+- Canonical family CLI inspection: 15 retained boundary declarations with discoverable guides.+- Canonical family production CLI build: passed; output under ignored `artifacts/local/boundary2/`.+- `Polygon2<Rhombus>` Set regression and CLI inspection: passed.+- Canonical qualification: 161 fixtures passed.+- Repository layout and documentation-link guard: passed.+- Deterministic repeat export and fresh published-CLI parity: byte-identical SHA-256 `8af59b8584e2ecd92826442180fb7f83b6821292eb2d045107422478d57dac07`.+- STEP reimport: valid enclosed manifold; focused ellipse export/reimport retained `Ellipse3` curves.+- `git diff --check`: passed.diff --git a/fixtures/Canonical/Boundary2/closed-boundary-family.firmament b/fixtures/Canonical/Boundary2/closed-boundary-family.firmamentnew file mode 100644index 00000000..90f5e0b1--- /dev/null+++ b/fixtures/Canonical/Boundary2/closed-boundary-family.firmament@@ -0,0 +1,30 @@+Model ClosedBoundaryFamily {+ Units: mm++ Static OutlinePoints: Set<Point2> {+ A => Point2(-18mm, -10mm)+ B => Point2(12mm, -10mm)+ Nose => Point2(20mm, 0mm)+ C => Point2(12mm, 12mm)+ D => Point2(-18mm, 8mm)+ }++ Rect2 Plate { Center: [0mm, 0mm] Size: [100mm, 60mm] }+ Square2 Pad { Center: [0mm, 0mm] Size: 40mm }+ Triangle2<Equilateral> Equilateral { Center: [0mm, 0mm] Side: 40mm }+ Triangle2<Isosceles> Isosceles { Center: [0mm, 0mm] Base: 40mm Height: 30mm }+ Triangle2<Right> RightAngle { Origin: [0mm, 0mm] Legs: [30mm, 40mm] }+ Triangle2<Explicit> ExplicitTriangle { A: [0mm, 0mm] B: [30mm, 0mm] C: [0mm, 20mm] }+ Circle2 Bore { Center: [0mm, 0mm] Diameter: 12mm }+ Ellipse2 Opening { Center: [0mm, 0mm] AxisLengths: [40mm, 20mm] Rotation: 15deg }+ Slot2 CableSlot { Center: [0mm, 0mm] Length: 50mm Width: 12mm }+ RoundedRect2 MountingRegion { Center: [0mm, 0mm] Size: [80mm, 44mm] Radius: 8mm }+ Polygon2<Rhombus> Diamond { Center: [0mm, 0mm] Diagonals: [50mm, 32mm] }+ Polygon2<Parallelogram> Leaning { Center: [0mm, 0mm] Base: 40mm Height: 24mm Shear: 10mm }+ Polygon2<Trapezoid> Tapered { Center: [0mm, 0mm] BottomWidth: 44mm TopWidth: 28mm Height: 24mm }+ Polygon2<Explicit> AuthoredOutline { Vertices: OutlinePoints }+ RegularPolygon2<6> Hex { Center: [0mm, 0mm] AcrossFlats: 32mm Rotation: 30deg }++ Profile PlateProfile { Loop Outer { Plate |> TraceLoop } Loop BoreLoop { Bore |> TraceLoop } }+ Struct Part { Extrude Solid { Profile: PlateProfile From: 0mm To: 5mm } }+}diff --git a/fixtures/Canonical/coverage.json b/fixtures/Canonical/coverage.jsonindex 3a20ec87..632734b9 100644--- a/fixtures/Canonical/coverage.json+++ b/fixtures/Canonical/coverage.json@@ -57,6 +57,7 @@"MaterializedStandoff": "PlasticShell/plastic-shell-materialized-standoff.firmament","MaterializedRib": "PlasticShell/plastic-shell-materialized-rib.firmament","MoldedRibStandoffJunction": "PlasticShell/plastic-shell-rib-standoff-junction.firmament",- "Polygon2Rhombus": "Set/mounting-points.firmament"+ "Polygon2Rhombus": "Set/mounting-points.firmament",+ "ClosedBoundary2": "Boundary2/closed-boundary-family.firmament"}}diff --git a/fixtures/Canonical/qualification.json b/fixtures/Canonical/qualification.jsonindex 365fb39b..66c5e512 100644--- a/fixtures/Canonical/qualification.json+++ b/fixtures/Canonical/qualification.json@@ -24,12 +24,14 @@{ "path": "Basics", "operation": "build-step" },{ "path": "Primitives", "operation": "build-step" },{ "path": "Profiles", "operation": "build-step" },+ { "path": "Pipeline", "operation": "build-step" },{ "path": "Features", "operation": "build-step" },{ "path": "Feature", "operation": "build-step" },{ "path": "Schema", "operation": "build-step" },{ "path": "Patterns", "operation": "build-step" },{ "path": "Set", "operation": "build-step" },{ "path": "Span", "operation": "build-step" },+ { "path": "Boundary2", "operation": "build-step" },{ "path": "PMI", "operation": "build-step" },{ "path": "Templates", "operation": "build-step" },{ "path": "Integration", "operation": "build-step" }diff --git a/fixtures/Invalid/Boundary2/explicit-duplicate.firmament b/fixtures/Invalid/Boundary2/explicit-duplicate.firmamentnew file mode 100644index 00000000..8b71a86a--- /dev/null+++ b/fixtures/Invalid/Boundary2/explicit-duplicate.firmament@@ -0,0 +1 @@+Model Invalid { Units: mm Static V: Set<Point2> { A => Point2(0mm,0mm) B => Point2(1mm,0mm) C => Point2(1mm,0mm) } Polygon2<Explicit> Bad { Vertices: V } Box Base { Size: [2mm,2mm,2mm] } }diff --git a/fixtures/Invalid/Boundary2/explicit-self-intersection.firmament b/fixtures/Invalid/Boundary2/explicit-self-intersection.firmamentnew file mode 100644index 00000000..d9788129--- /dev/null+++ b/fixtures/Invalid/Boundary2/explicit-self-intersection.firmament@@ -0,0 +1 @@+Model Invalid { Units: mm Static V: Set<Point2> { A => Point2(0mm,0mm) B => Point2(2mm,2mm) C => Point2(0mm,2mm) D => Point2(2mm,0mm) } Polygon2<Explicit> Bad { Vertices: V } Box Base { Size: [2mm,2mm,2mm] } }diff --git a/fixtures/Invalid/Boundary2/explicit-too-few.firmament b/fixtures/Invalid/Boundary2/explicit-too-few.firmamentnew file mode 100644index 00000000..14b7a6ec--- /dev/null+++ b/fixtures/Invalid/Boundary2/explicit-too-few.firmament@@ -0,0 +1 @@+Model Invalid { Units: mm Static V: Set<Point2> { A => Point2(0mm,0mm) B => Point2(1mm,0mm) } Polygon2<Explicit> Bad { Vertices: V } Box Base { Size: [2mm,2mm,2mm] } }diff --git a/fixtures/Invalid/Boundary2/rect-negative-size.firmament b/fixtures/Invalid/Boundary2/rect-negative-size.firmamentnew file mode 100644index 00000000..3ed6e3f0--- /dev/null+++ b/fixtures/Invalid/Boundary2/rect-negative-size.firmament@@ -0,0 +1 @@+Model Invalid { Units: mm Rect2 Bad { Center: [0mm,0mm] Size: [-1mm,2mm] } Box Base { Size: [2mm,2mm,2mm] } }diff --git a/fixtures/Invalid/Boundary2/regular-count-too-small.firmament b/fixtures/Invalid/Boundary2/regular-count-too-small.firmamentnew file mode 100644index 00000000..779c0771--- /dev/null+++ b/fixtures/Invalid/Boundary2/regular-count-too-small.firmament@@ -0,0 +1 @@+Model Invalid { Units: mm RegularPolygon2<2> Bad { Center: [0mm,0mm] Circumradius: 1mm } Box Base { Size: [2mm,2mm,2mm] } }diff --git a/fixtures/Invalid/Boundary2/regular-invalid-size.firmament b/fixtures/Invalid/Boundary2/regular-invalid-size.firmamentnew file mode 100644index 00000000..65c70cd9--- /dev/null+++ b/fixtures/Invalid/Boundary2/regular-invalid-size.firmament@@ -0,0 +1 @@+Model Invalid { Units: mm RegularPolygon2<6> Bad { Center: [0mm,0mm] Circumradius: 0mm } Box Base { Size: [2mm,2mm,2mm] } }diff --git a/fixtures/Invalid/Boundary2/rounded-radius-too-large.firmament b/fixtures/Invalid/Boundary2/rounded-radius-too-large.firmamentnew file mode 100644index 00000000..10204e02--- /dev/null+++ b/fixtures/Invalid/Boundary2/rounded-radius-too-large.firmament@@ -0,0 +1 @@+Model Invalid { Units: mm RoundedRect2 Bad { Center: [0mm,0mm] Size: [20mm,10mm] Radius: 6mm } Box Base { Size: [2mm,2mm,2mm] } }diff --git a/fixtures/Invalid/Boundary2/slot-impossible.firmament b/fixtures/Invalid/Boundary2/slot-impossible.firmamentnew file mode 100644index 00000000..6e174fb7--- /dev/null+++ b/fixtures/Invalid/Boundary2/slot-impossible.firmament@@ -0,0 +1 @@+Model Invalid { Units: mm Slot2 Bad { Center: [0mm,0mm] Length: 10mm Width: 12mm } Box Base { Size: [2mm,2mm,2mm] } }diff --git a/fixtures/Invalid/Boundary2/square-zero-size.firmament b/fixtures/Invalid/Boundary2/square-zero-size.firmamentnew file mode 100644index 00000000..38194429--- /dev/null+++ b/fixtures/Invalid/Boundary2/square-zero-size.firmament@@ -0,0 +1 @@+Model Invalid { Units: mm Square2 Bad { Center: [0mm,0mm] Size: 0mm } Box Base { Size: [2mm,2mm,2mm] } }diff --git a/fixtures/Invalid/Boundary2/triangle-degenerate.firmament b/fixtures/Invalid/Boundary2/triangle-degenerate.firmamentnew file mode 100644index 00000000..49aff630--- /dev/null+++ b/fixtures/Invalid/Boundary2/triangle-degenerate.firmament@@ -0,0 +1 @@+Model Invalid { Units: mm Triangle2<Explicit> Bad { A: [0mm,0mm] B: [1mm,0mm] C: [2mm,0mm] } Box Base { Size: [2mm,2mm,2mm] } }