Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Mold M0: pull, draft, undercut and parting review on any built part

Claudef2824025ec52
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index dea4825c..ee10f5fa 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -552,6 +552,8 @@ public static class CliRunner
}
if (domain == FirmamentCommandDomain.PlasticShell)
return RunPlasticShellBuild(sourcePath, outPath, json, stdout, stderr);
+ if (domain == FirmamentCommandDomain.Mold)
+ return RunMoldBuild(sourcePath, outPath, json, stdout, stderr);
if (domain == FirmamentCommandDomain.SheetMetal)
return RunSheetMetalAuthoredBuild(sourcePath, outPath, json, stdout, stderr);
if (domain == FirmamentCommandDomain.Sculpting)
@@ -906,6 +908,40 @@ public static class CliRunner
return 0;
}
+ /// <summary>Builds the part as an ordinary model and writes the Mold report beside its STEP. Findings are warnings or
+ /// errors according to the Mold's stage; any error fails the build.</summary>
+ private static int RunMoldBuild(string sourcePath, string? outPath, bool json, TextWriter stdout, TextWriter stderr)
+ {
+ var compile = MoldFirmament.CompileFile(sourcePath);
+ var output = compile.PartStep is null ? null : Path.GetFullPath(outPath ?? Path.ChangeExtension(sourcePath, ".step"));
+ string? reportPath = null;
+ if (output is not null)
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(output)!);
+ File.WriteAllText(output, compile.PartStep);
+ reportPath = Path.ChangeExtension(output, ".mold.json");
+ File.WriteAllText(reportPath, JsonSerializer.Serialize(new { compile.Report, diagnostics = compile.Diagnostics }, JsonOptions));
+ }
+ if (json)
+ stdout.WriteLine(JsonSerializer.Serialize(new { command = "build", success = compile.IsSuccess, input = Path.GetFullPath(sourcePath), output, report = reportPath, domain = "Mold",
+ mold = compile.Intent?.MoldName, part = compile.Intent?.PartName, stage = compile.Intent?.Stage.ToString(), summary = compile.Report?.Summary, diagnostics = compile.Diagnostics }, JsonOptions));
+ else
+ {
+ if (compile.Report is { } report)
+ {
+ var s = report.Summary;
+ stdout.WriteLine($"Mold {report.Intent.MoldName} on {report.Intent.PartName} ({report.Intent.Policy.Name}, {report.Intent.Stage}, pull {Format(report.Intent.Pull)})");
+ stdout.WriteLine($" faces {s.Faces}: {s.PositiveFaces} +pull, {s.NegativeFaces} -pull, {s.VerticalFaces} parallel, {s.StraddlingFaces} straddling; {s.DraftFailures} short of draft, {s.UndercutFaces} undercut");
+ stdout.WriteLine($" projected area {s.ProjectedArea:0.#} mm², volume {s.Volume:0.#} mm³, shot {s.ShotMass:0.##} g; parting line {report.PartingLine.EdgeIds.Count} edges" + (report.PartingLine.OnDeclaredPlane ? "" : " (off the declared plane)"));
+ }
+ if (output is not null) { stdout.WriteLine($"STEP: {output}"); stdout.WriteLine($"Report: {reportPath}"); }
+ foreach (var d in compile.Diagnostics) (d.Severity == PlasticDiagnosticSeverity.Error ? stderr : stdout).WriteLine($"{d.Severity.ToString().ToLowerInvariant()} {d.Code}: {d.Message}");
+ }
+ return compile.IsSuccess ? 0 : 1;
+
+ static string Format(Aetheris.Kernel.Core.Math.Direction3D d) => $"[{d.X:0.###}, {d.Y:0.###}, {d.Z:0.###}]";
+ }
+
private static int RunPlasticShellBuild(string sourcePath, string? outPath, bool json, TextWriter stdout, TextWriter stderr)
{
var compile = PlasticShellFirmament.CompileFile(sourcePath);
@@ -2587,6 +2623,17 @@ Model CanonicalPanel {
return sceneValid ? 0 : 1;
}
validationSource = frontend.Source;
+ if (domain == FirmamentCommandDomain.Mold)
+ {
+ if (parseOnly) return RejectParseOnly("Mold");
+ var mold = MoldFirmament.Compile(validationSource, Path.GetFullPath(sourcePath));
+ var payload = new { source = sourcePath, status = mold.IsSuccess ? "valid" : "invalid", domain = "Mold", validationLevel = mold.IsSuccess ? "Built" : "BuildRejected",
+ summary = new { fatalDiagnosticCount = mold.Diagnostics.Count(x => x.Severity == PlasticDiagnosticSeverity.Error), warningDiagnosticCount = mold.Diagnostics.Count(x => x.Severity == PlasticDiagnosticSeverity.Warning), mold.Report?.Summary },
+ diagnostics = mold.Diagnostics };
+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { moldValidation = payload }, JsonOptions));
+ else { stdout.WriteLine($"Mold validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, {payload.summary.warningDiagnosticCount} warning)"); foreach (var d in mold.Diagnostics) stderr.WriteLine($"{d.Severity.ToString().ToLowerInvariant()} {d.Code}: {d.Message}"); }
+ return mold.IsSuccess ? 0 : 1;
+ }
if (domain == FirmamentCommandDomain.PlasticShell)
{
if (parseOnly) return RejectParseOnly("PlasticShell");
diff --git a/Aetheris.CLI/FirmamentCommandRouting.cs b/Aetheris.CLI/FirmamentCommandRouting.cs
index 1ea68806..eaaa7de8 100644
--- a/Aetheris.CLI/FirmamentCommandRouting.cs
+++ b/Aetheris.CLI/FirmamentCommandRouting.cs
@@ -13,7 +13,7 @@ namespace Aetheris.CLI;
internal enum FirmamentCommandDomain
{
- Mechanical, Drawing, Analysis, Garment, Assembly, Scene, PlasticShell,
+ Mechanical, Drawing, Analysis, Garment, Assembly, Scene, PlasticShell, Mold,
Sculpting, Plateau, Piping, Structural, SectionChain, WireForm, Sweep, SheetMetal
}
@@ -29,6 +29,7 @@ internal static class FirmamentCommandRouting
if (Path.GetExtension(path).Equals(".firmasm", StringComparison.OrdinalIgnoreCase) || FirmamentLanguageAnalysisService.HasAssemblyRoot(source, path)) return FirmamentCommandDomain.Assembly;
if (Aetheris.Kernel.Firmament.Scene.SceneAuthoring.HasRoot(source)) return FirmamentCommandDomain.Scene;
if (PlasticShellFirmament.LooksLikePlasticShell(source)) return FirmamentCommandDomain.PlasticShell;
+ if (MoldFirmament.LooksLikeMold(source)) return FirmamentCommandDomain.Mold;
if (SculptingAuthoring.IsSculptingSource(source)) return FirmamentCommandDomain.Sculpting;
if (PlateauAuthoring.IsSource(source)) return FirmamentCommandDomain.Plateau;
if (PipingAuthoring.IsPipingSource(source)) return FirmamentCommandDomain.Piping;
diff --git a/Aetheris.PlasticShell.Tests/MoldTests.cs b/Aetheris.PlasticShell.Tests/MoldTests.cs
new file mode 100644
index 00000000..0b8e8246
--- /dev/null
+++ b/Aetheris.PlasticShell.Tests/MoldTests.cs
@@ -0,0 +1,91 @@
+using Aetheris.PlasticShell;
+using Xunit;
+
+namespace Aetheris.PlasticShell.Tests;
+
+public sealed class MoldTests
+{
+ private static string Fixture(string kind, string name) => Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "fixtures", kind, "Mold", name + ".firmament"));
+
+ [Fact]
+ public void DraftedCupReleasesAlongItsAxisWithNoFindings()
+ {
+ var result = MoldFirmament.CompileFile(Fixture("Canonical", "drafted-cup"));
+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics.Select(d => d.Message)));
+ Assert.Empty(result.Diagnostics);
+ var report = result.Report!;
+ // The walls are cones about the pull: their draft is exact, the cone's semi-angle.
+ var cones = report.Faces.Where(f => f.Surface == "Cone").ToArray();
+ Assert.Equal(2, cones.Length);
+ Assert.All(cones, f => Assert.Equal(double.Atan(1.397 / 40) * 180 / double.Pi, f.MinimumDraftDegrees, 9));
+ Assert.All(cones, f => Assert.Equal(MoldEvidenceStrength.ExactAnalytic, f.Strength));
+ Assert.Contains(cones, f => f.Side == MoldFaceSide.Positive);
+ Assert.Contains(cones, f => f.Side == MoldFaceSide.Negative);
+ Assert.True(report.PartingLine.OnDeclaredPlane);
+ Assert.Equal(40d, report.PartingLine.MinimumHeight, 6);
+ // Projected along the pull the cup is its rim disk.
+ Assert.InRange(report.Summary.ProjectedArea, double.Pi * 31.397 * 31.397 * (1 - 1e-3), double.Pi * 31.397 * 31.397 * (1 + 1e-3));
+ }
+
+ [Fact]
+ public void VerticalWallsAreShortOfDraftButPullClean()
+ {
+ var result = MoldFirmament.CompileFile(Fixture("Canonical", "tray-concept"));
+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics.Select(d => d.Message)));
+ var report = result.Report!;
+ Assert.Equal(0, report.Summary.UndercutFaces);
+ Assert.Equal(24, report.Summary.DraftFailures);
+ Assert.All(result.Diagnostics, d => Assert.Equal(PlasticDiagnosticSeverity.Warning, d.Severity));
+ Assert.Contains(result.Diagnostics, d => d.Code == MoldDiagnosticCodes.DraftInsufficient);
+ // The parting line is the outer edge of the rim, on the declared plane.
+ Assert.Equal(8, report.PartingLine.EdgeIds.Count);
+ Assert.True(report.PartingLine.OnDeclaredPlane);
+ var outline = 120d * 80d - (4d - double.Pi) * 144d;
+ Assert.InRange(report.Summary.ProjectedArea, outline * (1 - 1e-3), outline * (1 + 1e-3));
+ }
+
+ [Fact]
+ public void ToolingStageTurnsFindingsIntoErrors()
+ {
+ var source = File.ReadAllText(Fixture("Canonical", "tray-concept")).Replace("stage: Concept", "stage: Tooling", StringComparison.Ordinal);
+ var result = MoldFirmament.Compile(source, Fixture("Canonical", "tray-concept"));
+ Assert.False(result.IsSuccess);
+ Assert.Contains(result.Diagnostics, d => d.Code == MoldDiagnosticCodes.DraftInsufficient && d.Severity == PlasticDiagnosticSeverity.Error);
+ }
+
+ [Fact]
+ public void PolicyAndTextureRaiseTheRequiredDraftOnTheTexturedHalf()
+ {
+ var result = MoldFirmament.CompileFile(Fixture("Canonical", "cup-textured-policy"));
+ Assert.True(result.IsSuccess);
+ var report = result.Report!;
+ Assert.Equal(1.5, report.Intent.Policy.MinimumDraftDegrees, 12);
+ var failing = Assert.Single(report.Faces, f => !f.DraftSatisfied);
+ Assert.Equal(MoldFaceSide.Negative, failing.Side);
+ Assert.Equal(2.5, failing.RequiredDraftDegrees, 9);
+ Assert.Single(result.Diagnostics, d => d.Code == MoldDiagnosticCodes.DraftInsufficient);
+ }
+
+ [Theory]
+ [InlineData("bottle-shoulder-undercut", MoldDiagnosticCodes.Undercut)]
+ [InlineData("pulley-groove-undercut", MoldDiagnosticCodes.Undercut)]
+ [InlineData("unknown-material", MoldDiagnosticCodes.MaterialUnknown)]
+ public void RefusalsNameTheirCause(string fixture, string code)
+ {
+ var result = MoldFirmament.CompileFile(Fixture("Invalid", fixture));
+ Assert.False(result.IsSuccess);
+ Assert.Contains(result.Diagnostics, d => d.Code == code && d.Severity == PlasticDiagnosticSeverity.Error);
+ }
+
+ [Fact]
+ public void PulleyGrooveIsHiddenFromBothHalves()
+ {
+ var report = MoldFirmament.CompileFile(Fixture("Invalid", "pulley-groove-undercut")).Report!;
+ // The groove: its upper and lower faces and its floor. The flanges, bore and ends release.
+ var undercuts = report.Faces.Where(f => f.UndercutFraction > 0).ToArray();
+ Assert.Equal(3, undercuts.Length);
+ Assert.All(undercuts, f => Assert.Equal(1d, f.UndercutFraction));
+ Assert.Equal(["Cylinder", "Plane", "Plane"], undercuts.Select(f => f.Surface).Order());
+ Assert.All(undercuts, f => Assert.InRange(double.Hypot(f.Representative.X, f.Representative.Y), 13.9, 20.1));
+ }
+}
diff --git a/Aetheris.PlasticShell/MoldAnalysis.cs b/Aetheris.PlasticShell/MoldAnalysis.cs
new file mode 100644
index 00000000..c2a81c82
--- /dev/null
+++ b/Aetheris.PlasticShell/MoldAnalysis.cs
@@ -0,0 +1,357 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Brep.Verification;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Topology;
+
+namespace Aetheris.PlasticShell;
+
+/// <summary>
+/// Single-direction moldability of a built part against its declared pull.
+/// <list type="bullet">
+/// <item>Side and draft come from each face's outward normals against the pull: exact for planes, and for cylinders
+/// and cones whose axis is the pull; otherwise the extremes over the face's display mesh.</item>
+/// <item>A face is an undercut where steel cannot leave it along its side's pull: rays from its mesh samples along
+/// +pull (or −pull) that hit the part. Faces parallel to the pull take whichever direction is free, and the parting
+/// plane's side when both are.</item>
+/// <item>The parting line is every edge between a face of the +pull half and one of the −pull half.</item>
+/// </list>
+/// </summary>
+public static class MoldAnalysis
+{
+ private const double ParallelTolerance = 1.75e-4; // sin(0.01°): a face this close to the pull is vertical
+ private const int MaximumSamplesPerFace = 64;
+
+ public static MoldReport? Analyze(BrepBody body, MoldIntent intent, List<MoldDiagnostic> diagnostics)
+ {
+ // Rays start a few chord tolerances off the surface: neighbouring faces' meshes may sample a shared curved edge
+ // differently, and their chords overhang each other by up to that much. A step smaller than this offset is
+ // below what the check can see.
+ var scale = BodyDiagonal(body);
+ var chord = double.Clamp(scale / 4000d, 0.002d, 0.05d);
+ var mesh = BrepDisplayTessellator.Tessellate(body, DisplayTessellationOptions.Default with { ChordTolerance = chord, AngularToleranceRadians = double.Pi / 36d, MaximumSegments = 1024 });
+ if (!mesh.IsSuccess)
+ {
+ diagnostics.Add(new(MoldDiagnosticCodes.PartBuildFailed, PlasticDiagnosticSeverity.Error, "The part could not be meshed for the pull analysis.", intent.PartName));
+ return null;
+ }
+ var patches = mesh.Value.FacePatches.Where(p => p.TriangleIndices.Count > 0).ToArray();
+ var pull = intent.Pull.ToVector();
+ var (min, max) = Bounds(patches);
+ var size = (max - min).Length;
+ var eps = 3d * chord;
+
+ // Display normals point out of the material; a mesh whose enclosed volume comes out negative is flipped.
+ var orientation = SignedVolume(patches) < 0 ? -1d : 1d;
+ var rays = new RayGrid(patches, pull);
+
+ var cosmetic = new HashSet<int>();
+ foreach (var selector in intent.Cosmetic.Where(IsAxisSelector))
+ {
+ var faces = AxisFaces(body, selector);
+ if (faces.Count == 0) diagnostics.Add(new(MoldDiagnosticCodes.SelectorUnresolved, PlasticDiagnosticSeverity.Error, $"{selector} resolves to no planar face of the part: the part's extreme in that direction is not planar.", intent.MoldName));
+ cosmetic.UnionWith(faces.Select(f => f.Value));
+ }
+ var textured = new HashSet<int>();
+ foreach (var selector in (intent.Texture?.Selectors ?? []).Where(IsAxisSelector))
+ {
+ var faces = AxisFaces(body, selector);
+ if (faces.Count == 0) diagnostics.Add(new(MoldDiagnosticCodes.SelectorUnresolved, PlasticDiagnosticSeverity.Error, $"texture {selector} resolves to no planar face of the part.", intent.MoldName));
+ textured.UnionWith(faces.Select(f => f.Value));
+ }
+
+ double? partingHeight = null;
+ if (intent.Parting is { } parting)
+ {
+ if (double.IsNaN(parting.Origin.X))
+ {
+ var faces = AxisFaces(body, parting.Source);
+ var planes = faces.Select(f => body.TryGetFaceSurfaceGeometry(f, out var s) ? s?.Plane : null).OfType<Aetheris.Kernel.Core.Geometry.Surfaces.PlaneSurface>().ToArray();
+ if (planes.Length == 0) diagnostics.Add(new(MoldDiagnosticCodes.SelectorUnresolved, PlasticDiagnosticSeverity.Error, $"parting at {parting.Source} resolves to no planar face of the part.", intent.MoldName));
+ else if (double.Abs(double.Abs(planes[0].Normal.ToVector().Dot(pull)) - 1d) > 1e-9)
+ diagnostics.Add(new(MoldDiagnosticCodes.PartingInvalid, PlasticDiagnosticSeverity.Error, $"parting at {parting.Source}: that face is not perpendicular to the pull, so a plane through it cannot be the parting plane.", intent.MoldName));
+ else partingHeight = (planes[0].Origin - Point3D.Origin).Dot(pull);
+ }
+ else partingHeight = (parting.Origin - Point3D.Origin).Dot(pull);
+ }
+ if (diagnostics.Any(d => d.Severity == PlasticDiagnosticSeverity.Error)) return null;
+
+ var evidence = new List<MoldFaceEvidence>();
+ var sideOf = new Dictionary<int, MoldFaceSide>();
+ foreach (var patch in patches)
+ {
+ var face = patch.FaceId.Value;
+ body.TryGetFaceSurfaceGeometry(patch.FaceId, out var surface);
+ var aligned = body.Bindings.TryGetFaceBinding(patch.FaceId, out var binding) && binding.Orientation.IsAlignedWithSurface;
+ var normals = patch.Normals.Select(n => n * orientation).ToArray();
+ var dots = normals.Select(n => n.Dot(pull) / double.Max(n.Length, 1e-300)).ToArray();
+ var (dMin, dMax) = (dots.Min(), dots.Max());
+ var strength = MoldEvidenceStrength.SampledConservative;
+ switch (surface)
+ {
+ case { Plane: { } plane }:
+ dMin = dMax = plane.Normal.ToVector().Dot(pull) * (aligned ? 1d : -1d);
+ strength = MoldEvidenceStrength.ExactAnalytic;
+ break;
+ case { Cylinder: { } cylinder } when double.Abs(double.Abs(cylinder.Axis.ToVector().Dot(pull)) - 1d) < 1e-12:
+ dMin = dMax = 0d;
+ strength = MoldEvidenceStrength.ExactAnalytic;
+ break;
+ case { Cone: { } cone } when double.Abs(double.Abs(cone.Axis.ToVector().Dot(pull)) - 1d) < 1e-12:
+ dMin = dMax = double.Sign(dots.Average()) * double.Sin(cone.SemiAngleRadians);
+ strength = MoldEvidenceStrength.ExactAnalytic;
+ break;
+ }
+ var side = dMin >= -ParallelTolerance && dMax <= ParallelTolerance ? MoldFaceSide.Vertical
+ : dMin >= -ParallelTolerance ? MoldFaceSide.Positive
+ : dMax <= ParallelTolerance ? MoldFaceSide.Negative
+ : MoldFaceSide.Straddling;
+ var draft = side switch
+ {
+ MoldFaceSide.Positive => double.Asin(double.Clamp(dMin, 0d, 1d)),
+ MoldFaceSide.Negative => double.Asin(double.Clamp(-dMax, 0d, 1d)),
+ _ => 0d,
+ } * 180d / double.Pi;
+ var required = intent.Policy.MinimumDraftDegrees + (textured.Contains(face) ? intent.Policy.TextureDraftDegreesPerMillimetre * intent.Texture!.Depth : 0d);
+
+ // Release: rays from the face's mesh samples along its half's pull must leave the part.
+ var triangles = Triangles(patch, orientation);
+ var stride = int.Max(1, triangles.Length / MaximumSamplesPerFace);
+ var samples = 0; var blocked = 0; var freePositive = 0; var freeNegative = 0;
+ for (var t = 0; t < triangles.Length; t += stride)
+ {
+ var (centroid, normal, _) = triangles[t];
+ var start = centroid + normal * eps;
+ var d = normal.Dot(pull);
+ samples++;
+ if (double.Abs(d) <= ParallelTolerance)
+ {
+ var up = !rays.Hits(start, pull, eps); var down = !rays.Hits(start, -pull, eps);
+ if (up) freePositive++;
+ if (down) freeNegative++;
+ if (!up && !down) blocked++;
+ }
+ else if (rays.Hits(start, pull * double.Sign(d), eps)) blocked++;
+ }
+ var area = triangles.Sum(x => x.Area);
+ var representative = triangles.Length == 0 ? Point3D.Origin : Weighted(triangles);
+ if (side == MoldFaceSide.Vertical)
+ {
+ // A wall parallel to the pull goes with the half it can leave towards; when both are open, with the
+ // half on its side of the parting plane.
+ var height = (representative - Point3D.Origin).Dot(pull);
+ sideOf[face] = freePositive > 0 && freeNegative == 0 ? MoldFaceSide.Positive
+ : freeNegative > 0 && freePositive == 0 ? MoldFaceSide.Negative
+ : partingHeight is { } h ? (height > h ? MoldFaceSide.Positive : MoldFaceSide.Negative)
+ : MoldFaceSide.Vertical;
+ }
+ else sideOf[face] = side;
+
+ evidence.Add(new(face, surface?.Kind.ToString() ?? "Unknown", side, draft, required, draft + 1e-9 >= required,
+ samples == 0 ? 0d : (double)blocked / samples, samples, cosmetic.Contains(face), representative, area, strength));
+ }
+
+ // side(+pull) and side(-pull) name the faces a half forms, known only now.
+ HashSet<int> Side(IEnumerable<string> selectors) => selectors.Where(x => !IsAxisSelector(x))
+ .SelectMany(x => sideOf.Where(p => p.Value == (x.Contains('+') ? MoldFaceSide.Positive : MoldFaceSide.Negative)).Select(p => p.Key)).ToHashSet();
+ cosmetic.UnionWith(Side(intent.Cosmetic));
+ textured.UnionWith(Side(intent.Texture?.Selectors ?? []));
+ evidence = evidence.Select(f =>
+ {
+ var required = intent.Policy.MinimumDraftDegrees + (textured.Contains(f.FaceId) ? intent.Policy.TextureDraftDegreesPerMillimetre * intent.Texture!.Depth : 0d);
+ return f with { RequiredDraftDegrees = required, DraftSatisfied = f.MinimumDraftDegrees + 1e-9 >= required, Cosmetic = cosmetic.Contains(f.FaceId) };
+ }).ToList();
+
+ // Parting line: edges between the two halves.
+ var faceOfLoop = body.Topology.Faces.SelectMany(f => f.LoopIds.Select(l => (Loop: l, Face: f.Id.Value))).ToDictionary(x => x.Loop, x => x.Face);
+ var edgeFaces = body.Topology.Coedges.GroupBy(c => c.EdgeId).ToDictionary(g => g.Key, g => g.Select(c => faceOfLoop[c.LoopId]).Distinct().ToArray());
+ var polylines = mesh.Value.EdgePolylines.ToDictionary(e => e.EdgeId);
+ var partingEdges = edgeFaces.Where(e => e.Value.Length == 2
+ && sideOf.GetValueOrDefault(e.Value[0]) is var a && sideOf.GetValueOrDefault(e.Value[1]) is var b
+ && ((a == MoldFaceSide.Positive && b == MoldFaceSide.Negative) || (a == MoldFaceSide.Negative && b == MoldFaceSide.Positive)))
+ .Select(e => e.Key).OrderBy(e => e.Value).ToArray();
+ var heights = partingEdges.SelectMany(e => polylines.TryGetValue(e, out var line) ? line.Points : []).Select(p => (p - Point3D.Origin).Dot(pull)).ToArray();
+ var (hMin, hMax) = heights.Length == 0 ? (double.NaN, double.NaN) : (heights.Min(), heights.Max());
+ var onPlane = partingHeight is not { } ph || heights.All(h => double.Abs(h - ph) <= 1e-6 * size + 1e-6);
+ var cosmeticTouched = partingEdges.SelectMany(e => edgeFaces[e]).Where(cosmetic.Contains).Distinct().Order().ToArray();
+ var partingLine = new MoldPartingLineEvidence(partingEdges.Select(e => e.Value).ToArray(), hMin, hMax, onPlane, cosmeticTouched);
+
+ // Findings, scaled by stage.
+ foreach (var f in evidence.Where(f => f.Side == MoldFaceSide.Straddling))
+ diagnostics.Add(new(MoldDiagnosticCodes.StraddlingFace, Severity(intent.Stage, hard: true),
+ $"Face {f.FaceId} ({f.Surface} near {Format(f.Representative)}) faces both ways along the pull; the parting line has to split it.", $"face:{f.FaceId}"));
+ foreach (var f in evidence.Where(f => f.UndercutFraction > 0))
+ diagnostics.Add(new(f.Cosmetic ? MoldDiagnosticCodes.UndercutOnCosmetic : MoldDiagnosticCodes.Undercut, Severity(intent.Stage, hard: true),
+ $"Face {f.FaceId} ({f.Surface} near {Format(f.Representative)}) cannot release along the pull: {f.UndercutFraction:P0} of its samples are blocked by the part. It needs a side action, a lifter, or a different pull.", $"face:{f.FaceId}"));
+ // Draft findings come as one line per required angle: a part at its first review typically has every wall
+ // vertical, and the report lists the faces individually.
+ foreach (var group in evidence.Where(f => !f.DraftSatisfied && f.Side != MoldFaceSide.Straddling).GroupBy(f => f.RequiredDraftDegrees))
+ {
+ var faces = group.ToArray();
+ diagnostics.Add(new(MoldDiagnosticCodes.DraftInsufficient, Severity(intent.Stage, hard: false),
+ $"{faces.Length} face(s) have less than the {group.Key:0.##}° of draft {intent.Policy.Name} needs: "
+ + string.Join("; ", faces.Select(f => $"{f.FaceId} ({f.Surface} near {Format(f.Representative)}, {f.MinimumDraftDegrees:0.##}°)")) + ".",
+ "faces:" + string.Join(",", faces.Select(f => f.FaceId))));
+ }
+ if (!onPlane)
+ diagnostics.Add(new(MoldDiagnosticCodes.PartingLineOffPlane, Severity(intent.Stage, hard: false),
+ $"The parting line runs from {hMin:0.###} to {hMax:0.###} mm along the pull, off the declared parting plane at {partingHeight:0.###} mm; the part needs a stepped parting surface or a different plane.", intent.MoldName));
+ if (cosmeticTouched.Length > 0)
+ diagnostics.Add(new(MoldDiagnosticCodes.PartingLineOnCosmetic, Severity(intent.Stage, hard: false),
+ $"The parting line runs along cosmetic face(s) {string.Join(", ", cosmeticTouched)}; it leaves a witness line there.", intent.MoldName));
+
+ var projected = patches.Where(p => sideOf.GetValueOrDefault(p.FaceId.Value) == MoldFaceSide.Positive)
+ .SelectMany(p => Triangles(p, orientation)).Sum(t => t.Area * double.Abs(t.Normal.Dot(pull)));
+ var volume = BrepMassProperties.Evaluate(body).AbsoluteVolume;
+ var summary = new MoldSummary(evidence.Count,
+ evidence.Count(f => f.Side == MoldFaceSide.Positive), evidence.Count(f => f.Side == MoldFaceSide.Negative),
+ evidence.Count(f => f.Side == MoldFaceSide.Vertical), evidence.Count(f => f.Side == MoldFaceSide.Straddling),
+ evidence.Count(f => !f.DraftSatisfied), evidence.Count(f => f.UndercutFraction > 0),
+ projected, volume, volume * intent.Policy.Density / 1000d);
+ return new(intent, evidence, partingLine, summary,
+ "Face normals against the pull (exact on planes, and on cylinders and cones about the pull; mesh extremes otherwise); release by casting the display mesh's samples along the pull against the part; parting line from face adjacency. Undercuts between samples are not proven absent.");
+ }
+
+ private static PlasticDiagnosticSeverity Severity(MoldStage stage, bool hard) => stage switch
+ {
+ MoldStage.Tooling => PlasticDiagnosticSeverity.Error,
+ MoldStage.Prototype when hard => PlasticDiagnosticSeverity.Error,
+ _ => PlasticDiagnosticSeverity.Warning,
+ };
+
+ private static string Format(Point3D p) => $"({p.X:0.##}, {p.Y:0.##}, {p.Z:0.##})";
+
+ private static bool IsAxisSelector(string selector) => selector.StartsWith("face(", StringComparison.Ordinal);
+
+ /// <summary>The faces <c>face(±X|Y|Z)</c> names: planar faces lying in the part's extreme plane in that direction.</summary>
+ internal static IReadOnlyList<FaceId> AxisFaces(BrepBody body, string selector)
+ {
+ var token = selector.Replace(" ", "")[5..^1];
+ var s = token[0] == '-' ? -1d : 1d;
+ var axis = token[1] switch { 'X' => new Vector3D(s, 0, 0), 'Y' => new Vector3D(0, s, 0), _ => new Vector3D(0, 0, s) };
+ var planes = body.Topology.Faces
+ .Select(face => (face.Id, Plane: body.TryGetFaceSurfaceGeometry(face.Id, out var surface) ? surface?.Plane : null,
+ Aligned: body.Bindings.TryGetFaceBinding(face.Id, out var binding) && binding.Orientation.IsAlignedWithSurface))
+ .Where(f => f.Plane is { } plane && plane.Normal.ToVector().Dot(axis) * (f.Aligned ? 1d : -1d) > 1 - 1e-8)
+ .Select(f => (f.Id, Offset: (f.Plane!.Value.Origin - Point3D.Origin).Dot(axis))).ToArray();
+ if (planes.Length == 0) return [];
+ var extreme = body.Topology.Vertices.Select(v => body.TryGetVertexPoint(v.Id, out var p) ? (p - Point3D.Origin).Dot(axis) : double.NegativeInfinity).Max();
+ var support = planes.Max(p => p.Offset);
+ return support < extreme - 1e-7 ? [] : planes.Where(p => double.Abs(p.Offset - support) < 1e-7).Select(p => p.Id).ToArray();
+ }
+
+ private static (Point3D Centroid, Vector3D Normal, double Area)[] Triangles(DisplayFaceMeshPatch patch, double orientation)
+ {
+ var result = new (Point3D, Vector3D, double)[patch.TriangleIndices.Count / 3];
+ for (var i = 0; i < result.Length; i++)
+ {
+ int a = patch.TriangleIndices[3 * i], b = patch.TriangleIndices[3 * i + 1], c = patch.TriangleIndices[3 * i + 2];
+ var (pa, pb, pc) = (patch.Positions[a], patch.Positions[b], patch.Positions[c]);
+ var cross = (pb - pa).Cross(pc - pa);
+ var n = (patch.Normals[a] + patch.Normals[b] + patch.Normals[c]) * orientation;
+ var length = n.Length;
+ result[i] = (new Point3D((pa.X + pb.X + pc.X) / 3, (pa.Y + pb.Y + pc.Y) / 3, (pa.Z + pb.Z + pc.Z) / 3), length > 0 ? n / length : n, cross.Length / 2);
+ }
+ return result;
+ }
+
+ /// <summary>A point on the face near its area centroid: the mesh sample closest to it, so a ring's point is on the ring.</summary>
+ private static Point3D Weighted((Point3D Centroid, Vector3D Normal, double Area)[] triangles)
+ {
+ var total = triangles.Sum(t => t.Area);
+ if (total <= 0) return triangles[0].Centroid;
+ var centre = Point3D.Origin + triangles.Aggregate(Vector3D.Zero, (acc, t) => acc + (t.Centroid - Point3D.Origin) * t.Area) / total;
+ return triangles.MinBy(t => (t.Centroid - centre).Length).Centroid;
+ }
+
+ private static double BodyDiagonal(BrepBody body)
+ {
+ var points = body.Topology.Vertices.Select(v => body.TryGetVertexPoint(v.Id, out var p) ? (Point3D?)p : null).OfType<Point3D>().ToArray();
+ return points.Length < 2 ? 100d : new Vector3D(points.Max(p => p.X) - points.Min(p => p.X), points.Max(p => p.Y) - points.Min(p => p.Y), points.Max(p => p.Z) - points.Min(p => p.Z)).Length;
+ }
+
+ private static (Point3D Min, Point3D Max) Bounds(IEnumerable<DisplayFaceMeshPatch> patches)
+ {
+ var points = patches.SelectMany(p => p.Positions).ToArray();
+ return (new Point3D(points.Min(p => p.X), points.Min(p => p.Y), points.Min(p => p.Z)),
+ new Point3D(points.Max(p => p.X), points.Max(p => p.Y), points.Max(p => p.Z)));
+ }
+
+ private static double SignedVolume(IEnumerable<DisplayFaceMeshPatch> patches)
+ {
+ var volume = 0d;
+ foreach (var patch in patches)
+ for (var i = 0; i + 2 < patch.TriangleIndices.Count; i += 3)
+ {
+ var (a, b, c) = (patch.Positions[patch.TriangleIndices[i]], patch.Positions[patch.TriangleIndices[i + 1]], patch.Positions[patch.TriangleIndices[i + 2]]);
+ var cross = (b - a).Cross(c - a);
+ var n = patch.Normals[patch.TriangleIndices[i]] + patch.Normals[patch.TriangleIndices[i + 1]] + patch.Normals[patch.TriangleIndices[i + 2]];
+ // Orient each triangle by its display normals, then sum the divergence volume.
+ var s = cross.Dot(n) < 0 ? -1d : 1d;
+ volume += s * (a - Point3D.Origin).Dot((b - Point3D.Origin).Cross(c - Point3D.Origin)) / 6d;
+ }
+ return volume;
+ }
+
+ /// <summary>Triangles bucketed on the plane perpendicular to the pull, so a ray along ±pull tests only its cell.</summary>
+ private sealed class RayGrid
+ {
+ private readonly (Point3D A, Point3D B, Point3D C)[] triangles;
+ private readonly List<int>[] cells;
+ private readonly Vector3D u, v;
+ private readonly double u0, v0, cell;
+ private readonly int n;
+
+ public RayGrid(IReadOnlyList<DisplayFaceMeshPatch> patches, Vector3D pull)
+ {
+ triangles = patches.SelectMany(p => Enumerable.Range(0, p.TriangleIndices.Count / 3)
+ .Select(i => (p.Positions[p.TriangleIndices[3 * i]], p.Positions[p.TriangleIndices[3 * i + 1]], p.Positions[p.TriangleIndices[3 * i + 2]]))).ToArray();
+ var helper = double.Abs(pull.X) < 0.9 ? new Vector3D(1, 0, 0) : new Vector3D(0, 1, 0);
+ u = pull.Cross(helper); u /= u.Length;
+ v = pull.Cross(u); v /= v.Length;
+ var projected = triangles.Select(t => new[] { t.A, t.B, t.C }.Select(P).ToArray()).ToArray();
+ var all = projected.SelectMany(x => x).ToArray();
+ u0 = all.Min(p => p.U); v0 = all.Min(p => p.V);
+ var extent = double.Max(all.Max(p => p.U) - u0, all.Max(p => p.V) - v0);
+ n = int.Clamp((int)double.Sqrt(triangles.Length), 8, 256);
+ cell = extent / n + 1e-12;
+ cells = new List<int>[n * n];
+ for (var i = 0; i < projected.Length; i++)
+ {
+ var p = projected[i];
+ var (i0, i1) = (Index(p.Min(x => x.U) - u0), Index(p.Max(x => x.U) - u0));
+ var (j0, j1) = (Index(p.Min(x => x.V) - v0), Index(p.Max(x => x.V) - v0));
+ for (var a = i0; a <= i1; a++)
+ for (var b = j0; b <= j1; b++) (cells[a * n + b] ??= []).Add(i);
+ }
+ }
+
+ private (double U, double V) P(Point3D p) => ((p - Point3D.Origin).Dot(u), (p - Point3D.Origin).Dot(v));
+ private int Index(double offset) => int.Clamp((int)(offset / cell), 0, n - 1);
+
+ public bool Hits(Point3D origin, Vector3D direction, double eps)
+ {
+ var (pu, pv) = P(origin);
+ var list = cells[Index(pu - u0) * n + Index(pv - v0)];
+ if (list is null) return false;
+ foreach (var i in list)
+ {
+ var (a, b, c) = triangles[i];
+ var e1 = b - a; var e2 = c - a;
+ var h = direction.Cross(e2);
+ var det = e1.Dot(h);
+ if (double.Abs(det) < 1e-14 * e1.Length * e2.Length) continue;
+ var s = origin - a;
+ var f = 1d / det;
+ var bu = f * s.Dot(h);
+ if (bu < -1e-9 || bu > 1 + 1e-9) continue;
+ var q = s.Cross(e1);
+ var bv = f * direction.Dot(q);
+ if (bv < -1e-9 || bu + bv > 1 + 1e-9) continue;
+ if (f * e2.Dot(q) > eps) return true;
+ }
+ return false;
+ }
+ }
+}
diff --git a/Aetheris.PlasticShell/MoldFirmament.cs b/Aetheris.PlasticShell/MoldFirmament.cs
new file mode 100644
index 00000000..fcb91eab
--- /dev/null
+++ b/Aetheris.PlasticShell/MoldFirmament.cs
@@ -0,0 +1,235 @@
+using System.Globalization;
+using System.Text.RegularExpressions;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+
+namespace Aetheris.PlasticShell;
+
+/// <summary>
+/// A <c>Mold</c> block declares the tooling intent for a part: pull direction, parting, cosmetic faces and the
+/// molding policy. The part is built through the ordinary compiler, unchanged; the Mold block only reads it.
+/// </summary>
+public static partial class MoldFirmament
+{
+ private static readonly HashSet<string> Fields = new(StringComparer.OrdinalIgnoreCase)
+ { "part", "material", "policy", "stage", "pull", "parting", "cosmetic", "texture", "minimumDraft" };
+
+ public static bool LooksLikeMold(string? source) => source is not null && source.Contains("Mold", StringComparison.Ordinal)
+ && FirmamentSyntaxParser.Parse(source).Document.Statements.OfType<DeclarationSyntax>().Any(d => d.Type.Name.Text == "Mold");
+
+ public static MoldCompileResult CompileFile(string path) => Compile(File.ReadAllText(path), Path.GetFullPath(path));
+
+ public static MoldCompileResult Compile(string source, string sourcePath = "authored.firmament")
+ {
+ var diagnostics = new List<MoldDiagnostic>();
+ var document = FirmamentSyntaxParser.Parse(source, sourcePath).Document;
+ var molds = document.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "Mold").ToArray();
+ if (molds.Length != 1 || molds[0].Name is null)
+ return Fail(diagnostics, MoldDiagnosticCodes.SourceInvalid, "Declare exactly one named Mold block per file.");
+ var mold = molds[0];
+ var intent = ReadIntent(source, document, mold, diagnostics);
+ if (intent is null || diagnostics.Any(d => d.Severity == PlasticDiagnosticSeverity.Error)) return new(false, intent, null, null, diagnostics);
+
+ // The part builds exactly as it would without the Mold block: blank the block out, keeping every other span.
+ var partSource = string.Concat(source.AsSpan(0, mold.Span.Start), new string(' ', mold.Span.Length), source.AsSpan(mold.Span.Start + mold.Span.Length));
+ var built = FirmamentBuildAndExport.CompileSource(partSource, Path.GetDirectoryName(sourcePath));
+ if (!built.IsSuccess)
+ {
+ diagnostics.AddRange(built.Diagnostics.Select(d => new MoldDiagnostic(MoldDiagnosticCodes.PartBuildFailed, PlasticDiagnosticSeverity.Error, d.Message, intent.PartName)));
+ return new(false, intent, null, null, diagnostics);
+ }
+ var body = Step242Importer.ImportBody(built.Value.StepText);
+ if (!body.IsSuccess)
+ return Fail(diagnostics, MoldDiagnosticCodes.PartBuildFailed, "The part's STEP did not import as one closed body: " + string.Join("; ", body.Diagnostics.Select(d => d.Message)), intent.PartName, intent);
+
+ var report = MoldAnalysis.Analyze(body.Value, intent, diagnostics);
+ return new(report is not null && !diagnostics.Any(d => d.Severity == PlasticDiagnosticSeverity.Error), intent, report, built.Value.StepText, diagnostics);
+ }
+
+ private static MoldIntent? ReadIntent(string source, DocumentSyntax document, DeclarationSyntax mold, List<MoldDiagnostic> diagnostics)
+ {
+ var name = mold.Name!.Text;
+ var fields = new Dictionary<string, FieldSyntax>(StringComparer.OrdinalIgnoreCase);
+ foreach (var statement in mold.Body?.Statements ?? [])
+ {
+ if (statement is not FieldSyntax field) { Error(diagnostics, MoldDiagnosticCodes.SourceInvalid, $"Mold {name} takes fields only; declarations such as Gate and Action arrive in later phases.", name); continue; }
+ if (!Fields.Contains(field.Name.Text)) { Error(diagnostics, MoldDiagnosticCodes.SourceInvalid, $"Unknown Mold field '{field.Name.Text}'. Known fields: {string.Join(", ", Fields.Order())}.", name); continue; }
+ if (!fields.TryAdd(field.Name.Text, field)) Error(diagnostics, MoldDiagnosticCodes.SourceInvalid, $"Mold field '{field.Name.Text}' is declared twice.", name);
+ }
+ string Text(ExpressionSyntax e) => source.Substring(e.Span.Start, e.Span.Length).Trim();
+
+ var models = document.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "Model" && d.Name is not null).Select(d => d.Name!.Text).ToArray();
+ var part = fields.TryGetValue("part", out var partField) ? Text(partField.Value) : models.Length == 1 ? models[0] : null;
+ if (part is null || !models.Contains(part, StringComparer.Ordinal))
+ Error(diagnostics, MoldDiagnosticCodes.PartUnresolved, part is null
+ ? "Name the part: `part: ModelName`. The file declares " + (models.Length == 0 ? "no Model." : $"{models.Length} Models.")
+ : $"part '{part}' is not a Model declared in this file.", name);
+
+ if (!fields.TryGetValue("material", out var materialField)) { Error(diagnostics, MoldDiagnosticCodes.MaterialUnknown, $"Mold {name} needs a material: one of {string.Join(", ", MoldingMaterials.Defaults.Keys)}.", name); return null; }
+ if (!MoldingMaterials.Defaults.TryGetValue(Text(materialField.Value), out var policy))
+ { Error(diagnostics, MoldDiagnosticCodes.MaterialUnknown, $"Unknown material '{Text(materialField.Value)}'. Known: {string.Join(", ", MoldingMaterials.Defaults.Keys)}.", name); return null; }
+ if (fields.TryGetValue("policy", out var policyField))
+ policy = ReadPolicy(source, Text(policyField.Value), policy, diagnostics, name);
+ if (fields.TryGetValue("minimumDraft", out var draftField))
+ {
+ if (TryAngle(Text(draftField.Value), out var degrees) && degrees >= 0 && degrees < 45) policy = policy with { MinimumDraftDegrees = degrees };
+ else Error(diagnostics, MoldDiagnosticCodes.PolicyInvalid, "minimumDraft takes an angle in [0deg, 45deg).", name);
+ }
+
+ var stage = MoldStage.Concept;
+ if (fields.TryGetValue("stage", out var stageField) && !Enum.TryParse(Text(stageField.Value), false, out stage))
+ Error(diagnostics, MoldDiagnosticCodes.SourceInvalid, "stage is Concept, Prototype or Tooling.", name);
+
+ Direction3D? pull = null;
+ if (!fields.TryGetValue("pull", out var pullField)) Error(diagnostics, MoldDiagnosticCodes.SourceInvalid, "Mold needs pull: the direction the +pull half opens, such as +Z or [0, 0, 1].", name);
+ else if (TryDirection(Text(pullField.Value), out var direction)) pull = direction;
+ else Error(diagnostics, MoldDiagnosticCodes.SourceInvalid, $"pull '{Text(pullField.Value)}' is not an axis (+Z) or a nonzero vector ([0, 0, 1]).", name);
+
+ MoldPartingPlane? parting = null;
+ if (fields.TryGetValue("parting", out var partingField) && pull is { } p)
+ parting = ReadParting(source, partingField.Value, p, diagnostics, name);
+
+ var cosmetic = fields.TryGetValue("cosmetic", out var cosmeticField) ? Selectors(source, cosmeticField.Value, diagnostics, name) : [];
+ MoldTexture? texture = null;
+ if (fields.TryGetValue("texture", out var textureField))
+ {
+ if (textureField.Value is not ObjectSyntax obj) Error(diagnostics, MoldDiagnosticCodes.SourceInvalid, "texture is { faces: [face(...)], depth: 0.025mm }.", name);
+ else
+ {
+ var inner = obj.Body.Statements.OfType<FieldSyntax>().ToDictionary(f => f.Name.Text, StringComparer.OrdinalIgnoreCase);
+ if (!inner.TryGetValue("faces", out var faces) || !inner.TryGetValue("depth", out var depth) || !TryLength(Text(depth.Value), out var mm) || mm <= 0)
+ Error(diagnostics, MoldDiagnosticCodes.SourceInvalid, "texture needs faces: [face(...)] and a positive depth.", name);
+ else texture = new(Selectors(source, faces.Value, diagnostics, name), mm);
+ }
+ }
+ return pull is null || part is null ? null : new MoldIntent(name, part, policy, stage, pull.Value, parting, cosmetic, texture);
+ }
+
+ /// <summary>A typed policy Static overrides the material's defaults field by field.</summary>
+ private static MoldingPolicy ReadPolicy(string source, string staticName, MoldingPolicy policy, List<MoldDiagnostic> diagnostics, string owner)
+ {
+ var binding = new FirmamentDomainBinding(source, "mold-policy", "Mold", new HashSet<string>(StringComparer.Ordinal));
+ double? Value(string field, string unit)
+ {
+ var reference = FirmamentSyntaxParser.Parse($"Model M {{ x: {staticName}.{field} }}").Document.Statements.OfType<DeclarationSyntax>().Single().Body!.Statements.OfType<FieldSyntax>().Single().Value;
+ if (!binding.TryValue(reference, out var bound) || bound.Value.NumericValue is not { } number) return null;
+ return (bound.Value.Unit ?? "") switch
+ {
+ "rad" when unit == "deg" => number * 180d / double.Pi,
+ var u when u == unit || u == "" => number,
+ _ => null,
+ };
+ }
+ var draft = Value("MinimumDraft", "deg");
+ if (draft is null) Error(diagnostics, MoldDiagnosticCodes.PolicyInvalid, $"policy '{staticName}' does not resolve to a Static with a MinimumDraft angle.", owner);
+ return policy with
+ {
+ Name = $"{policy.Name} with {staticName}",
+ MinimumDraftDegrees = draft ?? policy.MinimumDraftDegrees,
+ MinimumWall = Value("MinimumWall", "mm") ?? policy.MinimumWall,
+ MaximumWall = Value("MaximumWall", "mm") ?? policy.MaximumWall,
+ MaximumFlowRatio = Value("MaximumFlowRatio", "") ?? policy.MaximumFlowRatio,
+ };
+ }
+
+ private static MoldPartingPlane? ReadParting(string source, ExpressionSyntax value, Direction3D pull, List<MoldDiagnostic> diagnostics, string owner)
+ {
+ string Text(ExpressionSyntax e) => source.Substring(e.Span.Start, e.Span.Length).Trim();
+ if (value is not ObjectSyntax { Type: { } type } obj || Text(type) != "Plane")
+ { Error(diagnostics, MoldDiagnosticCodes.PartingInvalid, "parting is Plane { at: face(+Z) } or Plane { origin: [x, y, z] } in this phase; stepped and contoured parting come later.", owner); return null; }
+ var inner = obj.Body.Statements.OfType<FieldSyntax>().ToDictionary(f => f.Name.Text, StringComparer.OrdinalIgnoreCase);
+ if (inner.Keys.Any(k => !k.Equals("at", StringComparison.OrdinalIgnoreCase) && !k.Equals("origin", StringComparison.OrdinalIgnoreCase)) || inner.Count != 1)
+ { Error(diagnostics, MoldDiagnosticCodes.PartingInvalid, "A parting Plane takes exactly one of at: face(...) or origin: [x, y, z]; its normal is the pull.", owner); return null; }
+ if (inner.TryGetValue("origin", out var origin))
+ {
+ if (TryPoint(Text(origin.Value), out var point)) return new(point, pull, $"origin {Text(origin.Value)}");
+ Error(diagnostics, MoldDiagnosticCodes.PartingInvalid, "origin is [x, y, z] in mm.", owner); return null;
+ }
+ var selector = Text(inner["at"].Value);
+ if (!SelectorRegex().IsMatch(selector) || !selector.StartsWith("face(", StringComparison.Ordinal)) { Error(diagnostics, MoldDiagnosticCodes.SelectorUnresolved, $"'{selector}' is not a face selector; use face(+Z) and the other axis faces.", owner); return null; }
+ // The plane through that face is resolved against the built part.
+ return new(new Point3D(double.NaN, double.NaN, double.NaN), pull, selector);
+ }
+
+ private static IReadOnlyList<string> Selectors(string source, ExpressionSyntax value, List<MoldDiagnostic> diagnostics, string owner)
+ {
+ var items = value is SequenceSyntax sequence ? sequence.Items.Select(i => i.Value) : [value];
+ var result = new List<string>();
+ foreach (var item in items)
+ {
+ var text = source.Substring(item.Span.Start, item.Span.Length).Trim();
+ if (SelectorRegex().IsMatch(text)) result.Add(text);
+ else Error(diagnostics, MoldDiagnosticCodes.SelectorUnresolved, $"'{text}' is not a face selector; this phase admits the axis faces face(+X) … face(-Z) and the halves side(+pull), side(-pull).", owner);
+ }
+ return result;
+ }
+
+ [GeneratedRegex(@"^(face\(\s*[+-][XYZ]\s*\)|side\(\s*[+-]pull\s*\))$")]
+ internal static partial Regex SelectorRegex();
+
+ internal static bool TryDirection(string text, out Direction3D direction)
+ {
+ direction = default;
+ var axis = Regex.Match(text.Replace(" ", ""), @"^([+-])([XYZ])$");
+ if (axis.Success)
+ {
+ var s = axis.Groups[1].Value == "-" ? -1d : 1d;
+ direction = Direction3D.Create(axis.Groups[2].Value switch { "X" => new Vector3D(s, 0, 0), "Y" => new Vector3D(0, s, 0), _ => new Vector3D(0, 0, s) });
+ return true;
+ }
+ if (!TryTriple(text, "", out var v) || v.Length < 1e-12) return false;
+ direction = Direction3D.Create(v);
+ return true;
+ }
+
+ private static bool TryPoint(string text, out Point3D point)
+ {
+ point = default;
+ if (!TryTriple(text, "mm", out var v)) return false;
+ point = new Point3D(v.X, v.Y, v.Z);
+ return true;
+ }
+
+ private static bool TryTriple(string text, string unit, out Vector3D value)
+ {
+ value = default;
+ var t = text.Trim();
+ if (!t.StartsWith('[') || !t.EndsWith(']')) return false;
+ var parts = t[1..^1].Split(',', StringSplitOptions.TrimEntries);
+ if (parts.Length != 3) return false;
+ var numbers = new double[3];
+ for (var i = 0; i < 3; i++)
+ if (!TryQuantity(parts[i], unit, out numbers[i]) && !double.TryParse(parts[i], NumberStyles.Float, CultureInfo.InvariantCulture, out numbers[i])) return false;
+ value = new Vector3D(numbers[0], numbers[1], numbers[2]);
+ return true;
+ }
+
+ internal static bool TryAngle(string text, out double degrees)
+ {
+ if (TryQuantity(text, "deg", out degrees)) return true;
+ if (TryQuantity(text, "rad", out var radians)) { degrees = radians * 180d / double.Pi; return true; }
+ return false;
+ }
+
+ internal static bool TryLength(string text, out double millimetres) => TryQuantity(text, "mm", out millimetres);
+
+ private static bool TryQuantity(string text, string unit, out double value)
+ {
+ value = double.NaN;
+ var m = Regex.Match(text.Trim(), @"^([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)\s*([A-Za-z]*)$");
+ if (!m.Success || !string.Equals(m.Groups[2].Value, unit, StringComparison.Ordinal)) return false;
+ return double.TryParse(m.Groups[1].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out value);
+ }
+
+ private static void Error(List<MoldDiagnostic> diagnostics, string code, string message, string? entity) =>
+ diagnostics.Add(new(code, PlasticDiagnosticSeverity.Error, message, entity));
+
+ private static MoldCompileResult Fail(List<MoldDiagnostic> diagnostics, string code, string message, string? entity = null, MoldIntent? intent = null)
+ {
+ Error(diagnostics, code, message, entity);
+ return new(false, intent, null, null, diagnostics);
+ }
+}
diff --git a/Aetheris.PlasticShell/MoldIr.cs b/Aetheris.PlasticShell/MoldIr.cs
new file mode 100644
index 00000000..f2798595
--- /dev/null
+++ b/Aetheris.PlasticShell/MoldIr.cs
@@ -0,0 +1,113 @@
+using Aetheris.Kernel.Core.Math;
+
+namespace Aetheris.PlasticShell;
+
+/// <summary>How hard a manufacturing finding is. Early designs get the whole report without failing the build; the
+/// tooling stage is the release gate.</summary>
+public enum MoldStage { Concept, Prototype, Tooling }
+
+/// <summary>Which half of the tool forms a face, by its outward normal against the pull direction.</summary>
+public enum MoldFaceSide
+{
+ /// <summary>Faces the pull direction: formed by the half that opens along +pull.</summary>
+ Positive,
+ /// <summary>Faces against the pull direction: formed by the half that opens along −pull.</summary>
+ Negative,
+ /// <summary>Parallel to the pull everywhere (zero draft): either half, at its parting end.</summary>
+ Vertical,
+ /// <summary>Faces both ways: the parting line has to split it.</summary>
+ Straddling,
+}
+
+public enum MoldEvidenceStrength { ExactAnalytic, SampledConservative }
+
+public static class MoldDiagnosticCodes
+{
+ public const string SourceInvalid = "mold-source-invalid";
+ public const string PartUnresolved = "mold-part-unresolved";
+ public const string PartBuildFailed = "mold-part-build-failed";
+ public const string MaterialUnknown = "mold-material-unknown";
+ public const string PolicyInvalid = "mold-policy-invalid";
+ public const string SelectorUnresolved = "mold-face-selector-unresolved";
+ public const string PartingInvalid = "mold-parting-invalid";
+ public const string DraftInsufficient = "mold-draft-insufficient";
+ public const string Undercut = "mold-undercut";
+ public const string StraddlingFace = "mold-face-straddles-pull";
+ public const string PartingLineOffPlane = "mold-parting-line-off-plane";
+ public const string PartingLineOnCosmetic = "mold-parting-line-on-cosmetic-face";
+ public const string UndercutOnCosmetic = "mold-cosmetic-face-not-pullable";
+}
+
+public sealed record MoldDiagnostic(string Code, PlasticDiagnosticSeverity Severity, string Message, string? Entity = null);
+
+/// <summary>The scalar rules of a molding material: compile-time policy, independent of any part.</summary>
+public sealed record MoldingPolicy(
+ string Name,
+ double MinimumDraftDegrees,
+ double TextureDraftDegreesPerMillimetre,
+ double MinimumWall,
+ double MaximumWall,
+ double MaximumFlowRatio,
+ double Shrinkage,
+ double Density);
+
+public sealed record MoldPartingPlane(Point3D Origin, Direction3D Normal, string Source);
+
+public sealed record MoldTexture(IReadOnlyList<string> Selectors, double Depth);
+
+public sealed record MoldIntent(
+ string MoldName,
+ string PartName,
+ MoldingPolicy Policy,
+ MoldStage Stage,
+ Direction3D Pull,
+ MoldPartingPlane? Parting,
+ IReadOnlyList<string> Cosmetic,
+ MoldTexture? Texture);
+
+public sealed record MoldFaceEvidence(
+ int FaceId,
+ string Surface,
+ MoldFaceSide Side,
+ double MinimumDraftDegrees,
+ double RequiredDraftDegrees,
+ bool DraftSatisfied,
+ double UndercutFraction,
+ int Samples,
+ bool Cosmetic,
+ Point3D Representative,
+ double Area,
+ MoldEvidenceStrength Strength);
+
+public sealed record MoldPartingLineEvidence(
+ IReadOnlyList<int> EdgeIds,
+ double MinimumHeight,
+ double MaximumHeight,
+ bool OnDeclaredPlane,
+ IReadOnlyList<int> CosmeticFacesTouched);
+
+public sealed record MoldSummary(
+ int Faces,
+ int PositiveFaces,
+ int NegativeFaces,
+ int VerticalFaces,
+ int StraddlingFaces,
+ int DraftFailures,
+ int UndercutFaces,
+ double ProjectedArea,
+ double Volume,
+ double ShotMass);
+
+public sealed record MoldReport(
+ MoldIntent Intent,
+ IReadOnlyList<MoldFaceEvidence> Faces,
+ MoldPartingLineEvidence PartingLine,
+ MoldSummary Summary,
+ string Method);
+
+public sealed record MoldCompileResult(
+ bool IsSuccess,
+ MoldIntent? Intent,
+ MoldReport? Report,
+ string? PartStep,
+ IReadOnlyList<MoldDiagnostic> Diagnostics);
diff --git a/Aetheris.PlasticShell/MoldingMaterials.cs b/Aetheris.PlasticShell/MoldingMaterials.cs
new file mode 100644
index 00000000..21e933c5
--- /dev/null
+++ b/Aetheris.PlasticShell/MoldingMaterials.cs
@@ -0,0 +1,25 @@
+namespace Aetheris.PlasticShell;
+
+/// <summary>
+/// Default molding rules per material: guideline values from common resin design guides, meant as starting
+/// policy and overridden per Mold (<c>minimumDraft:</c>) or by a typed policy Static. Draft for texture follows the usual
+/// rule of 1° per 0.025 mm of texture depth.
+/// </summary>
+public static class MoldingMaterials
+{
+ private const double TextureDraft = 40d; // degrees per millimetre of texture depth
+
+ public static IReadOnlyDictionary<string, MoldingPolicy> Defaults { get; } = new[]
+ {
+ // name draft texture wall min/max L/t shrink density g/cm³
+ new MoldingPolicy("ABS", 1.0, TextureDraft, 1.14, 3.56, 150, 0.006, 1.05),
+ new MoldingPolicy("PC", 1.0, TextureDraft, 1.00, 3.80, 100, 0.006, 1.20),
+ new MoldingPolicy("PC_ABS", 1.0, TextureDraft, 1.00, 3.50, 120, 0.006, 1.15),
+ new MoldingPolicy("PP", 1.0, TextureDraft, 0.64, 3.80, 250, 0.015, 0.90),
+ new MoldingPolicy("HDPE", 1.0, TextureDraft, 0.75, 5.00, 250, 0.025, 0.95),
+ new MoldingPolicy("PA66", 0.5, TextureDraft, 0.75, 3.00, 200, 0.015, 1.14),
+ new MoldingPolicy("PA66_GF30", 0.5, TextureDraft, 0.75, 3.00, 150, 0.005, 1.37),
+ new MoldingPolicy("POM", 0.5, TextureDraft, 0.75, 3.00, 150, 0.020, 1.41),
+ new MoldingPolicy("PMMA", 1.0, TextureDraft, 0.64, 3.80, 130, 0.004, 1.18),
+ }.ToDictionary(p => p.Name, StringComparer.OrdinalIgnoreCase);
+}
diff --git a/docs/development/reports/2026-11/MOLD-DFM-DESIGN.md b/docs/development/reports/2026-11/MOLD-DFM-DESIGN.md
index 9661fd14..f4661d56 100644
--- a/docs/development/reports/2026-11/MOLD-DFM-DESIGN.md
+++ b/docs/development/reports/2026-11/MOLD-DFM-DESIGN.md
@@ -155,3 +155,30 @@ M0 needs no new geometry and works on parts that already exist, which is why it
4. **Draft as a generator parameter** (proposed), exact and consistent with Hollow, rather than a `Modify Draft` that
tilts finished faces. A Modify Draft can come later for imported parts.
5. **Parting forms in M0**: `Plane` only. Stepped and contoured parting surfaces and parting from silhouette later.
+
+## Implementation status
+
+M0 is in (`Aetheris.PlasticShell/Mold*.cs`, CLI `build` and `validate`, `docs/public/firmament/mold.md`).
+
+- The Mold block is a top-level declaration beside the part's Model. The part builds through the ordinary compiler
+ with the block blanked out, and is read back from its STEP, so the review sees exactly what ships.
+- Materials are built-in defaults (ABS, PC, PC_ABS, PP, HDPE, PA66, PA66_GF30, POM, PMMA); a typed `Static` named by
+ `policy:` overrides them field by field, and `minimumDraft:` overrides both. A full `InjectionMoldingPolicy` Concept
+ waits for the M3 rules that would use its other fields.
+- Faces are named geometrically, so the review also works on parts whose construction names are not available:
+ `face(±X|Y|Z)` and `side(±pull)`. Construction names (`face(body.Floor)`) need the PMI resolver; later.
+- Side and draft are exact on planes and on cylinders and cones about the pull; elsewhere they are the extremes over
+ the face's mesh. Undercuts are traced from up to 64 mesh samples per face against the part's mesh, bucketed on the
+ plane normal to the pull. Rays start three chord tolerances off the surface, because neighbouring faces may chord a
+ shared curved edge differently: with the default 0.05 mm chords, a 12 mm tray corner first reported a 12–88% false
+ undercut from exactly that overlap.
+- A face parallel to the pull is assigned to the half it can leave towards, and to the half on its side of the parting
+ plane when both are open. This puts a cup's inner wall with the core and its outer wall with the cavity.
+- Draft findings are aggregated into one diagnostic per required angle; a first review of a Compose part otherwise
+ prints one line per vertical wall.
+
+Evidence: a 2° PP cup releases with exact 2.0002° cones and its projected area equals the rim disk to 0.1%; the hollow
+tray releases with every wall at 0° (24 warnings at `Concept`, errors at `Tooling`) and its projected area equals the
+rounded-rectangle outline; a bottle pulled along its axis reports the inside of its shoulder, body and floor as
+undercuts and a parting line from 39.4 to 58 mm, off its rim plane; a grooved pulley reports exactly the groove's two
+faces and floor.
diff --git a/docs/public/firmament/mold.md b/docs/public/firmament/mold.md
new file mode 100644
index 00000000..3dbc6b49
--- /dev/null
+++ b/docs/public/firmament/mold.md
@@ -0,0 +1,92 @@
+# Mold
+
+A `Mold` block declares how a part will be molded: the pull direction, the parting plane, the faces that must look
+good, and the molding material's rules. The part is an ordinary `Model` and builds exactly as it would without the
+block; the Mold only reads it and reports whether it will release from the tool.
+
+```firmament
+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 }
+ }
+}
+
+Mold TrayTool {
+ part: RoundedTray
+ material: ABS
+ stage: Concept
+ pull: +Z
+ parting: Plane { at: face(+Z) }
+ cosmetic: [face(-Z)]
+}
+```
+
+`aetheris build` writes the part STEP and a `.mold.json` report beside it, and prints a summary:
+
+```text
+Mold TrayTool on RoundedTray (ABS, Concept, pull [0, 0, 1])
+ faces 27: 2 +pull, 1 -pull, 24 parallel, 0 straddling; 24 short of draft, 0 undercut
+ projected area 9475.8 mm², volume 35369.8 mm³, shot 37.14 g; parting line 8 edges
+```
+
+## Fields
+
+| Field | Meaning |
+| --- | --- |
+| `part` | The `Model` in the same file. Optional when the file has one Model. |
+| `material` | Default rules: `ABS`, `PC`, `PC_ABS`, `PP`, `HDPE`, `PA66`, `PA66_GF30`, `POM`, `PMMA`. |
+| `policy` | Optional `Static` whose fields override the material: `MinimumDraft`, `MinimumWall`, `MaximumWall`, `MaximumFlowRatio`. |
+| `minimumDraft` | Optional angle overriding the policy's minimum draft. |
+| `stage` | `Concept` (default), `Prototype` or `Tooling`: how hard findings are (below). |
+| `pull` | The direction one half opens: `+Z`, `-X` … or a vector `[0, 0, 1]`. The other half opens the opposite way. |
+| `parting` | `Plane { at: face(+Z) }` (the plane through that face) or `Plane { origin: [x, y, z] }`. Its normal is the pull. |
+| `cosmetic` | Faces that must not carry a parting line or an undercut. |
+| `texture` | `{ faces: [...]; depth: 0.025mm }`: textured faces need 1° more draft per 0.025 mm of depth. |
+
+Faces are named by `face(+X)` … `face(-Z)` (the planar faces lying in the part's extreme plane in that direction) or
+by half: `side(+pull)` is every face the +pull half forms, `side(-pull)` every face the other half forms.
+
+The material defaults are common design-guide values (ABS: 1° draft, 1.14–3.56 mm wall). They are a starting policy;
+a house rule goes in a typed Static:
+
+```firmament
+Record MoldingPolicySpec { MinimumDraft: Angle }
+Static HouseRule: MoldingPolicySpec = MoldingPolicySpec { MinimumDraft: 1.5deg }
+
+Mold CupTool { part: Cup; material: PP; policy: HouseRule; pull: +Z }
+```
+
+## What is checked
+
+- **Side.** Each face is formed by the +pull half (its outward normal has a +pull component), the −pull half, either
+ (parallel to the pull), or it straddles (faces both ways, so the parting line must split it). A face parallel to
+ the pull goes with the half it can leave towards, and with the half on its side of the parting plane when both are
+ open.
+- **Draft.** The angle between each face and the pull, against the policy (plus texture). Exact on planes and on
+ cylinders and cones about the pull; elsewhere the minimum over the face's mesh.
+- **Undercuts.** Points across each face are traced along its half's pull; a face is an undercut where the part
+ blocks the way. Steps smaller than a few thousandths of the part's size are below what this sees, and the absence
+ of an undercut between samples is not proven.
+- **Parting line.** The edges between the two halves. When it leaves the declared plane the part needs a stepped
+ parting surface or another plane; where it runs along a cosmetic face it leaves a witness line.
+- **Report.** Projected area along the pull (for clamp tonnage), volume and shot mass from the material's density.
+
+## Stages
+
+| Finding | Concept | Prototype | Tooling |
+| --- | --- | --- | --- |
+| Undercut, straddling face | warning | error | error |
+| Draft, parting line off plane, parting line on a cosmetic face | warning | warning | error |
+
+An error fails the build. Problems in the Mold block itself (an unknown material, a selector that names no face) are
+always errors.
+
+## Not yet
+
+Side actions and lifters, gates, ejectors, wall-thickness, rib and boss rules, flow length, and draft on Extrude and
+Compose walls are later phases. Until draft can be authored, a Compose part reports its vertical walls as short of
+draft; the `Concept` stage keeps that a warning. `PlasticShell` remains the bounded route for its frustum enclosures.
diff --git a/docs/public/firmament/plastic-shell.md b/docs/public/firmament/plastic-shell.md
index 8fde5ffa..d0aa42ad 100644
--- a/docs/public/firmament/plastic-shell.md
+++ b/docs/public/firmament/plastic-shell.md
@@ -9,6 +9,8 @@ network identities such as `"perimeter-network"` and `"gate-oriented-fan"`;
the historical unquoted hyphenated forms remain bounded compatibility aliases.
Unknown network names reject instead of having no effect.
+For checking how any part will mold (pull, draft, undercuts, parting line), see [Mold](mold.md).
+
`PlasticShell` is Aetheris's manufacturing-first domain for injection-molded product definitions. Wall thickness, tooling direction, parting, and reinforcement intent live in the domain model rather than as a sequence of cleanup features.
For explicitly placed reinforcement on mechanical Box stock, use
diff --git a/docs/public/reference/supported-features.md b/docs/public/reference/supported-features.md
index 9cc2b741..35f2d40d 100644
--- a/docs/public/reference/supported-features.md
+++ b/docs/public/reference/supported-features.md
@@ -14,6 +14,7 @@
| Scene spatial composition | Supported / bounded | Metre/mm coordinates; rectangular Room boundaries; Door/Window apertures; independent AssemblyFile and typed Part occurrences; keyed patterns; retained definition reuse; cameras and appearances; USD/GLB. No Scene mechanical relationships, nested Scenes, whole-scene STEP or BIM. See [scenes](../firmament/scenes.md). |
| Bounded mathematical sculpting | Bounded | Immutable single-predecessor `BodyState` reconstructed from an admitted engineering-source or housing `BaseConstruction` plus typed replay operations; engineering bodies retain their exact product while the existing edit materializers require the documented housing supports; persistent `OffsetRegion`, `ReplaceRegion`, judged `BlendBoundary`, `HoleFeature`, east-attached `AddSectionChain`, and west/east through-duct `RemoveSectionChain`; atomic replay, semantic support invalidation, locality/preservation evidence, pcurves, AP242 associations, and rational-free STEP. General blend networks and arbitrary SectionChain supports remain unsupported. See the [sculpting guide](../firmament/sculpting.md). |
| Molded plastic shell | Bounded | First-class `PlasticShell` IR; exact drafted coaxial-frustum shell; analytic annular standoffs with retained core holes; constant-shell-thickness planar B-rep rib walls with flat tops; one closed product boundary; face-associated AP242 notes; and explicit zero-release-draft warning for constant-section vertical features. The retired polar height field is available only through the non-manufacturing experimental art command. Freeform exterior offsets and general junctions remain unsupported. See the [PlasticShell guide](../firmament/plastic-shell.md). |
+| Mold review | Bounded | A `Mold` block on any built part: per-face side and draft against a declared pull (exact on planes and on cylinders/cones about the pull), sampled undercut tracing, parting line against a declared plane, cosmetic and textured faces, material policies, stage-scaled severity, and a JSON report. No side actions, gates, ejectors or wall rules yet. See [Mold](../firmament/mold.md). |
| Virtual Sculpture | Bounded | The explicit `Mode: Virtual` Sol 1 flagship: deterministic golden-angle/Fibonacci 3D lattice, analytic toroidal frame and eye, exact closed-body AP242 assembly, evidence/preview output, and zero rational product surfaces. This is not manufacturing geometry and does not extend Firmament engineering domains. See [Virtual Sculpture](../virtual-sculpture.md). |
| Firmament V2 analytic primitives | Bounded | Direct named Sphere, Cone (including zero-radius pointed end), and Torus routes round-trip through AP242; legacy `solid` declarations remain compatibility inputs, not canonical authoring |
| Circular Sweep | Bounded | Open planar XY Concept Path, tangent line/arc segments, constant circular diameter, analytic cylinder/torus faces, capped solid; no general 3D/variable/rail/twist sweep |
diff --git a/fixtures/Canonical/Mold/README.md b/fixtures/Canonical/Mold/README.md
new file mode 100644
index 00000000..7b77e2f2
--- /dev/null
+++ b/fixtures/Canonical/Mold/README.md
@@ -0,0 +1,12 @@
+# Mold canonical fixtures
+
+Each file is an ordinary part `Model` plus one `Mold` block that reads it. Build any of them with
+`aetheris build <file>`: the part STEP and a `.mold.json` report are written side by side.
+
+- `drafted-cup.firmament`: a 2° cup at the `Tooling` stage; releases with no findings.
+- `tray-concept.firmament`: a hollow tray with vertical walls at the `Concept` stage; every wall is short of draft
+ (warnings), nothing is undercut.
+- `cup-textured-policy.firmament`: a typed policy Static and a textured −pull half raise the required draft.
+
+The invalid fixtures (`fixtures/Invalid/Mold`) show undercuts (a bottle shoulder, a pulley groove) and an unknown
+material.
diff --git a/fixtures/Canonical/Mold/cup-textured-policy.firmament b/fixtures/Canonical/Mold/cup-textured-policy.firmament
new file mode 100644
index 00000000..53c4f2dd
--- /dev/null
+++ b/fixtures/Canonical/Mold/cup-textured-policy.firmament
@@ -0,0 +1,30 @@
+// A cup with a typed molding policy: the house rule asks for 1.5° on PP, and the textured outside needs
+// 1° more per 0.025 mm of texture depth. The 2° walls pass the plain rule; the textured outside (the -pull half)
+// falls short.
+Record MoldingPolicySpec {
+ MinimumDraft: Angle
+}
+
+Static HouseRule: MoldingPolicySpec = MoldingPolicySpec {
+ MinimumDraft: 1.5deg
+}
+
+Model Cup {
+ units: mm
+ Axis spindle { origin: [0mm, 0mm, 0mm]; direction: [0, 0, 1] }
+ Concept Struct meridian on XZ {
+ Polygon2 section { points: [[0mm, 0mm], [30mm, 0mm], [31.397mm, 40mm], [0mm, 40mm]] }
+ }
+ Profile outline using meridian { Loop Outer { section |> TraceLoop } }
+ Revolve<Hollow> body { profile: outline; about: spindle; angle: full; wallThickness: 1.5mm; openings: [Top] }
+}
+
+Mold CupTool {
+ part: Cup
+ material: PP
+ policy: HouseRule
+ stage: Concept
+ pull: +Z
+ parting: Plane { at: face(+Z) }
+ texture: { faces: [side(-pull)]; depth: 0.025mm }
+}
diff --git a/fixtures/Canonical/Mold/drafted-cup.firmament b/fixtures/Canonical/Mold/drafted-cup.firmament
new file mode 100644
index 00000000..910ea16f
--- /dev/null
+++ b/fixtures/Canonical/Mold/drafted-cup.firmament
@@ -0,0 +1,19 @@
+// A turned cup with 2° walls: releases along its axis with no findings.
+Model Cup {
+ units: mm
+ Axis spindle { origin: [0mm, 0mm, 0mm]; direction: [0, 0, 1] }
+ Concept Struct meridian on XZ {
+ Polygon2 section { points: [[0mm, 0mm], [30mm, 0mm], [31.397mm, 40mm], [0mm, 40mm]] }
+ }
+ Profile outline using meridian { Loop Outer { section |> TraceLoop } }
+ Revolve<Hollow> body { profile: outline; about: spindle; angle: full; wallThickness: 1.5mm; openings: [Top] }
+}
+
+Mold CupTool {
+ part: Cup
+ material: PP
+ stage: Tooling
+ pull: +Z
+ parting: Plane { at: face(+Z) }
+ cosmetic: [face(-Z)]
+}
diff --git a/fixtures/Canonical/Mold/tray-concept.firmament b/fixtures/Canonical/Mold/tray-concept.firmament
new file mode 100644
index 00000000..d657226b
--- /dev/null
+++ b/fixtures/Canonical/Mold/tray-concept.firmament
@@ -0,0 +1,20 @@
+// A rounded tray at its first mold review: vertical walls, so every wall reports insufficient draft,
+// and nothing else. The parting plane sits at the rim; the core forms the inside.
+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 }
+ }
+}
+
+Mold TrayTool {
+ part: RoundedTray
+ material: ABS
+ stage: Concept
+ pull: +Z
+ parting: Plane { at: face(+Z) }
+ cosmetic: [face(-Z)]
+}
diff --git a/fixtures/Invalid/Mold/bottle-shoulder-undercut.firmament b/fixtures/Invalid/Mold/bottle-shoulder-undercut.firmament
new file mode 100644
index 00000000..47f97fc5
--- /dev/null
+++ b/fixtures/Invalid/Mold/bottle-shoulder-undercut.firmament
@@ -0,0 +1,18 @@
+// A bottle cannot be core-pulled along its axis: the inside of the shoulder hangs over the cavity.
+Model Bottle {
+ units: mm
+ Axis spindle { origin: [0mm, 0mm, 0mm]; direction: [0, 0, 1] }
+ Concept Struct meridian on XZ {
+ Polygon2 section { points: [[0mm, 0mm], [30mm, 0mm], [32mm, 40mm], [14mm, 58mm], [14mm, 75mm], [0mm, 75mm]] }
+ }
+ Profile outline using meridian { Loop Outer { section |> TraceLoop } }
+ Revolve<Hollow> body { profile: outline; about: spindle; angle: full; wallThickness: 1.5mm; openings: [Top] }
+}
+
+Mold BottleTool {
+ part: Bottle
+ material: PP
+ stage: Prototype
+ pull: +Z
+ parting: Plane { at: face(+Z) }
+}
diff --git a/fixtures/Invalid/Mold/pulley-groove-undercut.firmament b/fixtures/Invalid/Mold/pulley-groove-undercut.firmament
new file mode 100644
index 00000000..aa4de746
--- /dev/null
+++ b/fixtures/Invalid/Mold/pulley-groove-undercut.firmament
@@ -0,0 +1,19 @@
+// A grooved pulley with a bore, molded along its axis: the groove's upper face looks down onto the lower flange and its floor is
+// hidden from both halves. Molded this way it needs a split cavity (side actions); along a diameter it would not.
+Model Pulley {
+ units: mm
+ Axis spindle { origin: [0mm, 0mm, 0mm]; direction: [0, 0, 1] }
+ Concept Struct meridian on XZ {
+ Polygon2 section { points: [[5mm, 0mm], [20mm, 0mm], [20mm, 5mm], [14mm, 5mm], [14mm, 10mm], [20mm, 10mm], [20mm, 15mm], [5mm, 15mm]] }
+ }
+ Profile outline using meridian { Loop Outer { section |> TraceLoop } }
+ Revolve body { profile: outline; about: spindle; angle: full }
+}
+
+Mold PulleyTool {
+ part: Pulley
+ material: POM
+ stage: Tooling
+ pull: +Z
+ parting: Plane { origin: [0mm, 0mm, 15mm] }
+}
diff --git a/fixtures/Invalid/Mold/unknown-material.firmament b/fixtures/Invalid/Mold/unknown-material.firmament
new file mode 100644
index 00000000..21e4dd6b
--- /dev/null
+++ b/fixtures/Invalid/Mold/unknown-material.firmament
@@ -0,0 +1,10 @@
+Model Plate {
+ units: mm
+ Box Base { size: [40mm, 40mm, 3mm] }
+}
+
+Mold PlateTool {
+ part: Plate
+ material: Unobtainium
+ pull: +Z
+}