Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Firmament: Compose<Hollow> and Extrude<Hollow> at constant wall

Claude3922d92af1e8
diff --git a/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs b/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs
index 9fe00236..eb647650 100644
--- a/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs
+++ b/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs
@@ -400,13 +400,32 @@ public static class BrepMassProperties
if (!TrySignedPlanarCurveAreaTwice(body, use.Edge, use.From, out var contribution)) return false;
signedArea += contribution / 2d;
}
- var probe = new Point3D(candidate.Points.Average(p => p.X), candidate.Points.Average(p => p.Y), candidate.Points[0].Z);
- var depth = loops.Where((_, index) => index != i).Count(loop => PointInPolygon(probe, loop.Points));
+ // Nesting is decided from a point on this loop against the other loops traced along their arcs: section
+ // loops never cross, so any point of one lies strictly inside or outside another. A vertex average is
+ // not a safe probe: an outer wall's average falls inside a concentric inner wall.
+ var probe = candidate.Points[0];
+ var depth = loops.Where((_, index) => index != i).Count(loop => PointInPolygon(probe, Trace(body, loop.Uses, loop.Points)));
area += (depth & 1) == 0 ? System.Math.Abs(signedArea) : -System.Math.Abs(signedArea);
}
return area > 0d;
}
+ private static IReadOnlyList<Point3D> Trace(BrepBody body, IReadOnlyList<(EdgeId Edge, VertexId From)> uses, IReadOnlyList<Point3D> vertices)
+ {
+ var points = new List<Point3D>();
+ for (var u = 0; u < uses.Count; u++)
+ {
+ points.Add(vertices[u]);
+ var (edgeId, from) = uses[u];
+ if (!body.Bindings.TryGetEdgeBinding(edgeId, out var binding) || binding.TrimInterval is not { } trim
+ || !body.Geometry.TryGetCurve(binding.CurveGeometryId, out var curve) || curve?.Circle3 is not { } circle) continue;
+ var forward = (body.Topology.GetEdge(edgeId).StartVertexId == from) == binding.OrientedEdgeSense;
+ var (start, end) = forward ? (trim.Start, trim.End) : (trim.End, trim.Start);
+ for (var k = 1; k < 32; k++) points.Add(circle.Evaluate(start + (end - start) * k / 32d));
+ }
+ return points;
+ }
+
private static bool PointInPolygon(Point3D point, IReadOnlyList<Point3D> polygon)
{
var inside = false;
@@ -471,11 +490,11 @@ public static class BrepMassProperties
}
case CurveGeometryKind.Circle3 when curve.Circle3 is { } circle && System.Math.Abs(circle.Normal.ToVector().Z) > 1d - 1e-8d:
{
+ // Chord plus circular segment: independent of where the circle's parameter starts.
var sign = circle.Normal.ToVector().Z >= 0d ? 1d : -1d;
- var a = start * sign; var b = end * sign;
- areaTwice = (circle.Center.X * circle.Radius * (System.Math.Sin(b) - System.Math.Sin(a)))
- - (circle.Center.Y * circle.Radius * (System.Math.Cos(b) - System.Math.Cos(a)))
- + (circle.Radius * circle.Radius * (b - a));
+ var sweep = (end - start) * sign;
+ var p = circle.Evaluate(start); var q = circle.Evaluate(end);
+ areaTwice = (p.X * q.Y - q.X * p.Y) + circle.Radius * circle.Radius * (sweep - System.Math.Sin(sweep));
return true;
}
default:
diff --git a/Aetheris.Kernel.Firmament.Tests/ComposeHollowTests.cs b/Aetheris.Kernel.Firmament.Tests/ComposeHollowTests.cs
new file mode 100644
index 00000000..635f6554
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/ComposeHollowTests.cs
@@ -0,0 +1,97 @@
+using Aetheris.Kernel.Core.Brep.Verification;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament.Materializer;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class ComposeHollowTests
+{
+ private static double RoundedRect(double w, double h, double r) => w * h - (4d - double.Pi) * r * r;
+
+ public static TheoryData<string, double> Canonical => new()
+ {
+ // Exterior minus cavity, from the closed forms of each section.
+ { "rounded-tray", RoundedRect(120, 80, 12) * 24 - RoundedRect(116, 76, 10) * 22 },
+ {
+ "enclosure-boss-pocket",
+ RoundedRect(100, 60, 8) * 20 + RoundedRect(30, 30, 6) * 12 - 20 * 24 * 6
+ - (RoundedRect(96, 56, 6) * 12 + (RoundedRect(96, 56, 6) - RoundedRect(24, 28, 2)) * 6 + RoundedRect(26, 26, 4) * 12)
+ },
+ // The reflex corner adds the square of the wall less a quarter disc; the bore's tube grows it by the wall.
+ { "bracket-tray", (1275 - 9 * double.Pi) * 15 - (891 + 4 - double.Pi - 25 * double.Pi) * 13 },
+ };
+
+ [Theory]
+ [MemberData(nameof(Canonical))]
+ public void HollowSectionStacksBuildAtConstantWall(string fixture, double expectedVolume)
+ {
+ var built = FirmamentBuildAndExport.CompileSource(File.ReadAllText(Fixture("Canonical", fixture)));
+ Assert.True(built.IsSuccess, string.Join(Environment.NewLine, built.Diagnostics.Select(d => d.Message)));
+ var imported = Step242Importer.ImportBody(built.Value.StepText);
+ Assert.True(imported.IsSuccess, string.Join(Environment.NewLine, imported.Diagnostics.Select(d => d.Message)));
+ var enclosure = BrepMassProperties.EvaluateEnclosure(imported.Value);
+ Assert.True(enclosure.IsEnclosed && enclosure.IsOrientationConsistent, string.Join(" | ", enclosure.Diagnostics));
+ var volume = BrepMassProperties.Evaluate(imported.Value, new(0.01d, double.Pi / 90d, 1d, MaximumSegments: 256)).AbsoluteVolume;
+ Assert.InRange(volume, expectedVolume * (1 - 2e-4), expectedVolume * (1 + 2e-4));
+ }
+
+ [Theory]
+ [InlineData("narrow-neck", "hollow-wall-offset-collapse")]
+ [InlineData("closed-vessel", "firmament-v2-hollow-closed-vessel-unsupported")]
+ [InlineData("side-opening", "firmament-v2-hollow-opening-unsupported")]
+ public void HollowRefusalsNameTheirCause(string fixture, string code)
+ {
+ var built = FirmamentBuildAndExport.CompileSource(File.ReadAllText(Fixture("Invalid", fixture)));
+ Assert.False(built.IsSuccess);
+ Assert.Contains(built.Diagnostics, d => d.Message.Contains(code, StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void ConvexArcsNoLargerThanTheWallVanishIntoSharpCorners()
+ {
+ // A 20 x 10 rounded rectangle with 1mm corners, inset by 2mm, is a sharp 16 x 6 rectangle.
+ var diagnostics = new List<string>();
+ var loop = ProfileInset2D.InsetLoop(RoundedRectangle(20, 10, 1), 2, outer: true, "test", diagnostics);
+ Assert.NotNull(loop);
+ Assert.Equal(4, loop!.Count);
+ Assert.All(loop, curve => Assert.IsType<LineArcLineSegment2D>(curve));
+ Assert.Equal(96d, ProfileInset2D.SignedArea(loop), 9);
+ }
+
+ [Fact]
+ public void ConvexArcsLargerThanTheWallStayConcentric()
+ {
+ var diagnostics = new List<string>();
+ var loop = ProfileInset2D.InsetLoop(RoundedRectangle(20, 10, 3), 2, outer: true, "test", diagnostics);
+ Assert.NotNull(loop);
+ Assert.Equal(RoundedRect(16, 6, 1), ProfileInset2D.SignedArea(loop!), 9);
+ Assert.All(loop!.OfType<LineArcCircularArc2D>(), arc => Assert.Equal(1d, arc.Radius, 12));
+ }
+
+ [Fact]
+ public void HoleLoopsGrowByTheWall()
+ {
+ var diagnostics = new List<string>();
+ var loop = ProfileInset2D.InsetLoop([new LineArcFullCircle2D((0, 0), 3)], 2, outer: false, "test", diagnostics);
+ Assert.Equal(5d, Assert.IsType<LineArcFullCircle2D>(Assert.Single(loop!)).Radius, 12);
+ }
+
+ private static IReadOnlyList<LineArcProfileCurve2D> RoundedRectangle(double w, double h, double r)
+ {
+ var (x, y) = (w / 2, h / 2);
+ return
+ [
+ new LineArcLineSegment2D((-x + r, -y), (x - r, -y)),
+ new LineArcCircularArc2D((x - r, -y + r), r, -double.Pi / 2, double.Pi / 2),
+ new LineArcLineSegment2D((x, -y + r), (x, y - r)),
+ new LineArcCircularArc2D((x - r, y - r), r, 0, double.Pi / 2),
+ new LineArcLineSegment2D((x - r, y), (-x + r, y)),
+ new LineArcCircularArc2D((-x + r, y - r), r, double.Pi / 2, double.Pi / 2),
+ new LineArcLineSegment2D((-x, y - r), (-x, -y + r)),
+ new LineArcCircularArc2D((-x + r, -y + r), r, double.Pi, double.Pi / 2),
+ ];
+ }
+
+ private static string Fixture(string kind, string name) =>
+ Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, $"../../../../fixtures/{kind}/Hollow/{name}.firmament"));
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index 8eb0a867..686bb3fa 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -1230,13 +1230,22 @@ public static partial class FirmamentV2Parser
/// Rewrites <c>Extrude X { profile: P; from: a; to: b }</c> as <c>Compose X { Base X { ... } }</c> in the
/// adapter source. Field text is carried verbatim, so expressions and unknown fields report as they would on Base.
/// </summary>
+ private static bool IsHollowExtrude(DeclarationSyntax d) => d.Type.Name.Text == "Extrude" && d.Type.Arguments.Count == 1
+ && FirmamentSyntaxValues.Reference(d.Type.Arguments[0].Value) == "Hollow";
+
private static string ExtrudeAsCompose(string adapterSource, DeclarationSyntax extrude, int shift, string source)
{
var start = extrude.Span.Start + shift;
- var fields = string.Join("; ", (extrude.Body?.Statements.OfType<FieldSyntax>() ?? [])
- .Select(f => $"{f.Name.Text}: {source.Substring(f.Value.Span.Start, f.Value.Span.Length)}"));
+ // A hollow extrude is a hollow one-slab Compose: its wall fields belong to the Compose.
+ var hollow = IsHollowExtrude(extrude);
+ static bool WallField(FieldSyntax f) => FirmamentSyntaxFields.SameField(f.Name.Text, "WallThickness") || FirmamentSyntaxFields.SameField(f.Name.Text, "Openings");
+ string Fields(IEnumerable<FieldSyntax> items) => string.Join("; ", items.Select(f => $"{f.Name.Text}: {source.Substring(f.Value.Span.Start, f.Value.Span.Length)}"));
+ var all = extrude.Body?.Statements.OfType<FieldSyntax>().ToArray() ?? [];
+ var fields = Fields(all.Where(f => !hollow || !WallField(f)));
var name = extrude.Name?.Text ?? "Body";
- var text = $"Compose {name} {{ Base {name} {{ {fields} }} }}";
+ var text = hollow
+ ? $"Compose<Hollow> {name} {{ {Fields(all.Where(WallField))}; Base {name} {{ {fields} }} }}"
+ : $"Compose {name} {{ Base {name} {{ {fields} }} }}";
if (start < 0 || start + extrude.Span.Length > adapterSource.Length
|| adapterSource.Substring(start, extrude.Span.Length) != source.Substring(extrude.Span.Start, extrude.Span.Length))
throw new InvalidOperationException("Extrude declaration does not map into the adapter source.");
@@ -1271,8 +1280,8 @@ public static partial class FirmamentV2Parser
// Compose { Base }; give it that construction so its Modify features are cut.
// Edge finishes alone keep the plain profile route, which owns them.
if (declarations.Count(d => d.Type.Name.Text == "Extrude") == 1 && declarations.All(d => d.Type.Name.Text != "Compose")
- && declarations.Where(d => d.Type.Name.Text == "Modify").SelectMany(d => d.Body?.Statements.OfType<DeclarationSyntax>() ?? [])
- .Any(d => d.Type.Name.Text != "EdgeFinish"))
+ && (declarations.Where(d => d.Type.Name.Text == "Modify").SelectMany(d => d.Body?.Statements.OfType<DeclarationSyntax>() ?? [])
+ .Any(d => d.Type.Name.Text != "EdgeFinish") || declarations.Any(IsHollowExtrude)))
{
var extrude = declarations.Single(d => d.Type.Name.Text == "Extrude");
adapterSource = ExtrudeAsCompose(adapterSource, extrude, model.Span.Start - bodySpan.Start, source);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringDeclarations.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringDeclarations.cs
index 0246bcdd..2d3d30a8 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringDeclarations.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringDeclarations.cs
@@ -13,10 +13,14 @@ public static class ProfileSemanticDeclaration { }
[FirmamentField("Profile", "Profile", FirmamentSchemaValueKind.Profile, Required = true, Description = "Name of the Profile to extrude.")]
[FirmamentField("From", "From", FirmamentSchemaValueKind.Length, Required = true, Description = "Start height along the layout normal.")]
[FirmamentField("To", "To", FirmamentSchemaValueKind.Length, Required = true, Description = "End height; greater than From.")]
+[FirmamentField("WallThickness", "WallThickness", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Variants = ["Hollow"], Description = "Extrude<Hollow>: the constant wall of the hollow prism.")]
+[FirmamentField("Openings", "Openings", FirmamentSchemaValueKind.String, Variants = ["Hollow"], Description = "Extrude<Hollow>: end caps the cavity runs out through, [Top], [Bottom] or both; omit for a closed vessel.")]
public static class ExtrudeSemanticDeclaration { }
[FirmamentConstruct("Compose", "Compose", Context = "Model", Entry = "Compose Plate {\n Base Stock { Profile: Outline; From: 0mm; To: 8mm; Role: Stock }\n}",
Description = "A Profile-based body built from a Base and optional Boss, Pocket and Hole operations. A later Modify takes Hole, Slot, Pattern and qualified Profile rim finishes. A constant native-XY Base with disjoint through round holes supports top or bottom fillets/chamfers, including RoundedRect2 corners; other material histories have narrower admission. Round vertical corners in the Profile (RoundedRect2).")]
+[FirmamentField("WallThickness", "WallThickness", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Variants = ["Hollow"], Description = "Compose<Hollow>: the constant wall; the cavity is derived from the whole exterior, including its Boss and Pocket operations.")]
+[FirmamentField("Openings", "Openings", FirmamentSchemaValueKind.String, Variants = ["Hollow"], Description = "Compose<Hollow>: end caps the cavity runs out through, [Top], [Bottom] or both; omit for a closed vessel.")]
public static class ComposeSemanticDeclaration { }
[FirmamentConstruct("ComposeBase", "Base", Context = "Compose", Entry = "Base Stock { Profile: Outline; From: 0mm; To: 8mm; Role: Stock }",
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
index 6fc29df6..9e82259b 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
@@ -1520,6 +1520,12 @@ public static class ProfileAuthoringParser
var to = fields.Take("To");
fields.CheckUnit("From", from, "mm");
fields.CheckUnit("To", to, "mm");
+ // Extrude<Hollow> carries its wall; the hollow Compose it lowers to validates the values.
+ if (declaration.Type.Arguments.Count == 1 && FirmamentSyntaxValues.Reference(declaration.Type.Arguments[0].Value) == "Hollow")
+ {
+ fields.CheckUnit("WallThickness", fields.Take("WallThickness"), "mm");
+ fields.Take("Openings");
+ }
fields.Complete();
return (profile, from, to);
}
diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticHollowCavity.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticHollowCavity.cs
new file mode 100644
index 00000000..3bbab4fc
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticHollowCavity.cs
@@ -0,0 +1,131 @@
+namespace Aetheris.Kernel.Firmament.Materializer;
+
+/// <summary>A section-stack body declared hollow: its wall, and which end caps the cavity runs out through.</summary>
+public sealed record PrismaticHollowIntent(double WallThickness, bool OpenTop, bool OpenBottom, string SourceSpan);
+
+/// <summary>
+/// Derives the cavity of a hollow section stack from the exterior's own construction, as more section-stack
+/// removals. The cavity is the exterior eroded by a cylinder of radius t and half-height t: in each band its
+/// section is the exact inset (<see cref="ProfileInset2D"/>) of the intersection of the exterior sections within t
+/// above and below. Walls are exactly t thick, caps exactly t, and where slabs step the corner stays sharp (the wall
+/// there reaches √2·t at a right angle). Bosses and pockets declared in the exterior are hollowed with it; holes and
+/// slots are wall features and are cut afterwards.
+/// </summary>
+public static class PrismaticHollowCavity
+{
+ private const double Tol = 1e-7;
+
+ public static PrismaticProfileCompositionParseResult? Derive(PrismaticProfileCompositionParseResult parsed, out IReadOnlyList<string> diagnostics)
+ {
+ var d = new List<string>();
+ diagnostics = d;
+ var feature = parsed.Feature!;
+ var hollow = feature.Hollow!;
+ var t = hollow.WallThickness;
+ var exteriorOperations = feature.Operations.Where(IsExterior).ToArray();
+ var exterior = new PrismaticProfileCompositionFeature(feature.Name, feature.Frame, feature.Axis, feature.Placement, exteriorOperations,
+ exteriorOperations.SelectMany(o => new[] { o.From, o.To }).Distinct().Order().ToArray(), feature.Provenance);
+ var stack = PrismaticSectionStackCompiler.Normalize(new(exterior, parsed.Profiles, []), out var exteriorDiagnostics);
+ if (stack is null || stack.Slabs.Count == 0)
+ {
+ d.AddRange(exteriorDiagnostics);
+ d.Add("hollow-exterior-invalid");
+ return null;
+ }
+ var slabs = stack.Slabs;
+ var bottom = slabs.Min(s => s.From);
+ var top = slabs.Max(s => s.To);
+ var low = hollow.OpenBottom ? bottom : bottom + t;
+ var high = hollow.OpenTop ? top : top - t;
+ if (high - low <= Tol)
+ {
+ d.Add($"hollow-wall-offset-collapse:{feature.Name}: the body is {top - bottom:R} tall, too short for {(hollow.OpenTop || hollow.OpenBottom ? 1 : 2)} wall(s) of {t:R}");
+ return null;
+ }
+ var breaks = slabs.SelectMany(s => new[] { s.From - t, s.From + t, s.To - t, s.To + t })
+ .Append(low).Append(high).Where(z => z >= low - Tol && z <= high + Tol)
+ .Select(z => double.Clamp(z, low, high)).Order().ToList();
+ var levels = new List<double>();
+ foreach (var z in breaks) if (levels.Count == 0 || z - levels[^1] > Tol) levels.Add(z);
+
+ var profiles = parsed.Profiles.ToDictionary(p => p.Key, p => p.Value, StringComparer.Ordinal);
+ var cavities = new List<PrismaticProfileOperation>();
+ int[]? previousSet = null;
+ List<PrismaticProfileOperation> previousOps = [];
+ for (var band = 0; band + 1 < levels.Count; band++)
+ {
+ var (a, b) = (levels[band], levels[band + 1]);
+ var windowLow = hollow.OpenBottom ? double.Max(a - t, bottom) : a - t;
+ var windowHigh = hollow.OpenTop ? double.Min(b + t, top) : b + t;
+ var set = Enumerable.Range(0, slabs.Count).Where(i => slabs[i].From < windowHigh - Tol && slabs[i].To > windowLow + Tol).ToArray();
+ // A window the slabs do not cover reaches outside the body: no cavity in this band.
+ var covered = windowLow;
+ foreach (var i in set.OrderBy(i => slabs[i].From))
+ if (slabs[i].From <= covered + Tol) covered = double.Max(covered, slabs[i].To);
+ if (set.Length == 0 || covered < windowHigh - Tol) { previousSet = null; previousOps = []; continue; }
+ // When one slab's section lies inside all the others, the intersection is that section itself: use it
+ // directly, so neighbouring bands with the same governing section merge into one removal.
+ var areas = set.Select(i => slabs[i].MaterialRegions.Sum(PrismaticSectionStackCompiler.Area)).ToArray();
+ IReadOnlyList<PrismaticSectionRegion> regions;
+ int[] key;
+ var smallest = set[Array.IndexOf(areas, areas.Min())];
+ if (set.Select(i => slabs[i].MaterialRegions).Distinct().Count() == 1)
+ {
+ regions = slabs[smallest].MaterialRegions;
+ key = [smallest];
+ }
+ else
+ {
+ var intersection = ProfileArrangementBuilder.Intersection(feature.Frame, set.Select(i => slabs[i].MaterialRegions).ToArray(),
+ $"hollow:{feature.Name}:band={a:R}..{b:R}");
+ d.AddRange(intersection.Arrangement.Diagnostics.Where(x => x.Contains("rejected", StringComparison.Ordinal)));
+ var area = intersection.MaterialRegions.Sum(PrismaticSectionStackCompiler.Area);
+ if (double.Abs(area - areas.Min()) <= 1e-6 * double.Max(1d, area))
+ {
+ regions = slabs[smallest].MaterialRegions;
+ key = [smallest];
+ }
+ else
+ {
+ regions = intersection.MaterialRegions;
+ key = set;
+ }
+ }
+ if (previousSet is not null && previousSet.SequenceEqual(key))
+ {
+ for (var k = 0; k < previousOps.Count; k++)
+ {
+ var index = cavities.IndexOf(previousOps[k]);
+ cavities[index] = previousOps[k] = previousOps[k] with { To = b };
+ }
+ continue;
+ }
+ previousSet = key;
+ previousOps = [];
+ for (var r = 0; r < regions.Count; r++)
+ {
+ var name = $"{feature.Name}Cavity{cavities.Count}";
+ var inset = ProfileInset2D.Inset(regions[r], t, name, $"{feature.Name}:band={a:R}..{b:R}:region{r}");
+ if (inset.Profile is null) { d.AddRange(inset.Diagnostics); return null; }
+ profiles[name] = inset.Profile;
+ var operation = new PrismaticProfileOperation(name, PrismaticProfileIntent.Remove, name, a, b, "HollowCavity",
+ hollow.SourceSpan, $"hollow:{feature.Name}", "Hollow");
+ cavities.Add(operation);
+ previousOps.Add(operation);
+ }
+ }
+ if (cavities.Count == 0)
+ {
+ d.Add($"hollow-wall-offset-collapse:{feature.Name}: no section is wider than twice the wall {t:R}");
+ return null;
+ }
+ var operations = feature.Operations.Concat(cavities).ToArray();
+ var critical = feature.CriticalLevels.Concat(cavities.SelectMany(o => new[] { o.From, o.To })).Order().ToList();
+ var merged = new List<double>();
+ foreach (var z in critical) if (merged.Count == 0 || z - merged[^1] > Tol) merged.Add(z);
+ return new(feature with { Operations = operations, CriticalLevels = merged, Hollow = null }, profiles, parsed.Diagnostics, parsed.Expansion);
+ }
+
+ private static bool IsExterior(PrismaticProfileOperation operation) =>
+ operation.SemanticFeatureKind is null or "Boss" or "Pocket";
+}
diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs
index ff9840aa..16e4751c 100644
--- a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs
@@ -165,6 +165,9 @@ public sealed record PrismaticProfileCompositionFeature(
IReadOnlyList<PrismaticMaterialOffsetFeature>? MaterialOffsets = null,
IReadOnlyList<PrismaticCountersinkHoleFeature>? CountersinkHoles = null)
{
+ /// <summary>Set when the body is declared hollow; normalization derives the cavity from the exterior.</summary>
+ public PrismaticHollowIntent? Hollow { get; init; }
+
public IEnumerable<(string Name, string StableId, string ProfileReference)> AllSlotProfiles =>
(CapsuleSlots ?? []).Select(x => (x.Name, x.StableId, x.ProfileReference))
.Concat((RoundedRectangleSlots ?? []).Select(x => (x.Name, x.StableId, x.ProfileReference)));
@@ -331,8 +334,27 @@ public static class PrismaticProfileCompositionParser
var authoredProfiles = profiles.Keys.ToHashSet(StringComparer.Ordinal);
var compose = FirmamentSyntaxTraversal.Declarations(syntax.Document).FirstOrDefault(d => d.Type.Name.Text == "Compose");
if (compose?.Body is null || compose.Name is null) return new(null, profiles, diagnostics.Append("compose-source-missing-compose").ToArray());
- if (compose.Clauses.Count > 0 || compose.Type.Arguments.Count > 0)
+ var hollowCompose = compose.Type.Arguments.Count == 1 && FirmamentSyntaxValues.Reference(compose.Type.Arguments[0].Value) == "Hollow";
+ if (compose.Clauses.Count > 0 || compose.Type.Arguments.Count > 0 && !hollowCompose)
return new(null, profiles, diagnostics.Append("compose-header-unsupported: Declare a supported Placement block inside Compose.").ToArray());
+ PrismaticHollowIntent? hollow = null;
+ if (hollowCompose)
+ {
+ var hollowFields = compose.Body.Statements.OfType<FieldSyntax>().ToArray();
+ var wallField = hollowFields.FirstOrDefault(f => FirmamentSyntaxFields.SameField(f.Name.Text, "WallThickness"));
+ var openingsField = hollowFields.FirstOrDefault(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Openings"));
+ var wall = FirmamentSyntaxValues.TryMeasure(wallField?.Value, "mm", out var w) ? w : double.NaN;
+ if (wallField is null) diagnostics.Add("firmament-v2-hollow-wall-thickness-required: Compose<Hollow> requires wallThickness.");
+ else if (!(wall > 0d)) diagnostics.Add("firmament-v2-hollow-wall-thickness-must-be-positive");
+ var openings = (openingsField?.Value as SequenceSyntax)?.Items.Select(a => FirmamentSyntaxValues.Reference(a.Value)).ToArray() ?? [];
+ if (openings.Any(o => o is not ("Top" or "Bottom")) || openings.Distinct().Count() != openings.Length)
+ diagnostics.Add("firmament-v2-hollow-opening-unsupported: Compose<Hollow> openings are Top and/or Bottom; cut other openings with Modify features.");
+ if (openings.Length == 0)
+ diagnostics.Add("firmament-v2-hollow-closed-vessel-unsupported: A closed hollow needs an inner void shell, which the section stack does not build yet; open Top or Bottom.");
+ foreach (var extra in hollowFields.Where(f => f != wallField && f != openingsField))
+ diagnostics.Add($"{FirmamentV2Parser.CanonicalDeclarationUnknown}:Compose:{extra.Name.Text}");
+ hollow = new(wall, openings.Contains("Top"), openings.Contains("Bottom"), $"offset:{compose.Span.Start}");
+ }
var composeBody = source.Substring(compose.Body.Span.Start + 1, compose.Body.Span.Length - 2);
composeBody = BindExternalModifyFeatures(source, compose.Name.Text, composeBody, diagnostics);
var beforeAdmission = diagnostics.Count;
@@ -343,6 +365,8 @@ public static class PrismaticProfileCompositionParser
diagnostics.Add($"firmament-v2-field-duplicate:{declaration.Type.Name.Text}:{repeated.Key}");
foreach (var statement in operationsSyntax.Document.Statements)
{
+ if (hollow is not null && statement is FieldSyntax hollowField
+ && (FirmamentSyntaxFields.SameField(hollowField.Name.Text, "WallThickness") || FirmamentSyntaxFields.SameField(hollowField.Name.Text, "Openings"))) continue;
if (statement is DeclarationSyntax declared && declared.Type.Name.Text is
"Base" or "Add" or "Remove" or "Boss" or "Pocket" or "AddOffset" or "RemoveOffset" or "Hole" or "Slot" or "EdgeFinish" or "Placement" or "Point2" or "Line2" or "Circle2" or "Path" or "Profile" or "Rect2" or "Axis2" or "Plane") continue;
diagnostics.Add($"{FirmamentV2Parser.CanonicalDeclarationUnknown}:Compose:{(statement as DeclarationSyntax)?.Type.Name.Text ?? "expression"}");
@@ -883,7 +907,7 @@ public static class PrismaticProfileCompositionParser
diagnostics.Add($"compose-profile-frame-mismatch:{operation.Name}:{operation.ProfileReference}: All operands must use the same construction frame; an explicit Placement cannot override an oriented Profile.");
}
var levels = operations.SelectMany(o => new[] { o.From, o.To }).Concat(countersinkHoles.Select(h => h.ConeFrom)).Distinct().Order().ToArray();
- var feature = diagnostics.Count == 0 ? new PrismaticProfileCompositionFeature(compose.Name.Text, placement.ProfilePlane, placement.Axis, placement, operations, levels, "parser-backed-scaffold-profile-composition", shaftHoles, capsuleSlots, roundedRectangleSlots, constructionPlaneBlindDrills, counterboreHoles, bosses, pockets, materialOffsets, countersinkHoles) : null;
+ var feature = diagnostics.Count == 0 ? new PrismaticProfileCompositionFeature(compose.Name.Text, placement.ProfilePlane, placement.Axis, placement, operations, levels, "parser-backed-scaffold-profile-composition", shaftHoles, capsuleSlots, roundedRectangleSlots, constructionPlaneBlindDrills, counterboreHoles, bosses, pockets, materialOffsets, countersinkHoles) { Hollow = hollow } : null;
return new(feature, profiles, diagnostics.Distinct().ToArray(), expansion.Evidence);
}
diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs
index 15b4bd5c..bff58cf6 100644
--- a/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs
@@ -87,6 +87,12 @@ public static class PrismaticSectionStackCompiler
{
var d = parsed.Diagnostics.ToList();
if (parsed.Feature is null) { diagnostics = d; return null; }
+ if (parsed.Feature.Hollow is not null)
+ {
+ var hollowed = PrismaticHollowCavity.Derive(parsed, out var hollowDiagnostics);
+ if (hollowed is null) { diagnostics = d.Concat(hollowDiagnostics).Distinct().ToArray(); return null; }
+ parsed = hollowed;
+ }
// A variable cavity is legal only where its complete footprint lies in
// actual material. A Base-profile check alone misses pockets, slots,
// local height changes and disconnected material spans.
diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs
index 7296e6f4..cfb78db4 100644
--- a/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs
@@ -124,6 +124,14 @@ public static class ProfileArrangementBuilder
return Build(frame, sources, p => left.Any(region => InRegion(region, p)) && !right.Any(region => InRegion(region, p)), context, rejectAmbiguousTangencies: false, allowMultipleRegions: true);
}
+ /// <summary>Exact intersection of region sets: the points inside some region of every set.</summary>
+ public static ProfileArrangementResult Intersection(string frame, IReadOnlyList<IReadOnlyList<PrismaticSectionRegion>> sets, string context)
+ {
+ if (sets.Count == 0 || sets.Any(set => set.Count == 0)) return Empty(frame, context);
+ var sources = sets.SelectMany((set, i) => set.SelectMany((region, j) => RegionSources($"set{i}.{j}", region))).ToArray();
+ return Build(frame, sources, p => sets.All(set => set.Any(region => InRegion(region, p))), context, rejectAmbiguousTangencies: false, allowMultipleRegions: true);
+ }
+
public static ArrangementPointLocation PointInProfile(ResolvedProfile2D profile, (double X, double Y) point)
{
// A PrismaticSectionRegion stores each hole as a one-loop profile whose
@@ -405,10 +413,21 @@ public static class ProfileArrangementBuilder
if (loops.Count == 0) return [];
var result = new List<PrismaticSectionRegion>();
var inner = loops.Where(x => !x.IsOuter).ToArray();
- foreach (var outerLoop in loops.Where(x => x.IsOuter).OrderByDescending(x => x.SignedArea).ThenBy(x => x.Fragments.Min(f => f.Source.StableId), StringComparer.Ordinal))
+ var outerLoops = loops.Where(x => x.IsOuter).OrderByDescending(x => x.SignedArea).ThenBy(x => x.Fragments.Min(f => f.Source.StableId), StringComparer.Ordinal).ToArray();
+ var outerProfiles = outerLoops.Select(loop => ToProfile(loop, "Outer")).ToArray();
+ // An island inside another region's hole is itself an outer loop. Each hole belongs to the smallest outer that
+ // contains it, so a hole of the island is not also taken as a hole of the region around it.
+ var owner = inner.ToDictionary(loop => loop, loop =>
+ {
+ var start = Ends(loop.Fragments[0].Geometry).Start;
+ var containing = Enumerable.Range(0, outerLoops.Length).Where(i => PointInProfile(outerProfiles[i], start) == ArrangementPointLocation.Inside).ToArray();
+ return containing.Length == 0 ? -1 : containing.MinBy(i => double.Abs(outerLoops[i].SignedArea));
+ });
+ for (var index = 0; index < outerLoops.Length; index++)
{
- var outer = ToProfile(outerLoop, "Outer");
- var nested = inner.Where(loop => PointInProfile(outer, Ends(loop.Fragments[0].Geometry).Start) == ArrangementPointLocation.Inside).ToArray();
+ var outerLoop = outerLoops[index];
+ var outer = outerProfiles[index];
+ var nested = inner.Where(loop => owner[loop] == index).ToArray();
var holes = nested.Select((loop, index) => ToProfile(loop, $"Inner{index}")).ToArray();
result.Add(new PrismaticSectionRegion(outer, holes, outerLoop.Fragments.Concat(nested.SelectMany(x => x.Fragments))
.Select(x => x.Source.StableId).Distinct().OrderBy(x => x, StringComparer.Ordinal).ToArray()));
diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileInset2D.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileInset2D.cs
new file mode 100644
index 00000000..f53dcc7c
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileInset2D.cs
@@ -0,0 +1,318 @@
+namespace Aetheris.Kernel.Firmament.Materializer;
+
+/// <summary>
+/// Exact inward offset of a line/arc material region: every point of the result lies at least the inset distance
+/// from the region's boundary, and the result's boundary lies exactly at that distance. Lines stay parallel lines;
+/// arcs stay concentric; a reflex corner rounds with the inset distance about the corner, which keeps the wall
+/// constant; a convex arc no larger than the inset vanishes and its neighbours meet at a sharp corner. Any other
+/// collapse (a curve that reverses, a neck that closes, loops that meet) is refused with its location named.
+/// </summary>
+public static class ProfileInset2D
+{
+ private const double Tol = 1e-9;
+
+ public sealed record InsetResult(ResolvedProfile2D? Profile, IReadOnlyList<string> Diagnostics);
+
+ private abstract record Carrier;
+ private sealed record LineCarrier((double X, double Y) Point, (double X, double Y) Direction) : Carrier;
+ private sealed record CircleCarrier((double X, double Y) Center, double Radius, bool CounterClockwise) : Carrier;
+
+ private sealed class Element(Carrier carrier, (double X, double Y) start, (double X, double Y) end, double originalSweep)
+ {
+ public Carrier Carrier { get; } = carrier;
+ public (double X, double Y) Start { get; set; } = start;
+ public (double X, double Y) End { get; set; } = end;
+ public double OriginalSweep { get; } = originalSweep;
+ }
+
+ public static InsetResult Inset(PrismaticSectionRegion region, double distance, string name, string context)
+ {
+ var diagnostics = new List<string>();
+ var loops = new List<ResolvedProfileLoop2D>();
+ var outer = InsetLoop(Curves(region.Outer), distance, outer: true, context + ".outer", diagnostics);
+ if (outer is null) return new(null, diagnostics);
+ loops.Add(Loop(name, "Outer", true, outer));
+ for (var i = 0; i < region.Holes.Count; i++)
+ {
+ var hole = InsetLoop(Curves(region.Holes[i]), distance, outer: false, $"{context}.hole{i}", diagnostics);
+ if (hole is null) return new(null, diagnostics);
+ loops.Add(Loop(name, $"Hole{i}", false, hole));
+ }
+ // Loops that touch or cross would change the region's topology: a neck closed, or a hole's wall reaching the
+ // outer wall. Either way the wall would be thinner than asked somewhere.
+ var all = loops.Select(l => l.Segments.Select(s => s.Geometry).ToArray()).ToArray();
+ for (var a = 0; a < all.Length; a++)
+ for (var b = a; b < all.Length; b++)
+ for (var i = 0; i < all[a].Length; i++)
+ for (var j = a == b ? i + 1 : 0; j < all[b].Length; j++)
+ {
+ if (a == b && (j == i + 1 || (i == 0 && j == all[a].Length - 1))) continue;
+ var hit = ProfileArrangementBuilder.IntersectBounded(all[a][i], all[b][j]);
+ if (hit.Intersections.Count > 0 || hit.HasBoundedOverlap)
+ {
+ diagnostics.Add($"hollow-wall-offset-collapse:{context}:the inset wall meets itself (loop {a} curve {i}, loop {b} curve {j}); a section is narrower than twice the wall");
+ return new(null, diagnostics);
+ }
+ }
+ for (var h = 1; h < all.Length; h++)
+ if (ProfileArrangementBuilder.PointInProfile(new ResolvedProfile2D(name, region.Outer.PlaneFrame, [loops[0]]), StartPoint(all[h][0])) != ArrangementPointLocation.Inside)
+ {
+ diagnostics.Add($"hollow-wall-offset-collapse:{context}: a hole's inset wall leaves the inset outer wall");
+ return new(null, diagnostics);
+ }
+ var profile = new ResolvedProfile2D(name, region.Outer.PlaneFrame, loops, region.Outer.ConstructionPlane);
+ return new(profile, diagnostics);
+ }
+
+ /// <summary>Insets one closed loop; the material lies inside an outer loop and outside a hole loop.</summary>
+ public static IReadOnlyList<LineArcProfileCurve2D>? InsetLoop(IReadOnlyList<LineArcProfileCurve2D> curves, double distance, bool outer,
+ string context, List<string> diagnostics)
+ {
+ if (curves.Count == 1 && curves[0] is LineArcFullCircle2D circle)
+ {
+ var radius = outer ? circle.Radius - distance : circle.Radius + distance;
+ if (radius <= Tol) { diagnostics.Add($"hollow-wall-offset-collapse:{context}: a circle of radius {circle.Radius:R} closes at wall {distance:R}"); return null; }
+ return [new LineArcFullCircle2D(circle.Center, radius)];
+ }
+ if (curves.Any(c => c is not (LineArcLineSegment2D or LineArcCircularArc2D)))
+ {
+ diagnostics.Add($"hollow-offset-curve-unsupported:{context}: only lines and circular arcs have exact offsets of the same kind");
+ return null;
+ }
+ // Material on the left: an outer loop runs counter-clockwise, a hole clockwise.
+ var oriented = SignedArea(curves) > 0d == outer ? curves : Reverse(curves);
+ var elements = new List<Element?>();
+ foreach (var curve in oriented)
+ {
+ switch (curve)
+ {
+ case LineArcLineSegment2D line:
+ {
+ var d = Unit(Sub(line.End, line.Start));
+ var n = (-d.Y, d.X);
+ elements.Add(new Element(new LineCarrier(Add(line.Start, Mul(n, distance)), d),
+ Add(line.Start, Mul(n, distance)), Add(line.End, Mul(n, distance)), 0d));
+ break;
+ }
+ case LineArcCircularArc2D arc:
+ {
+ var ccw = arc.SweepAngleRadians > 0d;
+ var radius = ccw ? arc.Radius - distance : arc.Radius + distance;
+ if (radius <= Tol) { elements.Add(null); break; }
+ var a0 = arc.StartAngleRadians;
+ var a1 = a0 + arc.SweepAngleRadians;
+ elements.Add(new Element(new CircleCarrier(arc.Center, radius, ccw),
+ Polar(arc.Center, radius, a0), Polar(arc.Center, radius, a1), arc.SweepAngleRadians));
+ break;
+ }
+ }
+ }
+ var count = oriented.Count;
+ var kept = Enumerable.Range(0, count).Where(i => elements[i] is not null).ToArray();
+ if (kept.Length < 2) { diagnostics.Add($"hollow-wall-offset-collapse:{context}: the loop closes at wall {distance:R}"); return null; }
+ var result = new List<LineArcProfileCurve2D>();
+ var joins = new (double X, double Y)[kept.Length];
+ var reflexArcs = new LineArcCircularArc2D?[kept.Length];
+ for (var k = 0; k < kept.Length; k++)
+ {
+ var i = kept[k];
+ var j = kept[(k + 1) % kept.Length];
+ var first = elements[i]!;
+ var second = elements[j]!;
+ var vanishedBetween = (j - i + count) % count != 1;
+ var vertex = EndPoint(oriented[i]);
+ if (!vanishedBetween)
+ {
+ var tout = Unit(EndTangent(oriented[i]));
+ var tin = Unit(StartTangent(oriented[j]));
+ var cross = tout.X * tin.Y - tout.Y * tin.X;
+ var dot = tout.X * tin.X + tout.Y * tin.Y;
+ if (double.Abs(cross) <= 1e-9 && dot > 0d)
+ {
+ if (Distance(first.End, second.Start) > 1e-7) { diagnostics.Add($"hollow-wall-offset-collapse:{context}: tangent curves part at the inset"); return null; }
+ joins[k] = first.End;
+ continue;
+ }
+ if (double.Abs(cross) <= 1e-9) { diagnostics.Add($"hollow-wall-offset-collapse:{context}: the loop turns back on itself"); return null; }
+ if (cross < 0d)
+ {
+ // Reflex corner: the wall rounds about the corner, keeping its thickness.
+ var a0 = double.Atan2(first.End.Y - vertex.Y, first.End.X - vertex.X);
+ var a1 = double.Atan2(second.Start.Y - vertex.Y, second.Start.X - vertex.X);
+ var sweep = a1 - a0;
+ while (sweep >= 0d) sweep -= 2d * double.Pi;
+ while (sweep < -2d * double.Pi) sweep += 2d * double.Pi;
+ reflexArcs[k] = new LineArcCircularArc2D(vertex, distance, a0, sweep);
+ joins[k] = (double.NaN, double.NaN);
+ continue;
+ }
+ }
+ var expected = Mid(first.End, second.Start);
+ if (!TryIntersect(first.Carrier, second.Carrier, expected, out var point))
+ {
+ diagnostics.Add($"hollow-wall-offset-collapse:{context}: neighbouring walls no longer meet at the inset");
+ return null;
+ }
+ joins[k] = point;
+ }
+ for (var k = 0; k < kept.Length; k++)
+ {
+ var element = elements[kept[k]]!;
+ var previous = (k + kept.Length - 1) % kept.Length;
+ var start = double.IsNaN(joins[previous].X) ? element.Start : joins[previous];
+ var end = double.IsNaN(joins[k].X) ? element.End : joins[k];
+ var curve = Trim(element, start, end);
+ if (curve is null)
+ {
+ diagnostics.Add($"hollow-wall-offset-collapse:{context}: curve {kept[k]} reverses at wall {distance:R}; the section is narrower than twice the wall there");
+ return null;
+ }
+ result.Add(curve);
+ if (reflexArcs[k] is { } arc) result.Add(arc);
+ }
+ return result;
+ }
+
+ private static LineArcProfileCurve2D? Trim(Element element, (double X, double Y) start, (double X, double Y) end)
+ {
+ switch (element.Carrier)
+ {
+ case LineCarrier line:
+ var along = (end.X - start.X) * line.Direction.X + (end.Y - start.Y) * line.Direction.Y;
+ return along > 1e-9 ? new LineArcLineSegment2D(start, end) : null;
+ case CircleCarrier circle:
+ var a0 = double.Atan2(start.Y - circle.Center.Y, start.X - circle.Center.X);
+ var a1 = double.Atan2(end.Y - circle.Center.Y, end.X - circle.Center.X);
+ var sweep = a1 - a0;
+ // The trimmed span is the branch nearest the original one; a different sign means it reversed.
+ var best = sweep;
+ for (var k = -2; k <= 2; k++)
+ if (double.Abs(sweep + 2d * double.Pi * k - element.OriginalSweep) < double.Abs(best - element.OriginalSweep))
+ best = sweep + 2d * double.Pi * k;
+ if (double.Sign(best) != double.Sign(element.OriginalSweep) || double.Abs(best) <= 1e-9) return null;
+ return new LineArcCircularArc2D(circle.Center, circle.Radius, a0, best);
+ default:
+ return null;
+ }
+ }
+
+ private static bool TryIntersect(Carrier first, Carrier second, (double X, double Y) expected, out (double X, double Y) point)
+ {
+ var candidates = new List<(double X, double Y)>();
+ switch (first, second)
+ {
+ case (LineCarrier a, LineCarrier b):
+ {
+ var den = a.Direction.X * b.Direction.Y - a.Direction.Y * b.Direction.X;
+ if (double.Abs(den) > 1e-12)
+ {
+ var w = Sub(b.Point, a.Point);
+ var s = (w.X * b.Direction.Y - w.Y * b.Direction.X) / den;
+ candidates.Add(Add(a.Point, Mul(a.Direction, s)));
+ }
+ break;
+ }
+ case (LineCarrier a, CircleCarrier c): candidates.AddRange(LineCircle(a, c)); break;
+ case (CircleCarrier c, LineCarrier a): candidates.AddRange(LineCircle(a, c)); break;
+ case (CircleCarrier a, CircleCarrier b): candidates.AddRange(CircleCircle(a, b)); break;
+ }
+ if (candidates.Count == 0) { point = default; return false; }
+ point = candidates.MinBy(c => Distance(c, expected));
+ return true;
+ }
+
+ private static IEnumerable<(double X, double Y)> LineCircle(LineCarrier line, CircleCarrier circle)
+ {
+ var w = Sub(line.Point, circle.Center);
+ var b = w.X * line.Direction.X + w.Y * line.Direction.Y;
+ var c = w.X * w.X + w.Y * w.Y - circle.Radius * circle.Radius;
+ var disc = b * b - c;
+ if (disc < -1e-12) yield break;
+ var root = double.Sqrt(double.Max(0d, disc));
+ yield return Add(line.Point, Mul(line.Direction, -b - root));
+ yield return Add(line.Point, Mul(line.Direction, -b + root));
+ }
+
+ private static IEnumerable<(double X, double Y)> CircleCircle(CircleCarrier a, CircleCarrier b)
+ {
+ var d = Distance(a.Center, b.Center);
+ if (d < 1e-12 || d > a.Radius + b.Radius + 1e-12 || d < double.Abs(a.Radius - b.Radius) - 1e-12) yield break;
+ var x = (d * d + a.Radius * a.Radius - b.Radius * b.Radius) / (2d * d);
+ var h = double.Sqrt(double.Max(0d, a.Radius * a.Radius - x * x));
+ var u = Mul(Sub(b.Center, a.Center), 1d / d);
+ var mid = Add(a.Center, Mul(u, x));
+ yield return Add(mid, Mul((-u.Y, u.X), h));
+ yield return Add(mid, Mul((u.Y, -u.X), h));
+ }
+
+ private static ResolvedProfileLoop2D Loop(string name, string loop, bool isOuter, IReadOnlyList<LineArcProfileCurve2D> curves) =>
+ new($"{name}.{loop}", isOuter, curves.Select((curve, i) => new ResolvedProfileSegment2D($"{name}.{loop}.{i}", curve,
+ new ProfileSegmentProvenance($"hollow:{name}.{loop}.{i}", $"hollow:{name}", "generated", "hollow-inset", "XY"))).ToArray());
+
+ private static IReadOnlyList<LineArcProfileCurve2D> Curves(ResolvedProfile2D profile) =>
+ profile.Loops[0].Segments.Select(s => s.Geometry).ToArray();
+
+ private static IReadOnlyList<LineArcProfileCurve2D> Reverse(IReadOnlyList<LineArcProfileCurve2D> curves) =>
+ curves.Reverse().Select(c => c switch
+ {
+ LineArcLineSegment2D line => (LineArcProfileCurve2D)new LineArcLineSegment2D(line.End, line.Start),
+ LineArcCircularArc2D arc => new LineArcCircularArc2D(arc.Center, arc.Radius, arc.StartAngleRadians + arc.SweepAngleRadians, -arc.SweepAngleRadians),
+ _ => c
+ }).ToArray();
+
+ public static double SignedArea(IReadOnlyList<LineArcProfileCurve2D> curves)
+ {
+ var sum = 0d;
+ foreach (var curve in curves)
+ sum += curve switch
+ {
+ LineArcLineSegment2D line => line.Start.X * line.End.Y - line.End.X * line.Start.Y,
+ LineArcCircularArc2D arc => ArcDoubleArea(arc),
+ LineArcFullCircle2D circle => 2d * double.Pi * circle.Radius * circle.Radius,
+ _ => 0d
+ };
+ return sum / 2d;
+ }
+
+ private static double ArcDoubleArea(LineArcCircularArc2D arc)
+ {
+ var a = arc.StartAngleRadians; var b = a + arc.SweepAngleRadians; var r = arc.Radius; var (x, y) = arc.Center;
+ return x * r * (double.Sin(b) - double.Sin(a)) - y * r * (double.Cos(b) - double.Cos(a)) + r * r * (b - a);
+ }
+
+ private static (double X, double Y) StartPoint(LineArcProfileCurve2D curve) => curve switch
+ {
+ LineArcLineSegment2D line => line.Start,
+ LineArcCircularArc2D arc => Polar(arc.Center, arc.Radius, arc.StartAngleRadians),
+ LineArcFullCircle2D circle => (circle.Center.X + circle.Radius, circle.Center.Y),
+ _ => throw new NotSupportedException()
+ };
+ private static (double X, double Y) EndPoint(LineArcProfileCurve2D curve) => curve switch
+ {
+ LineArcLineSegment2D line => line.End,
+ LineArcCircularArc2D arc => Polar(arc.Center, arc.Radius, arc.StartAngleRadians + arc.SweepAngleRadians),
+ _ => throw new NotSupportedException()
+ };
+ private static (double X, double Y) StartTangent(LineArcProfileCurve2D curve) => curve switch
+ {
+ LineArcLineSegment2D line => Sub(line.End, line.Start),
+ LineArcCircularArc2D arc => ArcTangent(arc, arc.StartAngleRadians),
+ _ => throw new NotSupportedException()
+ };
+ private static (double X, double Y) EndTangent(LineArcProfileCurve2D curve) => curve switch
+ {
+ LineArcLineSegment2D line => Sub(line.End, line.Start),
+ LineArcCircularArc2D arc => ArcTangent(arc, arc.StartAngleRadians + arc.SweepAngleRadians),
+ _ => throw new NotSupportedException()
+ };
+ private static (double X, double Y) ArcTangent(LineArcCircularArc2D arc, double angle) =>
+ Mul((-double.Sin(angle), double.Cos(angle)), double.Sign(arc.SweepAngleRadians));
+
+ private static (double X, double Y) Polar((double X, double Y) c, double r, double a) => (c.X + r * double.Cos(a), c.Y + r * double.Sin(a));
+ private static (double X, double Y) Add((double X, double Y) a, (double X, double Y) b) => (a.X + b.X, a.Y + b.Y);
+ private static (double X, double Y) Sub((double X, double Y) a, (double X, double Y) b) => (a.X - b.X, a.Y - b.Y);
+ private static (double X, double Y) Mul((double X, double Y) a, double s) => (a.X * s, a.Y * s);
+ private static (double X, double Y) Mid((double X, double Y) a, (double X, double Y) b) => ((a.X + b.X) / 2d, (a.Y + b.Y) / 2d);
+ private static double Distance((double X, double Y) a, (double X, double Y) b) => double.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y));
+ private static (double X, double Y) Unit((double X, double Y) v) { var l = double.Sqrt(v.X * v.X + v.Y * v.Y); return (v.X / l, v.Y / l); }
+}
diff --git a/docs/development/reports/2026-11/HOLLOW-GENERALIZATION.md b/docs/development/reports/2026-11/HOLLOW-GENERALIZATION.md
index 7e8f811e..4f10b315 100644
--- a/docs/development/reports/2026-11/HOLLOW-GENERALIZATION.md
+++ b/docs/development/reports/2026-11/HOLLOW-GENERALIZATION.md
@@ -94,3 +94,45 @@ lives; its `Exterior` stops being frustum parameters and becomes any `HollowCons
sharp like commercial shell? Between slabs, sharp is proposed so the cavity stays a section stack.
2. **Exterior features.** A boss declared in the exterior program is hollowed with it (proposed);
a boss added by `Modify` after the hollow stays solid.
+
+## Decisions taken
+
+Both as proposed: in-plane reflex corners round at the wall (constant thickness), slab steps stay sharp; a
+boss in the exterior program is hollowed with it, features added afterwards are not.
+
+## Implementation status
+
+Phases 1 and 2 are in.
+
+- `ProfileInset2D`: exact inset of line/arc regions. Lines parallel, arcs concentric, reflex corners round at t,
+ convex arcs of r ≤ t vanish into sharp corners; reversal, self-contact and hole/outer contact are refused.
+- `PrismaticHollowCavity`: the cavity is the exterior eroded by a cylinder of radius t and half-height t. Bands
+ break at every slab level ± t; each band's section is the inset of the intersection of the exterior sections
+ within t of it. Bands governed by the same section merge into one `Remove`. The result lowers through the
+ unchanged section-stack emitter.
+- `Compose<Hollow>` (`wallThickness`, `openings: [Top|Bottom]`) and `Extrude<Hollow>`, which lowers to a one-`Base`
+ hollow Compose.
+- Closed vessels are refused: the cavity would be a second (void) shell, which the stack emitter rejects as a
+ disconnected solid.
+
+Two defects found and fixed on the way:
+
+- `ProfileArrangementBuilder.ToRegions` gave a hole to every outer loop containing it. An island inside another
+ region's hole (the ring of wall around a pocket inside a hollow body) then shared its hole with the region around
+ it, and the emitter duplicated those walls. Each hole now belongs to the smallest containing outer.
+- `BrepMassProperties`' exact vertical-prism lane decided loop nesting from the average of a loop's vertices. For
+ concentric walls that point lies inside the inner wall, so the outer wall was subtracted; with three loops the
+ wrong sum stayed positive and was reported as an exact volume (29274 mm³ for an 8128 mm³ tray). Nesting now uses a
+ point on the loop against the other loops traced along their arcs. Its arc area also assumed every circle's
+ parameter starts at +X; it now uses chord plus segment.
+
+Evidence: rounded tray, enclosure lid with boss and pocket, and L-bracket tray with a through bore build as single
+valid solids in OCCT, with volumes equal to closed forms (35369.8, 26302.9, 8127.7 mm³). The rounded tray matches
+the bespoke `RoundedBox<Hollow>` planner's volume exactly (26 faces there, 27 here: the stack splits the outer walls
+at the floor level).
+
+## Next
+
+Phase 3 (desugaring `RoundedBox`/`Cylinder<Hollow>` and retiring their planners) is coupled to Perforation, which
+consumes `ThinWalledBodyRealization` directly; it moves with Perforation onto section stacks. `Revolve<Hollow>`
+needs the revolve emitter to accept an axis-touching meridian. Phases 4 and 5 as planned.
diff --git a/docs/public/reference/language/solids-and-features.md b/docs/public/reference/language/solids-and-features.md
index d6c928d6..52d0291e 100644
--- a/docs/public/reference/language/solids-and-features.md
+++ b/docs/public/reference/language/solids-and-features.md
@@ -72,6 +72,42 @@ A Pocket always leaves a floor. Its required floor comes from
default, and the build fails when the floor would be thinner. Do not mix `depth`
or a floor requirement with `end: ThroughAll`.
+### Hollow bodies
+
+`Compose<Hollow>` and `Extrude<Hollow>` declare a thin-walled body. The cavity is
+built from the exterior's own construction, moved inward by `wallThickness`:
+
+```firmament
+Model EnclosureLid {
+ units: mm
+ Profile outline = RoundedRect2 { center: [0mm, 0mm]; size: [100mm, 60mm]; radius: 8mm }
+ Profile tower = RoundedRect2 { center: [-25mm, 0mm]; size: [30mm, 30mm]; radius: 6mm }
+ Compose<Hollow> body {
+ wallThickness: 2mm
+ openings: [Bottom]
+ Base stock { profile: outline; from: 0mm; to: 20mm; role: Stock }
+ Boss tower { on: Top; profile: tower; height: 12mm }
+ }
+}
+```
+
+- Every vertical wall and every closed cap is exactly `wallThickness` thick.
+- Profile arcs stay concentric: an outer corner of radius r becomes r − t inside,
+ and disappears into a sharp inner corner when r ≤ t. An inside corner of the
+ Profile, sharp or rounded, gets an inner round so the wall stays constant.
+- Where the section steps between heights (under a Boss, around a Pocket floor),
+ the inner corner is sharp, so the wall there is thicker, up to √2·t at a right
+ angle.
+- `Base`, `Add`, `Remove`, `Boss` and `Pocket` are the exterior and are hollowed
+ with it. `Hole` and `Slot` are cut through the finished wall.
+- `openings` lists the end caps the cavity runs out through: `[Top]`, `[Bottom]`
+ or `[Top, Bottom]` for a tube. Cut other openings with `Modify` features.
+
+The build refuses a section narrower than twice the wall
+(`hollow-wall-offset-collapse`, naming the band and loop), a Profile with
+ellipse or Bézier spans (`hollow-offset-curve-unsupported`), and a body with no
+opening, whose sealed inner void the section stack does not build yet.
+
### Coaxial primitive Compose
A coaxial `Compose` can join positive-radius `Cylinder` and `Frustum` spans without sketches or Boolean union. The first span starts at the local origin along +Z; each later span names the previous span's top support, and their joining radii must match. For example:
diff --git a/docs/public/reference/supported-features.md b/docs/public/reference/supported-features.md
index 563e5c6d..2ff472c6 100644
--- a/docs/public/reference/supported-features.md
+++ b/docs/public/reference/supported-features.md
@@ -30,7 +30,7 @@
| `AddOffset<Prism>` / `RemoveOffset<Prism>` | Bounded (Prism subset) | Explicit active Compose target, closed Profile tool, whole Top or bounded `Span<Plane>` support, `+Z` direction; Add uses positive Height, Remove uses positive Depth or ThroughAll; edge-crossing removals allowed on whole Top; Cylinder/Sphere deferred and rejected typed |
| Lower-level profile composition | Bounded | Existing prismatic `Compose` `Add`/`Remove` remains compatible for bounded blockout authoring |
| Semantic holes, slots, patterns | Bounded | Qualified shaft/counterbore/countersink and finite static pattern routes; no stable generated-instance selector |
-| Edge finishes/hollow/lattice | Bounded | Documented admitted chamfer/fillet, hollow, and cubic-truss routes; not arbitrary topology |
+| Edge finishes/hollow/lattice | Bounded | Documented admitted chamfer/fillet, hollow, and cubic-truss routes; not arbitrary topology. `Compose<Hollow>` and `Extrude<Hollow>` hollow any line/arc section stack at constant wall with Top and/or Bottom openings; see [Hollow bodies](language/solids-and-features.md#hollow-bodies) |
| Templates/Records/Static/Tables | Supported | Typed compile-time specialization, finite data, `with`, and `Require` |
| STEP AP242 export | Bounded | Deterministic single-body routes plus semantic PMI; unsupported intent fails loudly |
| Exact face graft / subdivision sculpting | Bounded | Native planar four-line face replacement by an outward bicubic graph; explicit box/sphere quad cages, Catmull-Clark refinement, creases, protected vertices, movement and scaling. MeshState exports STL/GLB with replay/provenance sidecars, never STEP; arbitrary BRep retopology and global mesh self-intersection proof are not implemented. See [sculpting](../firmament/sculpting.md). |
diff --git a/fixtures/Canonical/Hollow/bracket-tray.firmament b/fixtures/Canonical/Hollow/bracket-tray.firmament
new file mode 100644
index 00000000..0122f7c2
--- /dev/null
+++ b/fixtures/Canonical/Hollow/bracket-tray.firmament
@@ -0,0 +1,22 @@
+// An L-shaped tray with a through bore: the reflex corner rounds at the wall
+// radius, and the bore becomes a tube through the cavity.
+Model BracketTray {
+ units: mm
+
+ // Construction geometry only: nothing here is material yet.
+ Concept Struct layout on XY {
+ Polygon2<Explicit> outline {
+ points: [[0mm, 0mm], [60mm, 0mm], [60mm, 15mm], [15mm, 15mm], [15mm, 40mm], [0mm, 40mm]]
+ }
+ Circle2 bore { center: [7.5mm, 30mm]; diameter: 6mm }
+ }
+
+ // A Profile turns guides into closed loops with an inside and an outside.
+ Profile section using layout {
+ Loop Outer { outline |> TraceLoop }
+ Loop Inner { bore |> TraceLoop }
+ }
+
+ // A 15mm tall hollow prism with a 2mm wall, open at the top.
+ Extrude<Hollow> bracket { profile: section; from: 0mm; to: 15mm; wallThickness: 2mm; openings: [Top] }
+}
diff --git a/fixtures/Canonical/Hollow/enclosure-boss-pocket.firmament b/fixtures/Canonical/Hollow/enclosure-boss-pocket.firmament
new file mode 100644
index 00000000..cfa002b3
--- /dev/null
+++ b/fixtures/Canonical/Hollow/enclosure-boss-pocket.firmament
@@ -0,0 +1,15 @@
+// An enclosure lid, open underneath. The tower and the recess are part of the
+// exterior, so the cavity follows them at constant wall.
+Model EnclosureLid {
+ units: mm
+ Profile outline = RoundedRect2 { center: [0mm, 0mm]; size: [100mm, 60mm]; radius: 8mm }
+ Profile tower = RoundedRect2 { center: [-25mm, 0mm]; size: [30mm, 30mm]; radius: 6mm }
+ Profile notch = Rect2 { center: [30mm, 0mm]; size: [20mm, 24mm] }
+ Compose<Hollow> body {
+ wallThickness: 2mm
+ openings: [Bottom]
+ Base stock { profile: outline; from: 0mm; to: 20mm; role: Stock }
+ Boss tower { on: Top; profile: tower; height: 12mm }
+ Pocket recess { on: Top; profile: notch; depth: 6mm; minimumFloorThickness: 3mm }
+ }
+}
diff --git a/fixtures/Canonical/Hollow/rounded-tray.firmament b/fixtures/Canonical/Hollow/rounded-tray.firmament
new file mode 100644
index 00000000..7c0f7888
--- /dev/null
+++ b/fixtures/Canonical/Hollow/rounded-tray.firmament
@@ -0,0 +1,10 @@
+// A rounded tray: the cavity is the exterior inset by the wall, open at the top.
+Model RoundedTray {
+ units: mm
+ Profile outline = RoundedRect2 { center: [0mm, 0mm]; size: [120mm, 80mm]; radius: 12mm }
+ Compose<Hollow> body {
+ wallThickness: 2mm
+ openings: [Top]
+ Base stock { profile: outline; from: 0mm; to: 24mm; role: Stock }
+ }
+}
diff --git a/fixtures/Invalid/Hollow/closed-vessel.firmament b/fixtures/Invalid/Hollow/closed-vessel.firmament
new file mode 100644
index 00000000..05294a88
--- /dev/null
+++ b/fixtures/Invalid/Hollow/closed-vessel.firmament
@@ -0,0 +1,9 @@
+// Without an opening the cavity is a sealed void, which is not built yet.
+Model RoundedTray {
+ units: mm
+ Profile outline = RoundedRect2 { center: [0mm, 0mm]; size: [120mm, 80mm]; radius: 12mm }
+ Compose<Hollow> body {
+ wallThickness: 2mm
+ Base stock { profile: outline; from: 0mm; to: 24mm; role: Stock }
+ }
+}
diff --git a/fixtures/Invalid/Hollow/narrow-neck.firmament b/fixtures/Invalid/Hollow/narrow-neck.firmament
new file mode 100644
index 00000000..0bda7817
--- /dev/null
+++ b/fixtures/Invalid/Hollow/narrow-neck.firmament
@@ -0,0 +1,14 @@
+// The 3mm bridge is narrower than two 2mm walls: the cavity would split, so it is refused.
+Model Neck {
+ units: mm
+ Profile a = Rect2 { center: [0mm, 0mm]; size: [40mm, 40mm] }
+ Profile b = Rect2 { center: [30mm, 0mm]; size: [30mm, 3mm] }
+ Profile c = Rect2 { center: [60mm, 0mm]; size: [40mm, 40mm] }
+ Compose<Hollow> body {
+ wallThickness: 2mm
+ openings: [Top]
+ Base stock { profile: a; from: 0mm; to: 10mm; role: Stock }
+ Add bridge { profile: b; from: 0mm; to: 10mm }
+ Add other { profile: c; from: 0mm; to: 10mm }
+ }
+}
diff --git a/fixtures/Invalid/Hollow/side-opening.firmament b/fixtures/Invalid/Hollow/side-opening.firmament
new file mode 100644
index 00000000..0da18019
--- /dev/null
+++ b/fixtures/Invalid/Hollow/side-opening.firmament
@@ -0,0 +1,10 @@
+// Side openings are wall features: cut them with Modify.
+Model RoundedTray {
+ units: mm
+ Profile outline = RoundedRect2 { center: [0mm, 0mm]; size: [120mm, 80mm]; radius: 12mm }
+ Compose<Hollow> body {
+ wallThickness: 2mm
+ openings: [Side]
+ Base stock { profile: outline; from: 0mm; to: 24mm; role: Stock }
+ }
+}