Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Extend sheet metal templates and expose flat pattern validation

Yuechen Li408fc69ddc79
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index 7020f2e4..64fe2b8a 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -512,10 +512,10 @@ public static class CliRunner
stderr.WriteLine($"Unknown or invalid sheetmetal option '{args[i]}'.");stderr.WriteLine(SheetMetalUsage);return 1;
}
if(!File.Exists(input)){stderr.WriteLine($"Sheet Metal input was not found: {input}");return 1;}
- SheetMetalPartIr? part;SheetThicknessRecognition? thickness=null;TimeSpan importTime=TimeSpan.Zero,recognitionTime=TimeSpan.Zero;SheetMetalAuthoringTimings? authoredTimings=null;SheetMetalConstructionSpec? authoredSpec=null;IReadOnlyList<SheetMetalDiagnostic> recognitionDiagnostics;
+ SheetMetalPartIr? part;SheetThicknessRecognition? thickness=null;TimeSpan importTime=TimeSpan.Zero,recognitionTime=TimeSpan.Zero;SheetMetalAuthoringTimings? authoredTimings=null;SheetMetalConstructionSpec? authoredSpec=null;IReadOnlyList<Aetheris.Kernel.Firmament.FirmamentV2.ConceptIrTemplateInstantiation> templateInstantiations=[];IReadOnlyList<SheetMetalDiagnostic> recognitionDiagnostics;
var source=File.ReadAllText(input);if(SheetMetalFirmament.LooksLikeSheetMetal(source))
{
- var authored=SheetMetalFirmament.Compile(source,input);part=authored.Part;authoredSpec=authored.Spec;authoredTimings=authored.Timings;recognitionDiagnostics=authored.Diagnostics;if(!authored.IsSuccess||part is null){WriteFailure(authored.Diagnostics);return 1;}
+ var authored=SheetMetalFirmament.Compile(source,input);part=authored.Part;authoredSpec=authored.Spec;authoredTimings=authored.Timings;templateInstantiations=authored.TemplateInstantiations??[];recognitionDiagnostics=authored.Diagnostics;if(!authored.IsSuccess||part is null){WriteFailure(authored.Diagnostics);return 1;}
part=part with{FlatPatternPolicy=new(requestedK??part.FlatPatternPolicy.KFactor)};
}
else
@@ -541,7 +541,8 @@ public static class CliRunner
}
var body=part.FormedBody;var supportFamilies=body?.Topology.Faces.GroupBy(f=>body.TryGetFaceSurfaceGeometry(f.Id,out var s)?s?.Kind.ToString()??"Unknown":"Unknown").OrderBy(g=>g.Key).ToDictionary(g=>g.Key,g=>g.Count());
var pmiIndicators=Regex.Matches(source,"(DRAUGHTING_MODEL|GEOMETRIC_TOLERANCE|DATUM_FEATURE|ANNOTATION_OCCURRENCE|SHAPE_ASPECT)",RegexOptions.IgnoreCase).Count;
- var report=new{command=$"sheetmetal {operation}",success=true,input,sourceAuthority=SheetMetalFirmament.LooksLikeSheetMetal(source)?(source.Contains("Intent: Reconstructed",StringComparison.OrdinalIgnoreCase)?"Firmament reconstructed engineering authority":source.Contains("RecoveredRegion",StringComparison.Ordinal)?"Firmament recovered sheet-metal semantics":"Firmament authored semantics"):"STEP formed BRep (not mutated)",recognitionStatus=part.RecognitionStatus,thickness=new{nominal=part.Thickness,tolerance=thickness?.Tolerance,evidencePairs=thickness?.SourcePairs.Count(p=>p.Admitted)??0,outlierFaces=thickness?.OutlierFaceIds.Count??0},geometry=new{bodies=body?.Topology.Bodies.Count()??0,shells=body?.Topology.Shells.Count()??0,faces=body?.Topology.Faces.Count()??0,edges=body?.Topology.Edges.Count()??0,vertices=body?.Topology.Vertices.Count()??0,supportFamilies,pmiIndicators},sheetMetal=new{baseRegion=part.BaseRegionId,regions=part.Regions.Select(r=>new{r.StableId,r.Kind,r.ApproximateArea,sourceFaces=r.Source.FaceIds}),bends=part.Bends.Select(b=>new{b.StableId,b.AxisOrigin,b.AxisDirection,angleDegrees=b.BendAngleRadians*180/Math.PI,b.InsideRadius,b.Direction,b.AdjacentRegionA,b.AdjacentRegionB,sourceFaces=b.Source.FaceIds}),cuts=part.Features.Select(f=>new{f.StableId,f.Kind,f.OwningRegionId,f.Diameter,sourceFaces=f.Source.FaceIds}),conceptPaths},flatPattern=new{flat.Status,flat.Bounds,bendLines=flat.BendLines.Count,cuts=flat.CutLoops.Count,exactBlank=flat.ExactBlankContour is not null,kFactor=flat.Policy.KFactor,flat.DeterministicHash,svg=output,step=flatStepOutput,firmament=firmamentOutput},dfm=new{dfm.Overall,findings=dfm.Findings},diagnostics=allDiagnostics,timingsMilliseconds=new{parse=authoredTimings?.ParseMilliseconds,formedLower=authoredTimings?.FormedLowerMilliseconds,authoredFlatLower=authoredTimings?.FlatLowerMilliseconds,import=importTime.TotalMilliseconds,recognition=recognitionTime.TotalMilliseconds,flatten=flattenClock.Elapsed.TotalMilliseconds}};
+ var exactValidation=flat.ExactBlankContour is null?null:PlanarContourKernel.Validate(flat.ExactBlankContour);
+ var report=new{command=$"sheetmetal {operation}",success=true,input,sourceAuthority=SheetMetalFirmament.LooksLikeSheetMetal(source)?(source.Contains("Intent: Reconstructed",StringComparison.OrdinalIgnoreCase)?"Firmament reconstructed engineering authority":source.Contains("RecoveredRegion",StringComparison.Ordinal)?"Firmament recovered sheet-metal semantics":"Firmament authored semantics"):"STEP formed BRep (not mutated)",recognitionStatus=part.RecognitionStatus,thickness=new{nominal=part.Thickness,tolerance=thickness?.Tolerance,evidencePairs=thickness?.SourcePairs.Count(p=>p.Admitted)??0,outlierFaces=thickness?.OutlierFaceIds.Count??0},geometry=new{bodies=body?.Topology.Bodies.Count()??0,shells=body?.Topology.Shells.Count()??0,faces=body?.Topology.Faces.Count()??0,edges=body?.Topology.Edges.Count()??0,vertices=body?.Topology.Vertices.Count()??0,supportFamilies,pmiIndicators},sheetMetal=new{baseRegion=part.BaseRegionId,regions=part.Regions.Select(r=>new{r.StableId,r.Kind,r.ApproximateArea,sourceFaces=r.Source.FaceIds}),bends=part.Bends.Select(b=>new{b.StableId,b.AxisOrigin,b.AxisDirection,angleDegrees=b.BendAngleRadians*180/Math.PI,b.InsideRadius,b.Direction,b.AdjacentRegionA,b.AdjacentRegionB,sourceFaces=b.Source.FaceIds}),cuts=part.Features.Select(f=>new{f.StableId,f.Kind,f.OwningRegionId,f.Diameter,sourceFaces=f.Source.FaceIds}),reliefs=part.Reliefs?.Count??0,conceptPaths,templateInstantiations},flatPattern=new{flat.Status,flat.Bounds,bendLines=flat.BendLines.Count,cuts=flat.CutLoops.Count,reliefs=flat.ReliefLoops?.Count??0,exactBlank=flat.ExactBlankContour is not null,outerLoops=flat.ExactBlankContour is null?0:1,innerLoops=flat.ExactBlankContour?.InnerLoops.Count??0,connectedMaterialRegions=flat.ExactBlankContour is null?0:1,selfIntersects=exactValidation?.Diagnostics.Any(x=>x.Code=="planar-contour-self-intersection")??false,exactContoursValid=exactValidation?.IsValid??false,fallbackUsed=authoredSpec is not null&&flat.ExactBlankContour is null,kFactor=flat.Policy.KFactor,flat.DeterministicHash,svg=output,step=flatStepOutput,firmament=firmamentOutput},dfm=new{dfm.Overall,findings=dfm.Findings},diagnostics=allDiagnostics,timingsMilliseconds=new{parse=authoredTimings?.ParseMilliseconds,formedLower=authoredTimings?.FormedLowerMilliseconds,authoredFlatLower=authoredTimings?.FlatLowerMilliseconds,import=importTime.TotalMilliseconds,recognition=recognitionTime.TotalMilliseconds,flatten=flattenClock.Elapsed.TotalMilliseconds}};
if(json)stdout.WriteLine(JsonSerializer.Serialize(report,JsonOptions));else
{
stdout.WriteLine($"Sheet Metal: {part.RecognitionStatus} ({report.sourceAuthority})");stdout.WriteLine($"Thickness: {part.Thickness:G8} mm{(thickness is null?" authored/recovered":$" ± {thickness.Tolerance:G4} mm, {thickness.SourcePairs.Count(p=>p.Admitted)} paired supports")}");stdout.WriteLine($"Regions: {part.Regions.Count} ({part.Regions.Count(r=>r.Kind==SheetRegionKind.Planar)} planar, {part.Regions.Count(r=>r.Kind==SheetRegionKind.CylindricalBend)} cylindrical)");stdout.WriteLine($"Bends: {part.Bends.Count}; cuts: {part.Features.Count}; base: {part.BaseRegionId}");foreach(var bend in part.Bends)stdout.WriteLine($" {bend.StableId}: {bend.BendAngleRadians*180/Math.PI:G5} deg, R{bend.InsideRadius:G6}, {bend.Direction}, {bend.AdjacentRegionA} -> {bend.AdjacentRegionB}");stdout.WriteLine($"Flat pattern: {flat.Status}; {(flat.Bounds is null?"no bounds":$"{flat.Bounds.Width:G8} x {flat.Bounds.Height:G8} mm")}; K={flat.Policy.KFactor:G4}; hash={flat.DeterministicHash}");if(flatStepOutput is not null)stdout.WriteLine($"STEP: {flatStepOutput}");if(firmamentOutput is not null)stdout.WriteLine($"Firmament: {firmamentOutput}");if(output is not null)stdout.WriteLine($"SVG: {output}");foreach(var d in allDiagnostics)stdout.WriteLine($" [{d.Severity}] {d.Code}: {d.Message}");
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.cs
index 5c9543ca..7c66e69f 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.cs
@@ -35,6 +35,29 @@ public sealed record FirmamentHostTemplateExpansion(
string SpecializationIdentity,
IReadOnlyDictionary<string, IReadOnlyDictionary<string, string>> RecordArguments);
+public sealed record FirmamentTemplateSourceExpansion(
+ string ExpandedSource,
+ IReadOnlyList<ConceptIrTemplateInstantiation> Instantiations);
+
+/// <summary>
+/// Expands user-authored generic Templates before a domain compiler consumes the
+/// concrete declarations. Domain modules use this same typed parser/binder as the
+/// canonical Firmament V2 frontend; they do not implement their own substitution.
+/// </summary>
+public static class FirmamentTemplateSourceCompiler
+{
+ public static FirmamentTemplateSourceExpansion? Expand(
+ string source,
+ out IReadOnlyList<string> diagnostics)
+ {
+ ArgumentNullException.ThrowIfNull(source);
+ var collected = new List<string>();
+ var expansion = FirmamentV2TemplateExpansion.Expand(source, collected);
+ diagnostics = collected.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray();
+ return expansion is null ? null : new(expansion.Source, expansion.Instantiations);
+ }
+}
+
/// <summary>
/// Narrow public seam for Forge. Template declarations are parsed once into compiler IR and host
/// invocations enter the existing typed binder directly; this is not a general source-rewrite API.
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs
index a0c34e52..33a7830c 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs
@@ -253,7 +253,7 @@ internal static class FirmamentV2TemplateExpansion
foreach (Match start in Regex.Matches(source, @"\bTemplate\s*<", RegexOptions.CultureInvariant))
{
var open = source.IndexOf('<', start.Index); var close = Matching(source, open, '<', '>');
- var header = close < 0 ? Match.Empty : Regex.Match(source[(close + 1)..], @"^\s*(?<kind>Concept\s+Struct|Struct|Model|Panel)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)(?<tail>\s*:\s*[A-Za-z_][A-Za-z0-9_]*)?\s*\{", RegexOptions.CultureInvariant);
+ var header = close < 0 ? Match.Empty : Regex.Match(source[(close + 1)..], @"^\s*(?<kind>Concept\s+Struct|Struct|Model|Panel|SheetMetal)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)(?<tail>\s*:\s*[A-Za-z_][A-Za-z0-9_]*)?\s*\{", RegexOptions.CultureInvariant);
if (close < 0 || !header.Success) { diagnostics.Add(FirmamentV2Parser.UnsupportedConstruct); continue; }
var brace = close + 1 + header.Index + header.Value.LastIndexOf('{'); var end = Matching(source, brace, '{', '}');
if (end < 0) { diagnostics.Add(FirmamentV2Parser.UnsupportedConstruct); continue; }
@@ -285,7 +285,7 @@ internal static class FirmamentV2TemplateExpansion
private static ImmutableArray<TemplateApplicationIr> ParseApplications(string source, IReadOnlyDictionary<string, TemplateDeclarationIr> templates, List<string> diagnostics)
{
var result = ImmutableArray.CreateBuilder<TemplateApplicationIr>();
- foreach (Match start in Regex.Matches(source, @"\b(?<kind>Concept\s+Struct|Struct|Model|Panel)\s+(?<instance>[A-Za-z_][A-Za-z0-9_]*)\s*=\s*(?<template>[A-Za-z_][A-Za-z0-9_]*)\s*<", RegexOptions.CultureInvariant))
+ foreach (Match start in Regex.Matches(source, @"\b(?<kind>Concept\s+Struct|Struct|Model|Panel|SheetMetal)\s+(?<instance>[A-Za-z_][A-Za-z0-9_]*)\s*=\s*(?<template>[A-Za-z_][A-Za-z0-9_]*)\s*<", RegexOptions.CultureInvariant))
{
if (!templates.ContainsKey(start.Groups["template"].Value)) continue;
var open = source.IndexOf('<', start.Index); var close = Matching(source, open, '<', '>');
diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs
index 4ec0719e..b658ed01 100644
--- a/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticSectionStackCompiler.cs
@@ -413,7 +413,10 @@ public static class PrismaticSectionStackEmitter
private static string CurveKey(LineArcProfileCurve2D curve, double z, (double X, double Y) a, (double X, double Y) b) => curve switch
{
LineArcLineSegment2D => $"L:{P(a)}:{P(b)}:{Q(z)}",
- LineArcCircularArc2D arc => $"A:{P(arc.Center)}:{Q(arc.Radius)}:{P(a)}:{P(b)}:{Q(z)}",
+ // Endpoints alone do not identify a bounded circular arc: complementary
+ // semicircles share the same unordered endpoint pair. Include the exact
+ // domain midpoint so distinct cut-loop arcs never collapse to one edge.
+ LineArcCircularArc2D arc => $"A:{P(arc.Center)}:{Q(arc.Radius)}:{P(a)}:{P(b)}:{P((arc.Center.X+arc.Radius*Math.Cos(arc.StartAngleRadians+arc.SweepAngleRadians*.5d),arc.Center.Y+arc.Radius*Math.Sin(arc.StartAngleRadians+arc.SweepAngleRadians*.5d)))}:{Q(z)}",
_ => throw new NotSupportedException()
};
private static string P((double X, double Y) point) => $"{Q(point.X)},{Q(point.Y)}";
diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs
index 301b84d5..54e9288e 100644
--- a/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs
@@ -124,9 +124,21 @@ public static class ProfileArrangementBuilder
public static ArrangementPointLocation PointInProfile(ResolvedProfile2D profile, (double X, double Y) point)
{
- var loop = profile.Loops.SingleOrDefault();
- if (loop is null) return ArrangementPointLocation.Outside;
- return PointInLoop(loop.Segments.Select(x => x.Geometry).ToArray(), point);
+ // A PrismaticSectionRegion stores each hole as a one-loop profile whose
+ // loop is intentionally tagged non-outer. In that established contract
+ // the profile itself still denotes the bounded region for nesting tests.
+ if(profile.Loops.Count==1)return PointInLoop(profile.Loops[0].Segments.Select(x=>x.Geometry).ToArray(),point);
+ var outer = profile.Loops.SingleOrDefault(x=>x.IsOuter);
+ if (outer is null) return ArrangementPointLocation.Outside;
+ var outerLocation=PointInLoop(outer.Segments.Select(x => x.Geometry).ToArray(), point);
+ if(outerLocation is not ArrangementPointLocation.Inside)return outerLocation;
+ foreach(var inner in profile.Loops.Where(x=>!x.IsOuter))
+ {
+ var innerLocation=PointInLoop(inner.Segments.Select(x=>x.Geometry).ToArray(),point);
+ if(innerLocation==ArrangementPointLocation.OnBoundary)return innerLocation;
+ if(innerLocation==ArrangementPointLocation.Inside)return ArrangementPointLocation.Outside;
+ }
+ return ArrangementPointLocation.Inside;
}
/// <summary>
@@ -588,7 +600,19 @@ public static class ProfileArrangementBuilder
_ => false
};
}
- private static string VertexKey((double X, double Y) p) => $"{Math.Round(p.X / VertexTol):F0},{Math.Round(p.Y / VertexTol):F0}";
+ private static string VertexKey((double X, double Y) p)
+ {
+ // IEEE-754 preserves the sign of zero and the fixed-point formatter renders
+ // it as "-0". That is a numeric no-op but a different graph key from "0",
+ // which used to split one exact vertex into two nodes when symmetric Sheet
+ // Metal relief operations approached an axis from opposite sides.
+ static double Bucket(double value)
+ {
+ var rounded = Math.Round(value / VertexTol);
+ return rounded == 0d ? 0d : rounded;
+ }
+ return $"{Bucket(p.X):F0},{Bucket(p.Y):F0}";
+ }
private static double Cross((double X, double Y) a, (double X, double Y) b) => a.X * b.Y - a.Y * b.X;
private static double Distance((double X, double Y) a, (double X, double Y) b) => Math.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y));
}
diff --git a/Aetheris.SheetMetal.Tests/SheetMetalM5Tests.cs b/Aetheris.SheetMetal.Tests/SheetMetalM5Tests.cs
new file mode 100644
index 00000000..fd535dd6
--- /dev/null
+++ b/Aetheris.SheetMetal.Tests/SheetMetalM5Tests.cs
@@ -0,0 +1,144 @@
+using Aetheris.Kernel.Firmament.Materializer;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Step242;
+using Xunit;
+
+namespace Aetheris.SheetMetal.Tests;
+
+public sealed class SheetMetalM5Tests
+{
+ [Fact]
+ public void FourSemanticReliefsComposeOneExactConnectedBlank()
+ {
+ var result=SheetMetalFirmament.Compile("""
+ SheetMetal FourReliefTray {
+ Thickness: 1.2mm; KFactor: 0.42;
+ Base Base { Profile: Rectangle { Width: 80mm; Height: 60mm; }; }
+ Flange Front { From: Base.Front; Height: 18mm; Angle: 90deg; Radius: 1.5mm; Relief: Rectangular; }
+ Flange Right { From: Base.Right; Height: 18mm; Angle: 90deg; Radius: 1.5mm; Relief: Rectangular; }
+ Flange Rear { From: Base.Rear; Height: 18mm; Angle: 90deg; Radius: 1.5mm; Relief: Rectangular; }
+ Flange Left { From: Base.Left; Height: 18mm; Angle: 90deg; Radius: 1.5mm; Relief: Rectangular; }
+ }
+ """);
+ Assert.True(result.IsSuccess,string.Join('\n',result.Diagnostics.Select(x=>$"{x.Code}: {x.Message}")));
+ Assert.NotNull(result.FlatPattern!.ExactBlankContour);
+ Assert.Equal(4,result.FlatPattern.ReliefLoops!.Count);
+ Assert.Equal(4,result.FlatPattern.CompositionPlan!.CornerResolutions.Count);
+ Assert.Equal(8,result.FlatPattern.CompositionPlan.MaterialAdditions.Count);
+ Assert.True(PlanarContourKernel.Validate(result.FlatPattern.ExactBlankContour!).IsValid);
+ Assert.Equal(SheetMetalDfmStatus.Pass,SheetMetalDfm.Evaluate(result.Part!,result.FlatPattern).Overall);
+ }
+
+ [Fact]
+ public void UserDefinedGenericSheetMetalTemplateUsesRecordRequireAndConcept()
+ {
+ var source="""
+ Concept SheetMetalPart {
+ Base: SheetRegion
+ Flat: FlatPattern
+ }
+ Record SensorBracketSpec { Width: Length Depth: Length Height: Length Thickness: Length Radius: Length }
+ Static Small: SensorBracketSpec = SensorBracketSpec { Width: 42mm Depth: 24mm Height: 12mm Thickness: 1mm Radius: 1mm }
+ Template < Spec: SensorBracketSpec >
+ SheetMetal SensorBracket: SheetMetalPart {
+ Require Positive => Spec.Width > 0mm && Spec.Height > 0mm
+ Thickness: Spec.Thickness;
+ Base Base { Profile: Rectangle { Width: Spec.Width; Height: Spec.Depth; }; }
+ Flange SensorWall { From: Base.Front; Height: Spec.Height; Angle: 90deg; Radius: Spec.Radius; }
+ }
+ SheetMetal MySensorBracket = SensorBracket < Spec: Small >
+ """;
+ var result=SheetMetalFirmament.Compile(source);
+ Assert.True(result.IsSuccess,string.Join('\n',result.Diagnostics.Select(x=>$"{x.Code}: {x.Message}")));
+ var instance=Assert.Single(result.TemplateInstantiations!);
+ Assert.Equal("SensorBracket",instance.Template);
+ Assert.Equal("MySensorBracket",instance.Instance);
+ Assert.NotNull(result.FlatPattern!.ExactBlankContour);
+ }
+
+ [Fact]
+ public void ClaimedSheetMetalConceptMissingMemberIsTypedCompileFailure()
+ {
+ var source="""
+ Concept Tray {
+ Base: SheetRegion
+ Front: SheetFlange
+ Rear: SheetFlange
+ Flat: FlatPattern
+ }
+ Template < PartWidth: Length >
+ SheetMetal BadTray: Tray {
+ Thickness: 1mm;
+ Base Base { Profile: Rectangle { Width: PartWidth; Height: 30mm; }; }
+ Flange Front { From: Base.Front; Height: 10mm; Angle: 90deg; Radius: 1mm; }
+ }
+ SheetMetal Broken = BadTray < PartWidth: 40mm >
+ """;
+ var result=SheetMetalFirmament.Compile(source);
+ Assert.False(result.IsSuccess);
+ Assert.Contains(result.Diagnostics,x=>x.Code=="firmament-concept-missing-member"&&x.Message.Contains("Rear",StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void ClaimedSheetMetalConceptIncompatibleMemberTypeIsTypedCompileFailure()
+ {
+ var result=SheetMetalFirmament.Compile("""
+ Concept WrongPart { Base: SheetFlange }
+ Template < PartWidth: Length > SheetMetal Wrong: WrongPart {
+ Thickness: 1mm;
+ Base Base { Profile: Rectangle { Width: PartWidth; Height: 30mm; }; }
+ Flange Wall { From: Base.Front; Height: 10mm; Angle: 90deg; Radius: 1mm; }
+ }
+ SheetMetal Broken = Wrong < PartWidth: 40mm >
+ """);
+ Assert.False(result.IsSuccess);
+ Assert.Contains(result.Diagnostics,x=>x.Code=="firmament-concept-type-mismatch"&&x.Message.Contains("SheetRegion",StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void StandardLibraryTrayAndLidAreOrdinaryGenericTemplateSpecializations()
+ {
+ var tray=SheetMetalFirmament.Compile(SheetMetalTemplateLibrary.Source+"""
+ Static DemoTray: TraySpec = TraySpec { Width: 90mm Depth: 65mm WallHeight: 20mm Thickness: 1.2mm InsideRadius: 1.5mm KFactor: 0.42 ReliefPolicy: Round }
+ SheetMetal TrayA = FourWallTray < Spec: DemoTray >
+ """);
+ var lid=SheetMetalFirmament.Compile(SheetMetalTemplateLibrary.Source+"""
+ Static DemoLid: LidSpec = LidSpec { Width: 92mm Depth: 67mm SkirtHeight: 8mm Clearance: 1mm Thickness: 1.2mm InsideRadius: 1.5mm KFactor: 0.42 ReliefPolicy: Rectangular }
+ SheetMetal LidA = RemovablePanLid < Spec: DemoLid >
+ """);
+ Assert.True(tray.IsSuccess,string.Join('\n',tray.Diagnostics.Select(x=>$"{x.Code}: {x.Message}")));
+ Assert.True(lid.IsSuccess,string.Join('\n',lid.Diagnostics.Select(x=>$"{x.Code}: {x.Message}")));
+ Assert.NotNull(tray.FlatPattern!.ExactBlankContour);Assert.NotNull(lid.FlatPattern!.ExactBlankContour);
+ Assert.Equal(4,tray.Part!.Reliefs!.Count);Assert.Equal(4,lid.Part!.Reliefs!.Count);
+ }
+
+ [Fact]
+ public void ForgeFacingMakeEnclosureSpecializesSameTemplateAndKeepsPathShape()
+ {
+ var a=SheetMetalProductFamilies.MakeEnclosure(new(120,90,35,6,1.2,1.5),"NetworkA");
+ var b=SheetMetalProductFamilies.MakeEnclosure(new(240,180,60,8,1.5,2),"PsuB");
+ Assert.NotEqual(a.SpecializationIdentity,b.SpecializationIdentity);
+ Assert.Equal(a.SemanticPaths.Select(x=>x.Path),b.SemanticPaths.Select(x=>x.Path));
+ Assert.NotNull(a.FlatPattern.ExactBlankContour);Assert.NotNull(b.FlatPattern.ExactBlankContour);
+ Assert.Equal(SheetMetalDfmStatus.Pass,a.Dfm.Overall);Assert.Equal(SheetMetalDfmStatus.Pass,b.Dfm.Overall);
+ Assert.Contains(a.SemanticPaths,x=>x.Path=="Body.Front");
+ Assert.Contains(a.SemanticPaths,x=>x.Path=="FrontLip.Outer");
+ Assert.Equal(a.Compilation.FlatPattern!.CutLoops.Count,a.Fabrication.InnerCutContours.Count);
+ }
+
+ [Fact]
+ public void MultiCutNetworkFixtureExportsAnEnclosedReimportableFlatStep()
+ {
+ var root=FindRepoRoot();var result=SheetMetalFirmament.CompileFile(Path.Combine(root,"fixtures/FirmamentV2/SheetMetal/m5-network-appliance-enclosure.firmament"));
+ Assert.True(result.IsSuccess,string.Join('\n',result.Diagnostics.Select(x=>$"{x.Code}: {x.Message}")));
+ Assert.Equal(12,result.FlatPattern!.CutLoops.Count);Assert.Equal(12,result.FlatPattern.ExactBlankContour!.InnerLoops.Count);
+ var flat=SheetMetalManufacturingArtifacts.BuildFlatBody(result.Part!,result.FlatPattern);Assert.True(flat.IsSuccess,string.Join('\n',flat.Diagnostics.Select(x=>x.Message)));
+ var step=Step242Exporter.ExportBody(flat.Body!);Assert.True(step.IsSuccess);
+ var imported=Step242Importer.ImportBody(step.Value);Assert.True(imported.IsSuccess);
+ var preflight=BrepExportPreflight.Validate(imported.Value);Assert.True(preflight.IsValid,string.Join('\n',preflight.Diagnostics.Select(x=>$"{x.Code}: {x.Message}")));
+ Assert.Equal(SheetMetalDfmStatus.Pass,SheetMetalDfm.Evaluate(result.Part!,result.FlatPattern).Overall);
+ Assert.Contains(SheetMetalConceptPaths.Inspect(result.Spec!,result.Part!,result.FlatPattern),x=>x.Path=="Rear.RearEthernet");
+ }
+
+ private static string FindRepoRoot(){var dir=new DirectoryInfo(AppContext.BaseDirectory);while(dir is not null&&!File.Exists(Path.Combine(dir.FullName,"Aetheris.slnx")))dir=dir.Parent;return dir?.FullName??throw new InvalidOperationException("Repo root not found.");}
+}
diff --git a/Aetheris.SheetMetal/Aetheris.SheetMetal.csproj b/Aetheris.SheetMetal/Aetheris.SheetMetal.csproj
index adb34bc3..5c46d0f2 100644
--- a/Aetheris.SheetMetal/Aetheris.SheetMetal.csproj
+++ b/Aetheris.SheetMetal/Aetheris.SheetMetal.csproj
@@ -2,4 +2,5 @@
<PropertyGroup><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>
<ItemGroup><ProjectReference Include="..\Aetheris.Modules\Aetheris.Modules.csproj" /><ProjectReference Include="..\Aetheris.Surfacing\Aetheris.Surfacing.csproj" /></ItemGroup>
<ItemGroup><ProjectReference Include="..\Aetheris.Kernel.Core\Aetheris.Kernel.Core.csproj" /><ProjectReference Include="..\Aetheris.Kernel.Firmament\Aetheris.Kernel.Firmament.csproj" /></ItemGroup>
+ <ItemGroup><EmbeddedResource Include="Firmament\SheetMetalProductFamilies.firmament" /></ItemGroup>
</Project>
diff --git a/Aetheris.SheetMetal/BlankCompositionPlan.cs b/Aetheris.SheetMetal/BlankCompositionPlan.cs
new file mode 100644
index 00000000..3c769f80
--- /dev/null
+++ b/Aetheris.SheetMetal/BlankCompositionPlan.cs
@@ -0,0 +1,33 @@
+using Aetheris.Kernel.Firmament.Materializer;
+
+namespace Aetheris.SheetMetal;
+
+public enum BlankCompositionOperationKind
+{
+ AddMaterialRegion,
+ ResolveCornerRelief,
+ InsertThroughCut
+}
+
+public sealed record BlankCompositionOperation(
+ string StableId,
+ BlankCompositionOperationKind Kind,
+ string SemanticOwner,
+ PlanarContour2 Contour,
+ string ExpectedTopology,
+ int Order);
+
+/// <summary>
+/// Exact material-composition authority for an authored flat blank. Operations are
+/// ordered by known Sheet Metal topology; this is deliberately not an arbitrary
+/// polygon Boolean request.
+/// </summary>
+public sealed record BlankCompositionPlan(
+ string PartId,
+ PlanarContour2 BaseContour,
+ IReadOnlyList<BlankCompositionOperation> OrderedOperations)
+{
+ public IReadOnlyList<BlankCompositionOperation> MaterialAdditions=>OrderedOperations.Where(x=>x.Kind==BlankCompositionOperationKind.AddMaterialRegion).ToArray();
+ public IReadOnlyList<BlankCompositionOperation> CornerResolutions=>OrderedOperations.Where(x=>x.Kind==BlankCompositionOperationKind.ResolveCornerRelief).ToArray();
+ public IReadOnlyList<BlankCompositionOperation> Cuts=>OrderedOperations.Where(x=>x.Kind==BlankCompositionOperationKind.InsertThroughCut).ToArray();
+}
diff --git a/Aetheris.SheetMetal/Firmament/SheetMetalProductFamilies.firmament b/Aetheris.SheetMetal/Firmament/SheetMetalProductFamilies.firmament
new file mode 100644
index 00000000..3364e978
--- /dev/null
+++ b/Aetheris.SheetMetal/Firmament/SheetMetalProductFamilies.firmament
@@ -0,0 +1,151 @@
+// Sheet Metal product-family standard library.
+// Template is typed compile-time generic programming, not a prefab/document template.
+
+Concept SheetMetalPart {
+ Base: SheetRegion
+ Flat: FlatPattern
+}
+
+Concept Tray {
+ Base: SheetRegion
+ Front: SheetFlange
+ Right: SheetFlange
+ Rear: SheetFlange
+ Left: SheetFlange
+ Flat: FlatPattern
+}
+
+Concept RemovableLid {
+ Top: SheetRegion
+ Front: SheetFlange
+ Right: SheetFlange
+ Rear: SheetFlange
+ Left: SheetFlange
+ Flat: FlatPattern
+}
+
+Concept Enclosure {
+ Body: SheetRegion
+ Front: SheetFlange
+ Right: SheetFlange
+ Rear: SheetFlange
+ Left: SheetFlange
+ FrontLip: SheetFlange
+ Flat: FlatPattern
+}
+
+Enum SheetMetalReliefPolicy {
+ Auto
+ Rectangular
+ Round
+}
+
+Record LBracketSpec {
+ Width: Length
+ Depth: Length
+ FlangeHeight: Length
+ Thickness: Length
+ InsideRadius: Length
+ KFactor: float
+ ReliefPolicy: SheetMetalReliefPolicy
+}
+
+Record UChannelSpec {
+ Width: Length
+ Depth: Length
+ WallHeight: Length
+ Thickness: Length
+ InsideRadius: Length
+ KFactor: float
+ ReliefPolicy: SheetMetalReliefPolicy
+}
+
+Record TraySpec {
+ Width: Length
+ Depth: Length
+ WallHeight: Length
+ Thickness: Length
+ InsideRadius: Length
+ KFactor: float
+ ReliefPolicy: SheetMetalReliefPolicy
+}
+
+Record LidSpec {
+ Width: Length
+ Depth: Length
+ SkirtHeight: Length
+ Clearance: Length
+ Thickness: Length
+ InsideRadius: Length
+ KFactor: float
+ ReliefPolicy: SheetMetalReliefPolicy
+}
+
+Record EnclosureSpec {
+ Width: Length
+ Depth: Length
+ Height: Length
+ LidLipHeight: Length
+ Thickness: Length
+ InsideRadius: Length
+ KFactor: float
+ ReliefPolicy: SheetMetalReliefPolicy
+}
+
+Template < Spec: LBracketSpec >
+SheetMetal LBracket: SheetMetalPart {
+ Require Positive => Spec.Width > 0mm && Spec.Depth > 0mm && Spec.FlangeHeight > 0mm && Spec.Thickness > 0mm
+ Thickness: Spec.Thickness;
+ KFactor: Spec.KFactor;
+ Base Base { Profile: Rectangle { Width: Spec.Width; Height: Spec.Depth; }; }
+ Flange Wall { From: Base.Front; Height: Spec.FlangeHeight; Angle: 90deg; Radius: Spec.InsideRadius; Relief: Spec.ReliefPolicy; }
+}
+
+Template < Spec: UChannelSpec >
+SheetMetal UChannel: SheetMetalPart {
+ Require Positive => Spec.Width > 0mm && Spec.Depth > 0mm && Spec.WallHeight > 0mm && Spec.Thickness > 0mm
+ Thickness: Spec.Thickness;
+ KFactor: Spec.KFactor;
+ Base Base { Profile: Rectangle { Width: Spec.Width; Height: Spec.Depth; }; }
+ Flange LeftWall { From: Base.Left; Height: Spec.WallHeight; Angle: 90deg; Radius: Spec.InsideRadius; Relief: Spec.ReliefPolicy; }
+ Flange RightWall { From: Base.Right; Height: Spec.WallHeight; Angle: 90deg; Radius: Spec.InsideRadius; Relief: Spec.ReliefPolicy; }
+}
+
+Template < Spec: TraySpec >
+SheetMetal FourWallTray: Tray {
+ Require Positive => Spec.Width > 0mm && Spec.Depth > 0mm && Spec.WallHeight > 0mm && Spec.Thickness > 0mm
+ Require ManufacturableWall => Spec.WallHeight > Spec.InsideRadius
+ Thickness: Spec.Thickness;
+ KFactor: Spec.KFactor;
+ Base Base { Profile: Rectangle { Width: Spec.Width; Height: Spec.Depth; }; }
+ Flange Front { From: Base.Front; Height: Spec.WallHeight; Angle: 90deg; Radius: Spec.InsideRadius; Relief: Spec.ReliefPolicy; }
+ Flange Right { From: Base.Right; Height: Spec.WallHeight; Angle: 90deg; Radius: Spec.InsideRadius; Relief: Spec.ReliefPolicy; }
+ Flange Rear { From: Base.Rear; Height: Spec.WallHeight; Angle: 90deg; Radius: Spec.InsideRadius; Relief: Spec.ReliefPolicy; }
+ Flange Left { From: Base.Left; Height: Spec.WallHeight; Angle: 90deg; Radius: Spec.InsideRadius; Relief: Spec.ReliefPolicy; }
+}
+
+Template < Spec: LidSpec >
+SheetMetal RemovablePanLid: RemovableLid {
+ Require Positive => Spec.Width > 0mm && Spec.Depth > 0mm && Spec.SkirtHeight > 0mm && Spec.Thickness > 0mm
+ Thickness: Spec.Thickness;
+ KFactor: Spec.KFactor;
+ Base Top { Profile: Rectangle { Width: Spec.Width; Height: Spec.Depth; }; }
+ Flange Front { From: Top.Front; Height: Spec.SkirtHeight; Angle: 90deg; Radius: Spec.InsideRadius; Direction: Down; Relief: Spec.ReliefPolicy; }
+ Flange Right { From: Top.Right; Height: Spec.SkirtHeight; Angle: 90deg; Radius: Spec.InsideRadius; Direction: Down; Relief: Spec.ReliefPolicy; }
+ Flange Rear { From: Top.Rear; Height: Spec.SkirtHeight; Angle: 90deg; Radius: Spec.InsideRadius; Direction: Down; Relief: Spec.ReliefPolicy; }
+ Flange Left { From: Top.Left; Height: Spec.SkirtHeight; Angle: 90deg; Radius: Spec.InsideRadius; Direction: Down; Relief: Spec.ReliefPolicy; }
+}
+
+Template < Spec: EnclosureSpec >
+SheetMetal ElectronicsEnclosure: Enclosure {
+ Require Positive => Spec.Width > 0mm && Spec.Depth > 0mm && Spec.Height > 0mm && Spec.Thickness > 0mm
+ Require LipFits => Spec.LidLipHeight > Spec.InsideRadius
+ Thickness: Spec.Thickness;
+ KFactor: Spec.KFactor;
+ Base Body { Profile: Rectangle { Width: Spec.Width; Height: Spec.Depth; }; }
+ Flange Front { From: Body.Front; Height: Spec.Height; Angle: 90deg; Radius: Spec.InsideRadius; Relief: Spec.ReliefPolicy; }
+ Flange Right { From: Body.Right; Height: Spec.Height; Angle: 90deg; Radius: Spec.InsideRadius; Relief: Spec.ReliefPolicy; }
+ Flange Rear { From: Body.Rear; Height: Spec.Height; Angle: 90deg; Radius: Spec.InsideRadius; Relief: Spec.ReliefPolicy; }
+ Flange Left { From: Body.Left; Height: Spec.Height; Angle: 90deg; Radius: Spec.InsideRadius; Relief: Spec.ReliefPolicy; }
+ Flange FrontLip { From: Front.Outer; Height: Spec.LidLipHeight; Angle: 90deg; Radius: Spec.InsideRadius; }
+}
diff --git a/Aetheris.SheetMetal/SheetMetalAuthoredLowering.cs b/Aetheris.SheetMetal/SheetMetalAuthoredLowering.cs
index 1a8c089e..2aafea14 100644
--- a/Aetheris.SheetMetal/SheetMetalAuthoredLowering.cs
+++ b/Aetheris.SheetMetal/SheetMetalAuthoredLowering.cs
@@ -27,7 +27,7 @@ public sealed record AuthoredSheetCutSpec(
public sealed record SheetMetalConstructionSpec(
string Name, double Thickness, string? Material, double KFactor, AuthoredSheetBaseSpec Base,
IReadOnlyList<AuthoredSheetFlangeSpec> Flanges, IReadOnlyList<AuthoredSheetCutSpec> Cuts,
- SheetMetalProvenanceCategory Authority, bool LegacySyntax = false);
+ SheetMetalProvenanceCategory Authority, bool LegacySyntax = false, string? SatisfiesConcept = null);
/// <summary>
/// Bounded high-level authored Sheet Metal compiler. It deliberately consumes only
@@ -42,7 +42,7 @@ internal static class AuthoredSheetMetalCompiler
{
var parseStarted=Stopwatch.GetTimestamp();
var diagnostics = new List<SheetMetalDiagnostic>();
- var header = Regex.Match(source, @"\bSheetMetal\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", Rx);
+ var header = Regex.Match(source, @"\bSheetMetal\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)(?:\s*:\s*(?<concept>[A-Za-z_][A-Za-z0-9_]*))?\s*\{", Rx);
if (!header.Success) return Fail("Expected `SheetMetal <Name> { ... }`.");
if (!Scalar(source, "Thickness", "mm", out var thickness) || thickness <= 0)
return Fail("Thickness must be a positive millimetre value.");
@@ -102,6 +102,9 @@ internal static class AuthoredSheetMetalCompiler
return Fail($"Multiple flanges target {duplicate.First().ParentRegion}.{duplicate.First().EdgeName}.", SheetMetalDiagnosticCodes.DuplicateFlange);
if (flanges.Select(f => f.Name).Append(baseSpec.Name).Distinct(StringComparer.OrdinalIgnoreCase).Count() != flanges.Count + 1)
return Fail("Base and flange names must be unique.", SheetMetalDiagnosticCodes.ImpossibleTopology);
+ foreach(Match extension in Regex.Matches(source,@"\bExtend\s+SheetMetal\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{",Rx))
+ if(!extension.Groups["name"].Value.Equals(header.Groups["name"].Value,StringComparison.Ordinal))
+ return Fail($"Sheet Metal extension targets '{extension.Groups["name"].Value}', but the specialized part is '{header.Groups["name"].Value}'.","sheetmetal-extension-target-mismatch");
var cuts = new List<AuthoredSheetCutSpec>();
foreach (var block in Blocks(source, "Hole"))
@@ -134,7 +137,10 @@ internal static class AuthoredSheetMetalCompiler
var authority = Regex.IsMatch(source, @"\bIntent\s*:\s*Reconstructed\s*;", Rx)
? SheetMetalProvenanceCategory.Reconstructed : SheetMetalProvenanceCategory.Authored;
- var spec = new SheetMetalConstructionSpec(header.Groups["name"].Value, thickness, material, k, baseSpec, flanges, cuts, authority, legacyBase.Success);
+ var concept=header.Groups["concept"].Success?header.Groups["concept"].Value:null;
+ var spec = new SheetMetalConstructionSpec(header.Groups["name"].Value, thickness, material, k, baseSpec, flanges, cuts, authority, legacyBase.Success,concept);
+ if(concept is not null&&SheetMetalConceptContracts.Validate(source,spec) is { } conformanceFailure)
+ return Fail(conformanceFailure.Message,conformanceFailure.Code);
var parseMs=Stopwatch.GetElapsedTime(parseStarted).TotalMilliseconds;var formedStarted=Stopwatch.GetTimestamp();var lowered = AuthoredSheetMetalLowering.Lower(spec, sourcePath);var formedMs=Stopwatch.GetElapsedTime(formedStarted).TotalMilliseconds;
if (!lowered.IsSuccess || lowered.Part is null) return new(false, spec, null, null, lowered.Diagnostics);
var flatStarted=Stopwatch.GetTimestamp();var flat = SheetMetalFlattener.Flatten(lowered.Part);var flatMs=Stopwatch.GetElapsedTime(flatStarted).TotalMilliseconds;
diff --git a/Aetheris.SheetMetal/SheetMetalConceptContracts.cs b/Aetheris.SheetMetal/SheetMetalConceptContracts.cs
new file mode 100644
index 00000000..aaad9004
--- /dev/null
+++ b/Aetheris.SheetMetal/SheetMetalConceptContracts.cs
@@ -0,0 +1,33 @@
+using System.Text.RegularExpressions;
+
+namespace Aetheris.SheetMetal;
+
+internal static class SheetMetalConceptContracts
+{
+ internal sealed record Failure(string Code,string Message);
+
+ internal static Failure? Validate(string source,SheetMetalConstructionSpec spec)
+ {
+ var concept=spec.SatisfiesConcept;
+ if(string.IsNullOrWhiteSpace(concept))return null;
+ var declaration=Regex.Match(source,$@"\bConcept\s+{Regex.Escape(concept)}\s*\{{(?<body>[\s\S]*?)\}}",RegexOptions.CultureInvariant);
+ if(!declaration.Success)return new("firmament-template-unknown-concept-constraint",$"SheetMetal '{spec.Name}' claims unknown Concept '{concept}'.");
+ var available=new Dictionary<string,string>(StringComparer.Ordinal)
+ {
+ [spec.Base.Name]="SheetRegion",
+ ["Flat"]="FlatPattern"
+ };
+ foreach(var flange in spec.Flanges)
+ {
+ available[flange.Name]="SheetFlange";
+ available[flange.Name+"Bend"]="SheetBend";
+ }
+ foreach(Match requirement in Regex.Matches(declaration.Groups["body"].Value,@"(?m)^\s*(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*(?<type>[A-Za-z_][A-Za-z0-9_]*)\s*$",RegexOptions.CultureInvariant))
+ {
+ var name=requirement.Groups["name"].Value;var expected=requirement.Groups["type"].Value;
+ if(!available.TryGetValue(name,out var actual))return new("firmament-concept-missing-member",$"SheetMetal '{spec.Name}' claims to satisfy '{concept}' but does not expose required semantic member '{name}: {expected}'.");
+ if(!string.Equals(expected,actual,StringComparison.Ordinal))return new("firmament-concept-type-mismatch",$"SheetMetal '{spec.Name}.{name}' exposes '{actual}', but Concept '{concept}' requires '{expected}'.");
+ }
+ return null;
+ }
+}
diff --git a/Aetheris.SheetMetal/SheetMetalConceptPaths.cs b/Aetheris.SheetMetal/SheetMetalConceptPaths.cs
index fb22fcba..6f554bf3 100644
--- a/Aetheris.SheetMetal/SheetMetalConceptPaths.cs
+++ b/Aetheris.SheetMetal/SheetMetalConceptPaths.cs
@@ -34,7 +34,11 @@ public static class SheetMetalConceptPaths
Add($"{flange.Name}.RightCorner","SheetCorner",$"{flange.Name}.RightCorner",region?.StableId,$"flat-{region?.StableId}","canonical flange endpoint","CornerAdjacent");
Add($"{flange.Name}.Bend","SheetBend",$"{flange.Name}.Bend",bend?.StableId,$"flat-{bend?.StableId}","authored flange bend","BendBoundary","FlatCorrespondent");
}
- foreach(var cut in spec.Cuts)Add(cut.Name,"SheetCut",cut.Name,cut.Name,cut.Name,"authored cut declaration","FlatFeature","Cuttable");
+ foreach(var cut in spec.Cuts)
+ {
+ Add(cut.Name,"SheetCut",cut.Name,cut.Name,cut.Name,"authored cut declaration","FlatFeature","Cuttable");
+ Add($"{cut.RegionName}.{cut.Name}","SheetCut",$"{cut.RegionName}.{cut.Name}",cut.Name,cut.Name,"semantic owning-region cut path","FlatFeature","Cuttable");
+ }
Add("Flat","FlatPattern",$"flat-{part.StableId}",null,flat?.StableId,"derived flat state","ManufacturingContour");
foreach(var path in paths.Where(x=>x.FormedId is not null&&x.Path!="Flat").ToArray())Add($"Flat.{path.Path}","Flat"+path.Kind,$"Flat.{path.StableId}",path.FormedId,path.FlatId,"formed/flat semantic correspondence",[..path.Capabilities,"FlatState"]);
return paths.OrderBy(x=>x.Path,StringComparer.Ordinal).ToArray();
diff --git a/Aetheris.SheetMetal/SheetMetalDfm.cs b/Aetheris.SheetMetal/SheetMetalDfm.cs
index 86753df6..8b43a912 100644
--- a/Aetheris.SheetMetal/SheetMetalDfm.cs
+++ b/Aetheris.SheetMetal/SheetMetalDfm.cs
@@ -50,11 +50,12 @@ public static class SheetMetalDfm
findings.Add(new("sheetmetal-dfm-flat-overlap",flat.Status==FlatPatternStatus.Overlapping?SheetMetalDfmStatus.Fail:SheetMetalDfmStatus.Pass,flat.Status==FlatPatternStatus.Overlapping?"Flat material regions overlap.":"No planar-region overlap was detected.",flat.StableId,null,null));
foreach(var cut in flat.CutLoops)
{
+ var semanticSubject=$"{part.StableId.Replace("sheetmetal-",string.Empty,StringComparison.Ordinal)}.{cut.SourceRegionId}.{cut.FeatureId}";
var c=new SheetPoint2(cut.Boundary.Average(p=>p.X),cut.Boundary.Average(p=>p.Y));var nearest=flat.BendLines.Count==0?double.PositiveInfinity:cut.Boundary.Min(p=>flat.BendLines.Min(b=>PointLineDistance(p,b.Start,b.End)));var required=policy.MinimumHoleToBendDistanceFactor*part.Thickness;
- findings.Add(new("sheetmetal-dfm-cut-to-bend-distance",double.IsPositiveInfinity(nearest)?SheetMetalDfmStatus.NotEvaluated:nearest>=required?SheetMetalDfmStatus.Pass:SheetMetalDfmStatus.Warning,double.IsPositiveInfinity(nearest)?"No bend line is available for this cut.":$"'{cut.FeatureId}' boundary to nearest bend line is {nearest:G4} mm; parameterized policy requires {required:G4} mm.",cut.FeatureId,double.IsPositiveInfinity(nearest)?null:nearest,required,!double.IsPositiveInfinity(nearest)&&nearest<required?$"Move {cut.FeatureId} at least {required-nearest:G4} mm farther from the nearest bend, subject to engineer review.":null));
+ findings.Add(new("sheetmetal-dfm-cut-to-bend-distance",double.IsPositiveInfinity(nearest)?SheetMetalDfmStatus.NotEvaluated:nearest>=required?SheetMetalDfmStatus.Pass:SheetMetalDfmStatus.Warning,double.IsPositiveInfinity(nearest)?"No bend line is available for this cut.":$"'{semanticSubject}' boundary to nearest bend line is {nearest:G4} mm; parameterized policy requires {required:G4} mm.",semanticSubject,double.IsPositiveInfinity(nearest)?null:nearest,required,!double.IsPositiveInfinity(nearest)&&nearest<required?$"Move {semanticSubject} at least {required-nearest:G4} mm farther from the nearest bend, subject to engineer review.":null));
var owner=flat.Regions2D.FirstOrDefault(r=>r.SourceRegionId==cut.SourceRegionId);var edge=owner is null?double.PositiveInfinity:cut.Boundary.Min(p=>Enumerable.Range(0,owner.Boundary.Count).Min(i=>PointLineDistance(p,owner.Boundary[i],owner.Boundary[(i+1)%owner.Boundary.Count])));
var edgeRequired=policy.MinimumEdgeDistanceFactor*part.Thickness;
- findings.Add(new("sheetmetal-dfm-cut-to-edge-distance",edge>=edgeRequired?SheetMetalDfmStatus.Pass:SheetMetalDfmStatus.Warning,$"'{cut.FeatureId}' boundary to nearest recovered source edge is {edge:G4} mm; bounded policy requires {edgeRequired:G4} mm.",cut.FeatureId,edge,edgeRequired,edge<edgeRequired?$"Move {cut.FeatureId} at least {edgeRequired-edge:G4} mm inward, then re-run exact boundary validation.":null));
+ findings.Add(new("sheetmetal-dfm-cut-to-edge-distance",edge>=edgeRequired?SheetMetalDfmStatus.Pass:SheetMetalDfmStatus.Warning,$"'{semanticSubject}' boundary to nearest recovered source edge is {edge:G4} mm; bounded policy requires {edgeRequired:G4} mm.",semanticSubject,edge,edgeRequired,edge<edgeRequired?$"Move {semanticSubject} at least {edgeRequired-edge:G4} mm inward, then re-run exact boundary validation.":null));
}
}
return new(findings);
diff --git a/Aetheris.SheetMetal/SheetMetalFabricationIr.cs b/Aetheris.SheetMetal/SheetMetalFabricationIr.cs
new file mode 100644
index 00000000..54f174e9
--- /dev/null
+++ b/Aetheris.SheetMetal/SheetMetalFabricationIr.cs
@@ -0,0 +1,31 @@
+using Aetheris.Kernel.Firmament.Materializer;
+
+namespace Aetheris.SheetMetal;
+
+public sealed record FabricationBendLine(
+ string SemanticId,
+ SheetPoint2 Start,
+ SheetPoint2 End,
+ SheetBendDirection Direction,
+ double AngleRadians);
+
+public sealed record SheetMetalFabricationIr(
+ string PartId,
+ string Units,
+ PlanarContourLoop2 OuterCutContour,
+ IReadOnlyList<PlanarContourLoop2> InnerCutContours,
+ IReadOnlyList<FabricationBendLine> BendLines,
+ IReadOnlyList<string> ReliefSemanticIds,
+ string DeterministicHash);
+
+public static class SheetMetalFabricationArtifacts
+{
+ public static SheetMetalFabricationIr Create(SheetMetalPartIr part,SheetMetalFlatPatternIr flat)
+ {
+ ArgumentNullException.ThrowIfNull(part);ArgumentNullException.ThrowIfNull(flat);
+ var contour=flat.ExactBlankContour??throw new InvalidOperationException("Fabrication IR requires an accepted exact blank contour.");
+ return new(part.StableId,"mm",contour.OuterLoop,contour.InnerLoops,
+ flat.BendLines.OrderBy(x=>x.BendId,StringComparer.Ordinal).Select(x=>new FabricationBendLine(x.BendId,x.Start,x.End,x.Direction,x.BendAngleRadians)).ToArray(),
+ (flat.ReliefLoops??[]).OrderBy(x=>x.ReliefId,StringComparer.Ordinal).Select(x=>x.ReliefId).ToArray(),flat.DeterministicHash);
+ }
+}
diff --git a/Aetheris.SheetMetal/SheetMetalFirmament.cs b/Aetheris.SheetMetal/SheetMetalFirmament.cs
index ccb4914e..2f1d32e3 100644
--- a/Aetheris.SheetMetal/SheetMetalFirmament.cs
+++ b/Aetheris.SheetMetal/SheetMetalFirmament.cs
@@ -1,4 +1,5 @@
using System.Text.RegularExpressions;
+using Aetheris.Kernel.Firmament.FirmamentV2;
namespace Aetheris.SheetMetal;
@@ -9,7 +10,8 @@ public sealed record SheetMetalAuthoringResult(
SheetMetalPartIr? Part,
SheetMetalFlatPatternIr? FlatPattern,
IReadOnlyList<SheetMetalDiagnostic> Diagnostics,
- SheetMetalAuthoringTimings? Timings=null);
+ SheetMetalAuthoringTimings? Timings=null,
+ IReadOnlyList<ConceptIrTemplateInstantiation>? TemplateInstantiations=null);
/// <summary>
/// Entry point for the module-owned Sheet Metal dialects. Recovered and historical
@@ -24,7 +26,8 @@ public static class SheetMetalFirmament
{
if(source is null)return false;
var clean=Regex.Replace(source,@"//.*?$|#.*?$",string.Empty,RegexOptions.Multiline);
- return Regex.IsMatch(clean,@"^\s*SheetMetal\s+",RegexOptions.IgnoreCase|RegexOptions.CultureInvariant);
+ return Regex.IsMatch(clean,@"^\s*SheetMetal\s+",RegexOptions.IgnoreCase|RegexOptions.CultureInvariant)
+ ||Regex.IsMatch(clean,@"\bUse\s+SheetMetal\.ProductFamilies\s*;",RegexOptions.IgnoreCase|RegexOptions.CultureInvariant);
}
public static SheetMetalAuthoringResult CompileFile(string path)
@@ -36,10 +39,25 @@ public static class SheetMetalFirmament
public static SheetMetalAuthoringResult Compile(string source,string sourcePath="authored.firmament")
{
- ArgumentNullException.ThrowIfNull(source);var clean=Regex.Replace(source,@"//.*?$|#.*?$",string.Empty,RegexOptions.Multiline);
+ ArgumentNullException.ThrowIfNull(source);
+ if(Regex.IsMatch(source,@"\bUse\s+SheetMetal\.ProductFamilies\s*;",RegexOptions.IgnoreCase|RegexOptions.CultureInvariant))
+ {
+ source=Regex.Replace(source,@"\bUse\s+SheetMetal\.ProductFamilies\s*;",string.Empty,RegexOptions.IgnoreCase|RegexOptions.CultureInvariant);
+ source=SheetMetalTemplateLibrary.Source+Environment.NewLine+source;
+ }
+ IReadOnlyList<ConceptIrTemplateInstantiation> instantiations=[];
+ if(Regex.IsMatch(source,@"\bTemplate\s*<",RegexOptions.CultureInvariant))
+ {
+ var expanded=FirmamentTemplateSourceCompiler.Expand(source,out var templateDiagnostics);
+ if(expanded is null||templateDiagnostics.Count>0)
+ return new(false,null,null,null,templateDiagnostics.Select(x=>new SheetMetalDiagnostic(x.Split(':',2)[0],SheetMetalDiagnosticSeverity.Error,x)).ToArray());
+ source=expanded.ExpandedSource;instantiations=expanded.Instantiations;
+ }
+ var clean=Regex.Replace(source,@"//.*?$|#.*?$",string.Empty,RegexOptions.Multiline);
if(ReconstructedSheetMetalFirmament.IsReconstructed(clean)&&Regex.IsMatch(clean,@"\bEvidenceSource\s*:",Rx))return ReconstructedSheetMetalFirmament.Compile(clean,sourcePath);
if(RecoveredSheetMetalFirmament.IsRecovered(clean))return RecoveredSheetMetalFirmament.Compile(clean,sourcePath);
- return AuthoredSheetMetalCompiler.Compile(clean,sourcePath);
+ var result=AuthoredSheetMetalCompiler.Compile(clean,sourcePath);
+ return result with { TemplateInstantiations=instantiations };
}
private static SheetMetalAuthoringResult Failure(string message)=>new(false,null,null,null,[new("sheetmetal-firmament-invalid",SheetMetalDiagnosticSeverity.Error,message)]);
diff --git a/Aetheris.SheetMetal/SheetMetalFlattener.cs b/Aetheris.SheetMetal/SheetMetalFlattener.cs
index dca64851..642e4e51 100644
--- a/Aetheris.SheetMetal/SheetMetalFlattener.cs
+++ b/Aetheris.SheetMetal/SheetMetalFlattener.cs
@@ -98,7 +98,7 @@ public static class SheetMetalFlattener
if(allPoints.Any(p=>!double.IsFinite(p.X)||!double.IsFinite(p.Y)))return Unsupported("Flat lowering produced non-finite coordinates.");
var bounds=allPoints.Length==0?null:new FlatPatternBounds(allPoints.Min(p=>p.X),allPoints.Min(p=>p.Y),allPoints.Max(p=>p.X),allPoints.Max(p=>p.Y));
var authored=part.Provenance.Contains("source-independent",StringComparison.OrdinalIgnoreCase);
- var exactBlank=authored?BuildExactBlank(part,flatRegions,flatReliefs,diagnostics):null;
+ BlankCompositionPlan? compositionPlan=null;var exactBlank=authored?BuildExactBlank(part,flatRegions,flatReliefs,cuts,diagnostics,out compositionPlan):null;
var boundary=exactBlank is not null?ContourVertices(exactBlank):authored?StitchBoundary(flatRegions):ConvexHull(flatRegions.SelectMany(r=>r.Boundary));
if(authored&&exactBlank is null)diagnostics.Add(new(SheetMetalDiagnosticCodes.ExactBlankContour,SheetMetalDiagnosticSeverity.Warning,"Authored flat material regions contain a point-touch/open-corner topology that the exact single-loop contract rejects; compatibility boundary remains available."));
if(exactBlank is not null)
@@ -108,7 +108,7 @@ public static class SheetMetalFlattener
}
var status=overlaps.Count>0?FlatPatternStatus.Overlapping:(mappings.Count<planar.Count||part.RecognitionStatus==SheetMetalRecognitionStatus.Partial?FlatPatternStatus.Partial:FlatPatternStatus.Valid);
var hash=Hash(flatRegions,bendLines,cuts,flatReliefs,policy,status);
- return new($"flat-{part.StableId}",status,flatRegions,bendLines.OrderBy(b=>b.BendId,StringComparer.Ordinal).ToArray(),cuts,mappings.Values.OrderBy(m=>m.Region.StableId,StringComparer.Ordinal).Select(m=>m.Public()).ToArray(),boundary,bounds,policy,evidence,diagnostics,hash,exactBlank,flatReliefs);
+ return new($"flat-{part.StableId}",status,flatRegions,bendLines.OrderBy(b=>b.BendId,StringComparer.Ordinal).ToArray(),cuts,mappings.Values.OrderBy(m=>m.Region.StableId,StringComparer.Ordinal).Select(m=>m.Public()).ToArray(),boundary,bounds,policy,evidence,diagnostics,hash,exactBlank,flatReliefs,compositionPlan);
SheetMetalFlatPatternIr Unsupported(string message)=>new($"flat-{part.StableId}",FlatPatternStatus.Unsupported,[],[],[],[],[],null,policy,[],[new(SheetMetalDiagnosticCodes.UnsupportedBendTopology,SheetMetalDiagnosticSeverity.Error,message)],SheetMetalRecognizer.StableHash(message));
}
@@ -169,21 +169,35 @@ public static class SheetMetalFlattener
var c=(center.X,center.Y);var provenance=new ProfileSegmentProvenance($"{id}.circle",id,id,"SheetMetalFlatPatternIr:analytic circle","XY");
return new(id,"XY",new($"{id}.outer",true,[new($"{id}.arc0",new LineArcCircularArc2D(c,radius,0,Math.PI),provenance),new($"{id}.arc1",new LineArcCircularArc2D(c,radius,Math.PI,Math.PI),provenance with { StableId=$"{id}.circle.1" })]),[],$"SheetMetalFlatPatternIr:analytic circle radius={radius:R}");
}
- private static PlanarContour2? BuildExactBlank(SheetMetalPartIr part,IReadOnlyList<FlatRegion2D> regions,IReadOnlyList<FlatReliefLoop> reliefs,ICollection<SheetMetalDiagnostic> diagnostics)
+ private static PlanarContour2? BuildExactBlank(SheetMetalPartIr part,IReadOnlyList<FlatRegion2D> regions,IReadOnlyList<FlatReliefLoop> reliefs,IReadOnlyList<FlatCutLoop> cuts,ICollection<SheetMetalDiagnostic> diagnostics,out BlankCompositionPlan? plan)
{
+ plan=null;
var usable=regions.Where(x=>x.ExactContour is not null).OrderBy(x=>x.StableId,StringComparer.Ordinal).ToArray();
if(usable.Length!=regions.Count)return null;
- var profiles=usable.ToDictionary(x=>x.StableId,x=>PlanarContourKernel.ToResolvedProfile(x.ExactContour!,x.StableId),StringComparer.Ordinal);
- foreach(var relief in reliefs)profiles[relief.ReliefId]=PlanarContourKernel.ToResolvedProfile(relief.ExactContour,relief.ReliefId);
- var operations=usable.Select((x,index)=>new PrismaticProfileOperation(x.StableId,index==0?PrismaticProfileIntent.Base:PrismaticProfileIntent.Add,x.StableId,0,1,"SheetMetalBlankRegion",x.SourceRegionId))
- .Concat(reliefs.Select(x=>new PrismaticProfileOperation(x.ReliefId,PrismaticProfileIntent.Remove,x.ReliefId,0,1,"SheetMetalCornerRelief",x.ReliefId))).ToArray();
+ if(cuts.Any(x=>x.ExactContour is null))return null;
+ var baseRegion=usable.FirstOrDefault(x=>x.SourceRegionId==part.BaseRegionId)??usable[0];
+ var planOperations=usable.Where(x=>x!=baseRegion).Select((x,index)=>new BlankCompositionOperation(x.StableId,BlankCompositionOperationKind.AddMaterialRegion,x.SourceRegionId,x.ExactContour!,"one connected material region sharing an authored bend boundary",100+index))
+ .Concat(reliefs.OrderBy(x=>x.ReliefId,StringComparer.Ordinal).Select((x,index)=>new BlankCompositionOperation(x.ReliefId,BlankCompositionOperationKind.ResolveCornerRelief,x.ReliefId,x.ExactContour,"outer-boundary corner chain replacement; no material island",200+index)))
+ .Concat(cuts.OrderBy(x=>x.FeatureId,StringComparer.Ordinal).Select((x,index)=>new BlankCompositionOperation(x.FeatureId,BlankCompositionOperationKind.InsertThroughCut,x.SourceRegionId,x.ExactContour!,"one clockwise inner loop nested in the owning material region",300+index))).OrderBy(x=>x.Order).ToArray();
+ plan=new BlankCompositionPlan(part.StableId,baseRegion.ExactContour!,planOperations);
+ var all=new[]{new BlankCompositionOperation(baseRegion.StableId,BlankCompositionOperationKind.AddMaterialRegion,baseRegion.SourceRegionId,baseRegion.ExactContour!,"one authoritative base contour",0)}.Concat(plan.OrderedOperations).ToArray();
+ var profiles=all.ToDictionary(x=>x.StableId,x=>PlanarContourKernel.ToResolvedProfile(x.Contour,x.StableId),StringComparer.Ordinal);
+ var operations=all.Select(x=>new PrismaticProfileOperation(x.StableId,x.Order==0?PrismaticProfileIntent.Base:x.Kind==BlankCompositionOperationKind.AddMaterialRegion?PrismaticProfileIntent.Add:PrismaticProfileIntent.Remove,x.StableId,0,1,x.Kind.ToString(),x.SemanticOwner)).ToArray();
var composed=ProfileArrangementBuilder.Compose("XY",operations,profiles,$"sheetmetal-blank:{part.StableId}");
if(composed.Region is null)
{
foreach(var message in composed.Arrangement.Diagnostics)diagnostics.Add(new(SheetMetalDiagnosticCodes.ExactBlankContour,SheetMetalDiagnosticSeverity.Warning,$"Exact blank composition: {message}"));
return null;
}
- var contour=PlanarContourKernel.FromResolvedProfile(composed.Region.Outer,$"SheetMetal exact material composition:{part.StableId}") with { StableId=$"flat-{part.StableId}.blank" };
+ var regionProfile=new ResolvedProfile2D($"flat-{part.StableId}.blank","XY",[composed.Region.Outer.Loops.Single(),..composed.Region.Holes.Select(x=>x.Loops.Single())]);
+ var contour=PlanarContourKernel.FromResolvedProfile(regionProfile,$"SheetMetal exact semantic composition plan:{part.StableId}") with { StableId=$"flat-{part.StableId}.blank" };
+ contour=contour with { InnerLoops=contour.InnerLoops.Select(loop=>loop with { Segments=loop.Segments.Reverse().Select(segment=>segment with { Geometry=segment.Geometry switch
+ {
+ LineArcLineSegment2D line=>new LineArcLineSegment2D(line.End,line.Start),
+ LineArcCircularArc2D arc=>arc with { StartAngleRadians=arc.StartAngleRadians+arc.SweepAngleRadians,SweepAngleRadians=-arc.SweepAngleRadians },
+ LineArcFullCircle2D circle=>circle,
+ _=>segment.Geometry
+ }}).ToArray() }).ToArray() };
var validation=PlanarContourKernel.Validate(contour);
if(validation.IsValid)return contour;
foreach(var item in validation.Diagnostics)diagnostics.Add(new(SheetMetalDiagnosticCodes.ExactBlankContour,SheetMetalDiagnosticSeverity.Warning,$"Exact blank composition: {item.Code}: {item.Message}"));
diff --git a/Aetheris.SheetMetal/SheetMetalIr.cs b/Aetheris.SheetMetal/SheetMetalIr.cs
index 5b35483e..f2049617 100644
--- a/Aetheris.SheetMetal/SheetMetalIr.cs
+++ b/Aetheris.SheetMetal/SheetMetalIr.cs
@@ -282,7 +282,8 @@ public sealed record SheetMetalFlatPatternIr(
IReadOnlyList<SheetMetalDiagnostic> Diagnostics,
string DeterministicHash,
PlanarContour2? ExactBlankContour = null,
- IReadOnlyList<FlatReliefLoop>? ReliefLoops = null);
+ IReadOnlyList<FlatReliefLoop>? ReliefLoops = null,
+ BlankCompositionPlan? CompositionPlan = null);
public sealed record SheetMetalRecognitionResult(
SheetMetalPartIr? Part,
diff --git a/Aetheris.SheetMetal/SheetMetalManufacturingArtifacts.cs b/Aetheris.SheetMetal/SheetMetalManufacturingArtifacts.cs
index 43efabf4..21d5138e 100644
--- a/Aetheris.SheetMetal/SheetMetalManufacturingArtifacts.cs
+++ b/Aetheris.SheetMetal/SheetMetalManufacturingArtifacts.cs
@@ -26,29 +26,27 @@ public static class SheetMetalManufacturingArtifacts
var operations = new List<PrismaticProfileOperation>();
var shift = flat.Bounds is null ? new SheetPoint2(10, 10) : new SheetPoint2(10 - flat.Bounds.MinX, 10 - flat.Bounds.MinY);
var materialRegions = flat.Regions2D.Where(r => r.Boundary.Count >= 3).OrderBy(r => r.StableId, StringComparer.Ordinal).ToArray();
- for (var index = 0; index < materialRegions.Length; index++)
+ if(flat.ExactBlankContour is not null)
{
- var region = materialRegions[index];
- var name = $"material_{index:D3}";
- profiles[name] = region.ExactContour is not null ? Profile(name,region.ExactContour,shift) : Profile(name, region.Boundary, shift);
- operations.Add(new(name, index == 0 ? PrismaticProfileIntent.Base : PrismaticProfileIntent.Add, name, 0, part.Thickness,
- region.Kind == SheetRegionKind.CylindricalBend ? "NeutralAxisBendStrip" : "FlatSheetRegion", region.SourceRegionId));
+ const string name="exact_blank";
+ profiles[name]=Profile(name,flat.ExactBlankContour,shift);
+ operations.Add(new(name,PrismaticProfileIntent.Base,name,0,part.Thickness,"ExactSemanticBlank",part.StableId));
}
- for (var index = 0; index < flat.CutLoops.Count; index++)
+ else
{
- var cut = flat.CutLoops[index];
- if (cut.Boundary.Count < 3) continue;
- var name = $"cut_{index:D3}";
- var cutFeature=part.Features.FirstOrDefault(f=>f.StableId==cut.FeatureId);
- profiles[name] = cut.ExactContour is not null ? Profile(name,cut.ExactContour,shift) : cutFeature is { Kind:SheetFeatureKind.CircularHole,Diameter:not null }
- ? CircleProfile(name,new(cut.Boundary.Average(p=>p.X),cut.Boundary.Average(p=>p.Y)),cutFeature.Diameter.Value/2,shift)
- : Profile(name, cut.Boundary, shift);
- operations.Add(new(name, PrismaticProfileIntent.Remove, name, 0, part.Thickness, "ThroughCut", cut.FeatureId, cut.FeatureId, cut.Kind.ToString()));
- }
- foreach(var relief in (flat.ReliefLoops??[]).OrderBy(x=>x.ReliefId,StringComparer.Ordinal))
- {
- var name=$"relief_{Safe(relief.ReliefId)}";profiles[name]=Profile(name,relief.ExactContour,shift);
- operations.Add(new(name,PrismaticProfileIntent.Remove,name,0,part.Thickness,"CornerRelief",relief.ReliefId,relief.ReliefId,relief.Kind.ToString()));
+ for (var index = 0; index < materialRegions.Length; index++)
+ {
+ var region = materialRegions[index];var name = $"material_{index:D3}";
+ profiles[name] = region.ExactContour is not null ? Profile(name,region.ExactContour,shift) : Profile(name, region.Boundary, shift);
+ operations.Add(new(name, index == 0 ? PrismaticProfileIntent.Base : PrismaticProfileIntent.Add, name, 0, part.Thickness,region.Kind == SheetRegionKind.CylindricalBend ? "NeutralAxisBendStrip" : "FlatSheetRegion", region.SourceRegionId));
+ }
+ for (var index = 0; index < flat.CutLoops.Count; index++)
+ {
+ var cut = flat.CutLoops[index];if (cut.Boundary.Count < 3) continue;var name = $"cut_{index:D3}";var cutFeature=part.Features.FirstOrDefault(f=>f.StableId==cut.FeatureId);
+ profiles[name] = cut.ExactContour is not null ? Profile(name,cut.ExactContour,shift) : cutFeature is { Kind:SheetFeatureKind.CircularHole,Diameter:not null }?CircleProfile(name,new(cut.Boundary.Average(p=>p.X),cut.Boundary.Average(p=>p.Y)),cutFeature.Diameter.Value/2,shift):Profile(name, cut.Boundary, shift);
+ operations.Add(new(name, PrismaticProfileIntent.Remove, name, 0, part.Thickness, "ThroughCut", cut.FeatureId, cut.FeatureId, cut.Kind.ToString()));
+ }
+ foreach(var relief in (flat.ReliefLoops??[]).OrderBy(x=>x.ReliefId,StringComparer.Ordinal)){var name=$"relief_{Safe(relief.ReliefId)}";profiles[name]=Profile(name,relief.ExactContour,shift);operations.Add(new(name,PrismaticProfileIntent.Remove,name,0,part.Thickness,"CornerRelief",relief.ReliefId,relief.ReliefId,relief.Kind.ToString()));}
}
if (materialRegions.Length == 0) return Failure("Flat pattern contains no bounded material regions.");
@@ -56,8 +54,20 @@ public static class SheetMetalManufacturingArtifacts
var feature = new PrismaticProfileCompositionFeature(
$"flat_{Safe(part.StableId)}", "XY", "+Z", placement, operations, [0, part.Thickness],
$"SheetMetalFlatPatternIr:{flat.DeterministicHash}");
- var parsed = new PrismaticProfileCompositionParseResult(feature, profiles, []);
- var stack = PrismaticSectionStackCompiler.Normalize(parsed, out var normalizeDiagnostics);
+ PrismaticSectionStackConstruction? stack;IReadOnlyList<string> normalizeDiagnostics;
+ if(flat.ExactBlankContour is not null)
+ {
+ var exact=profiles["exact_blank"];var outerLoop=exact.Loops.Single(x=>x.IsOuter);
+ var outer=new ResolvedProfile2D("exact_blank.outer",exact.PlaneFrame,[outerLoop]);
+ var holes=exact.Loops.Where(x=>!x.IsOuter).Select((loop,index)=>new ResolvedProfile2D($"exact_blank.inner{index}",exact.PlaneFrame,[ReverseForSection(loop,index)])).ToArray();
+ var region=new PrismaticSectionRegion(outer,holes,[part.StableId,"ExactSemanticBlank"]);var area=PrismaticSectionStackCompiler.Area(region);
+ stack=new(feature,[new(0,part.Thickness,region,["exact_blank"])],[new(0,[],[region]),new(part.Thickness,[region],[])],area*part.Thickness,[]);normalizeDiagnostics=[];
+ }
+ else
+ {
+ var parsed = new PrismaticProfileCompositionParseResult(feature, profiles, []);
+ stack = PrismaticSectionStackCompiler.Normalize(parsed, out normalizeDiagnostics);
+ }
if (stack is null)
return Failure("Flat profile union could not be normalized: " + string.Join("; ", normalizeDiagnostics));
var emission = PrismaticSectionStackEmitter.Emit(stack);
@@ -171,6 +181,14 @@ public static class SheetMetalManufacturingArtifacts
return new(name,"XY",[new("Outer",true,[Segment("semicircle_0",0),Segment("semicircle_1",Math.PI)])]);
}
+ private static ResolvedProfileLoop2D ReverseForSection(ResolvedProfileLoop2D loop,int loopIndex)=>new($"Inner{loopIndex}",false,loop.Segments.Reverse().Select(segment=>segment with { Geometry=segment.Geometry switch
+ {
+ LineArcLineSegment2D line=>new LineArcLineSegment2D(line.End,line.Start),
+ LineArcCircularArc2D arc=>arc with { StartAngleRadians=arc.StartAngleRadians+arc.SweepAngleRadians,SweepAngleRadians=-arc.SweepAngleRadians },
+ LineArcFullCircle2D circle=>circle,
+ _=>segment.Geometry
+ }}).ToArray());
+
private static double SignedArea(IReadOnlyList<SheetPoint2> points) { var sum = 0d; for (var i = 0; i < points.Count; i++) { var q = points[(i + 1) % points.Count]; sum += points[i].X * q.Y - q.X * points[i].Y; } return sum / 2d; }
private static double Clean(double value) => Math.Abs(value) < 1e-9 ? 0d : value;
private static string Safe(string value) { var chars = value.Select(ch => char.IsLetterOrDigit(ch) || ch == '_' ? ch : '_').ToArray(); var result = new string(chars); return result.Length > 0 && (char.IsLetter(result[0]) || result[0] == '_') ? result : "Recovered_" + result; }
diff --git a/Aetheris.SheetMetal/SheetMetalProductFamilies.cs b/Aetheris.SheetMetal/SheetMetalProductFamilies.cs
new file mode 100644
index 00000000..4e9d7d45
--- /dev/null
+++ b/Aetheris.SheetMetal/SheetMetalProductFamilies.cs
@@ -0,0 +1,67 @@
+using System.Globalization;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+
+namespace Aetheris.SheetMetal;
+
+public sealed record ElectronicsEnclosureSpec(
+ double Width,
+ double Depth,
+ double Height,
+ double LidLipHeight,
+ double Thickness,
+ double InsideRadius,
+ double KFactor=.42d,
+ SheetReliefPolicy ReliefPolicy=SheetReliefPolicy.Rectangular);
+
+public sealed record ManufacturedSheetMetalResult(
+ string TemplateName,
+ string SpecializationIdentity,
+ SheetMetalAuthoringResult Compilation,
+ SheetMetalDfmReport Dfm,
+ IReadOnlyList<SheetMetalConceptPath> SemanticPaths,
+ SheetMetalFabricationIr Fabrication,
+ string FlatSvg)
+{
+ public SheetMetalPartIr Part=>Compilation.Part!;
+ public SheetMetalFlatPatternIr FlatPattern=>Compilation.FlatPattern!;
+}
+
+/// <summary>
+/// Typed Forge-facing convenience over the ordinary Firmament Template host bridge.
+/// Geometry remains authored by the embedded user-readable Firmament module.
+/// </summary>
+public static class SheetMetalProductFamilies
+{
+ public static ManufacturedSheetMetalResult MakeEnclosure(ElectronicsEnclosureSpec spec,string instanceName="Enclosure")
+ {
+ Positive(spec.Width,nameof(spec.Width));Positive(spec.Depth,nameof(spec.Depth));Positive(spec.Height,nameof(spec.Height));
+ Positive(spec.LidLipHeight,nameof(spec.LidLipHeight));Positive(spec.Thickness,nameof(spec.Thickness));
+ if(spec.InsideRadius<0||!double.IsFinite(spec.InsideRadius))throw new ArgumentOutOfRangeException(nameof(spec.InsideRadius));
+ if(spec.KFactor is <0 or >1||!double.IsFinite(spec.KFactor))throw new ArgumentOutOfRangeException(nameof(spec.KFactor));
+ var fields=new Dictionary<string,string>(StringComparer.Ordinal)
+ {
+ ["Width"]=Mm(spec.Width),["Depth"]=Mm(spec.Depth),["Height"]=Mm(spec.Height),
+ ["LidLipHeight"]=Mm(spec.LidLipHeight),["Thickness"]=Mm(spec.Thickness),
+ ["InsideRadius"]=Mm(spec.InsideRadius),["KFactor"]=N(spec.KFactor),
+ ["ReliefPolicy"]=spec.ReliefPolicy switch { SheetReliefPolicy.Round=>"Round",SheetReliefPolicy.Rectangular=>"Rectangular",_=>"Auto" }
+ };
+ var arguments=new Dictionary<string,FirmamentHostArgument>(StringComparer.Ordinal)
+ {
+ ["Spec"]=new("", "EnclosureSpec",fields)
+ };
+ var expansion=FirmamentTemplateHostBridge.Expand(SheetMetalTemplateLibrary.Source,"ElectronicsEnclosure",instanceName,arguments,out var diagnostics)
+ ?? throw new InvalidOperationException("Firmament enclosure Template specialization failed: "+string.Join("; ",diagnostics));
+ if(diagnostics.Count>0)throw new InvalidOperationException("Firmament enclosure Template specialization failed: "+string.Join("; ",diagnostics));
+ var compilation=SheetMetalFirmament.Compile(expansion.ExpandedSource,$"template:{expansion.SpecializationIdentity}");
+ if(!compilation.IsSuccess||compilation.Part is null||compilation.FlatPattern is null)
+ throw new InvalidOperationException("Specialized enclosure failed Sheet Metal lowering: "+string.Join("; ",compilation.Diagnostics.Select(x=>$"{x.Code}: {x.Message}")));
+ var paths=SheetMetalConceptPaths.Inspect(compilation.Spec!,compilation.Part,compilation.FlatPattern);
+ return new("ElectronicsEnclosure",expansion.SpecializationIdentity,compilation,
+ SheetMetalDfm.Evaluate(compilation.Part,compilation.FlatPattern),paths,
+ SheetMetalFabricationArtifacts.Create(compilation.Part,compilation.FlatPattern),SheetMetalSvgRenderer.Render(compilation.FlatPattern));
+ }
+
+ private static string Mm(double value)=>N(value)+"mm";
+ private static string N(double value)=>value.ToString("R",CultureInfo.InvariantCulture);
+ private static void Positive(double value,string name){if(!double.IsFinite(value)||value<=0)throw new ArgumentOutOfRangeException(name);}
+}
diff --git a/Aetheris.SheetMetal/SheetMetalTemplateLibrary.cs b/Aetheris.SheetMetal/SheetMetalTemplateLibrary.cs
new file mode 100644
index 00000000..3f7dcc36
--- /dev/null
+++ b/Aetheris.SheetMetal/SheetMetalTemplateLibrary.cs
@@ -0,0 +1,19 @@
+using System.Reflection;
+
+namespace Aetheris.SheetMetal;
+
+public static class SheetMetalTemplateLibrary
+{
+ private const string ResourceName="Aetheris.SheetMetal.Firmament.SheetMetalProductFamilies.firmament";
+
+ public static string Source
+ {
+ get
+ {
+ using var stream=typeof(SheetMetalTemplateLibrary).Assembly.GetManifestResourceStream(ResourceName)
+ ?? throw new InvalidOperationException($"Embedded Firmament module '{ResourceName}' was not found.");
+ using var reader=new StreamReader(stream);
+ return reader.ReadToEnd();
+ }
+ }
+}
diff --git a/Aetheris.SheetMetal/SheetMetalTemplates.cs b/Aetheris.SheetMetal/SheetMetalTemplates.cs
index 24996740..61249343 100644
--- a/Aetheris.SheetMetal/SheetMetalTemplates.cs
+++ b/Aetheris.SheetMetal/SheetMetalTemplates.cs
@@ -1,5 +1,5 @@
using System.Globalization;
-using System.Text;
+using Aetheris.Kernel.Firmament.FirmamentV2;
namespace Aetheris.SheetMetal;
@@ -15,33 +15,29 @@ public sealed record UChannelSpec(double Width,double Depth,double WallHeight,Sh
public sealed record FourWallTraySpec(double Width,double Depth,double WallHeight,SheetMetalTemplatePolicy Policy);
/// <summary>
-/// Small module-owned reusable template surface. Expansion emits ordinary SheetMetal
-/// declarations so lowering, DFM, correspondence, and Concept Paths are not bypassed.
+/// Compatibility C# entry points over the module's ordinary user-defined Firmament
+/// Templates. No Sheet Metal construction is implemented in this host wrapper.
/// </summary>
public static class SheetMetalTemplates
{
- public static string LBracket(string name,LBracketSpec spec)=>Emit(name,spec.Width,spec.Depth,spec.Policy,[new("Wall","Front",spec.FlangeHeight)]);
- public static string UChannel(string name,UChannelSpec spec)=>Emit(name,spec.Width,spec.Depth,spec.Policy,[new("LeftWall","Left",spec.WallHeight),new("RightWall","Right",spec.WallHeight)]);
- public static string FourWallTray(string name,FourWallTraySpec spec)=>Emit(name,spec.Width,spec.Depth,spec.Policy,
- [new("Front","Front",spec.WallHeight),new("Right","Right",spec.WallHeight),new("Rear","Rear",spec.WallHeight),new("Left","Left",spec.WallHeight)]);
+ public static string LBracket(string name,LBracketSpec spec)=>Expand("LBracket",name,"LBracketSpec",Fields(spec.Policy,("Width",Mm(spec.Width)),("Depth",Mm(spec.Depth)),("FlangeHeight",Mm(spec.FlangeHeight))));
+ public static string UChannel(string name,UChannelSpec spec)=>Expand("UChannel",name,"UChannelSpec",Fields(spec.Policy,("Width",Mm(spec.Width)),("Depth",Mm(spec.Depth)),("WallHeight",Mm(spec.WallHeight))));
+ public static string FourWallTray(string name,FourWallTraySpec spec)=>Expand("FourWallTray",name,"TraySpec",Fields(spec.Policy,("Width",Mm(spec.Width)),("Depth",Mm(spec.Depth)),("WallHeight",Mm(spec.WallHeight))));
- private static string Emit(string name,double width,double depth,SheetMetalTemplatePolicy policy,IReadOnlyList<(string Name,string Edge,double Height)> flanges)
+ private static string Expand(string template,string name,string recordType,Dictionary<string,string> fields)
{
- Positive(width,nameof(width));Positive(depth,nameof(depth));Positive(policy.Thickness,nameof(policy.Thickness));Positive(policy.InsideRadius,nameof(policy.InsideRadius),allowZero:true);
+ var expansion=FirmamentTemplateHostBridge.Expand(SheetMetalTemplateLibrary.Source,template,Safe(name),
+ new Dictionary<string,FirmamentHostArgument>(StringComparer.Ordinal){["Spec"]=new("",recordType,fields)},out var diagnostics);
+ return expansion?.ExpandedSource??throw new InvalidOperationException($"Firmament Template '{template}' specialization failed: {string.Join("; ",diagnostics)}");
+ }
+ private static Dictionary<string,string> Policy(SheetMetalTemplatePolicy policy)
+ {
+ Positive(policy.Thickness,nameof(policy.Thickness));Positive(policy.InsideRadius,nameof(policy.InsideRadius),true);
if(policy.KFactor is <0 or >1)throw new ArgumentOutOfRangeException(nameof(policy.KFactor));
- var b=new StringBuilder();b.Append("SheetMetal ").Append(Safe(name)).AppendLine(" {");
- b.Append(" Thickness: ").Append(N(policy.Thickness)).AppendLine("mm;");b.Append(" KFactor: ").Append(N(policy.KFactor)).AppendLine(";");
- if(!string.IsNullOrWhiteSpace(policy.Material))b.Append(" Material: \"").Append(policy.Material!.Replace("\"","\\\"",StringComparison.Ordinal)).AppendLine("\";");
- b.Append(" Base Base { Profile: Rectangle { Width: ").Append(N(width)).Append("mm; Height: ").Append(N(depth)).AppendLine("mm; }; }");
- foreach(var flange in flanges)
- {
- Positive(flange.Height,nameof(flange.Height));b.Append(" Flange ").Append(flange.Name).Append(" { From: Base.").Append(flange.Edge).Append("; Height: ").Append(N(flange.Height)).Append("mm; Angle: 90deg; Radius: ").Append(N(policy.InsideRadius)).Append("mm;");
- if(policy.CornerPolicy==SheetCornerPolicy.Mitered)b.Append(" Corner: Miter;");
- else if(policy.ReliefPolicy!=SheetReliefPolicy.None)b.Append(" Relief: ").Append(policy.ReliefPolicy switch{SheetReliefPolicy.Round=>"Round",SheetReliefPolicy.Rectangular=>"Rectangular",_=>"Auto"}).Append(';');
- b.AppendLine(" }");
- }
- b.AppendLine("}");return b.ToString();
+ return new(StringComparer.Ordinal){["Thickness"]=Mm(policy.Thickness),["InsideRadius"]=N(policy.InsideRadius)+"mm",["KFactor"]=N(policy.KFactor),["ReliefPolicy"]=policy.ReliefPolicy switch{SheetReliefPolicy.Round=>"Round",SheetReliefPolicy.Rectangular=>"Rectangular",_=>"Auto"}};
}
+ private static Dictionary<string,string> Fields(SheetMetalTemplatePolicy policy,params (string Name,string Value)[] values){var fields=Policy(policy);foreach(var value in values)fields[value.Name]=value.Value;return fields;}
+ private static string Mm(double value){Positive(value,nameof(value));return N(value)+"mm";}
private static string N(double value)=>value.ToString("R",CultureInfo.InvariantCulture);
private static void Positive(double value,string name,bool allowZero=false){if(!double.IsFinite(value)||(allowZero?value<0:value<=0))throw new ArgumentOutOfRangeException(name);}
private static string Safe(string value){if(string.IsNullOrWhiteSpace(value)||!char.IsLetter(value[0])&&value[0]!='_')throw new ArgumentException("Template instance name must be a Firmament identifier.",nameof(value));if(value.Any(c=>!char.IsLetterOrDigit(c)&&c!='_'))throw new ArgumentException("Template instance name must be a Firmament identifier.",nameof(value));return value;}
diff --git a/README.md b/README.md
index 2982f215..66e245b4 100644
--- a/README.md
+++ b/README.md
@@ -11,6 +11,26 @@ Firmament is a deterministic DSL for generating CAD geometry (STEP AP242) via Ae
Firmament V2 is the sole canonical authoring path. Firmament V1 TOON/JSON and JSON-shaped legacy `.firmasm` remain explicit compatibility/serialization inputs. See the [current authoring and kernel boundaries](docs/architecture/current-authoring-and-kernel-boundaries.md).
+## Generic Sheet Metal product families
+
+Firmament `Template` is typed compile-time generic programming—not a document
+template, prefab model, macro, or C# geometry generator. The Sheet Metal module
+ships its product families as readable Firmament source:
+
+```firmament
+Use SheetMetal.ProductFamilies;
+
+Static Psu: EnclosureSpec = EnclosureSpec {
+ Width: 240mm Depth: 180mm Height: 60mm LidLipHeight: 8mm
+ Thickness: 1.2mm InsideRadius: 1.5mm KFactor: 0.42
+ ReliefPolicy: Rectangular
+}
+SheetMetal Enclosure = ElectronicsEnclosure < Spec: Psu >
+```
+
+The specialization lowers through ordinary Base, Flange, Relief, Cut, exact-flat,
+DFM, SVG, and STEP paths. See the [M5 product-family guide](docs/firmament/sheetmetal-product-templates-m5.md).
+
## Static engineering data
Firmament `Record` values are immutable typed specifications. A finite standards
diff --git a/docs/firmament/sheetmetal-product-templates-m5.md b/docs/firmament/sheetmetal-product-templates-m5.md
new file mode 100644
index 00000000..9ca1aae5
--- /dev/null
+++ b/docs/firmament/sheetmetal-product-templates-m5.md
@@ -0,0 +1,109 @@
+# Firmament generic Sheet Metal product families (M5)
+
+`Template` is a Firmament language feature for typed compile-time generic
+engineering construction. It is not document templating, text substitution, a
+CAD prefab, or a privileged Sheet Metal generator. The source of the standard
+families is `Aetheris.SheetMetal/Firmament/SheetMetalProductFamilies.firmament`.
+The core Firmament Template parser/binder specializes it before the Sheet Metal
+domain compiler sees an ordinary concrete declaration.
+
+## Generic source and specialization
+
+```firmament
+Record TraySpec {
+ Width: Length
+ Depth: Length
+ WallHeight: Length
+ Thickness: Length
+ InsideRadius: Length
+ KFactor: float
+ ReliefPolicy: SheetMetalReliefPolicy
+}
+
+Template < Spec: TraySpec >
+SheetMetal FourWallTray: Tray {
+ Require Positive => Spec.Width > 0mm && Spec.WallHeight > 0mm
+ Thickness: Spec.Thickness;
+ KFactor: Spec.KFactor;
+ Base Base { Profile: Rectangle { Width: Spec.Width; Height: Spec.Depth; }; }
+ Flange Front { From: Base.Front; Height: Spec.WallHeight; Angle: 90deg; Radius: Spec.InsideRadius; Relief: Spec.ReliefPolicy; }
+ // Right, Rear, and Left use the same ordinary Flange construct.
+}
+
+Static LabTray: TraySpec = TraySpec {
+ Width: 160mm Depth: 110mm WallHeight: 36mm Thickness: 1.2mm
+ InsideRadius: 1.5mm KFactor: 0.42 ReliefPolicy: Rectangular
+}
+SheetMetal Body = FourWallTray < Spec: LabTray >
+```
+
+Angle-bracket application creates a deterministic specialization identity. A
+Record argument is checked field-by-field, `Require` is evaluated before
+geometry lowering, and the generated `SheetMetal Body: Tray` claim is checked
+against the Concept's required semantic members. Missing members and incompatible
+member types are compile errors.
+
+The shipped families are `LBracket`, `UChannel`, `FourWallTray`,
+`RemovablePanLid`, and `ElectronicsEnclosure`. The latter includes a bounded body
+and one parent-flange lip. A separate removable lid is specialized from the same
+module because the current Sheet Metal compilation result is one manufactured
+part. Cross-part nested Template specialization belongs in Firmament Assembly;
+pretending that two blanks are one `SheetMetalPartIr` would corrupt manufacturing
+semantics. This is the principal remaining product-family composition gap.
+
+## Semantic blank composition
+
+Authored exact flattening builds a `BlankCompositionPlan`:
+
+```text
+BaseContour
+ + ordered connected material regions
+ - topology-owned corner reliefs
+ - nested through-cut loops
+ = one exact material contour
+```
+
+Each operation states its semantic owner and expected topology. Corner reliefs
+must replace an outer corner chain; through cuts must produce clockwise inner
+loops. The shared analytic arrangement kernel retains line/arc provenance. M5
+also normalizes signed zero in topology buckets, fixing the M4 failure where
+`-0` and `0` incorrectly became different graph vertices in symmetric
+multi-relief trays.
+
+`SheetMetalFabricationIr` exposes the outer cut contour, inner cut loops,
+bend-up/down lines, relief semantic IDs, millimetre units, and deterministic
+hash. This is sufficient for a future bounded DXF serializer. M5 defers DXF
+serialization rather than introducing an unreviewed writer; STEP and review SVG
+are implemented now.
+
+## Downstream authoring
+
+A specialized part stays open to normal Sheet Metal operations:
+
+```firmament
+SheetMetal NetworkAppliance = ElectronicsEnclosure < Spec: NetworkSpec >
+
+Extend SheetMetal NetworkAppliance {
+ Cut RearEthernet { On: Rear; At: (80mm, 18mm); Profile: Rectangle; Width: 16mm; Length: 14mm; }
+ Hole MountA { On: Body; Center: (25mm, 25mm); Diameter: 3.2mm; }
+}
+```
+
+The public paths keep the same shape across specializations (`Body.Front`,
+`Front.Outer`, `FrontLip.Bend`, `Flat.Body`, and owning-region cut paths such as
+`Rear.RearEthernet`). DFM subjects retain the specialized instance, owning
+region, and feature name.
+
+## Forge host boundary
+
+`SheetMetalProductFamilies.MakeEnclosure(spec)` passes a typed host Record to
+the same Firmament Template binder. It returns the formed part IR, exact flat IR,
+DFM report, stable semantic paths, fabrication IR, SVG, and specialization
+identity. STEP emission remains an explicit artifact operation so applications
+choose output locations and I/O policy.
+
+The network-appliance fixtures demonstrate the body and lid paths. The awkward
+parts today are repeated vent declarations and the separate body/lid Assembly
+step. A generic bounded pattern Template is the next reusable language
+abstraction; lid clearance and connector placement remain genuine engineering
+choices rather than defaults the compiler should guess.
diff --git a/fixtures/FirmamentV2/SheetMetal/m5-four-relief-tray.firmament b/fixtures/FirmamentV2/SheetMetal/m5-four-relief-tray.firmament
new file mode 100644
index 00000000..9a1abd95
--- /dev/null
+++ b/fixtures/FirmamentV2/SheetMetal/m5-four-relief-tray.firmament
@@ -0,0 +1,10 @@
+SheetMetal FourReliefTray {
+ Thickness: 1.2mm;
+ KFactor: 0.42;
+ Material: "5052-H32";
+ Base Base { Profile: Rectangle { Width: 80mm; Height: 60mm; }; }
+ Flange Front { From: Base.Front; Height: 18mm; Angle: 90deg; Radius: 1.5mm; Relief: Rectangular; }
+ Flange Right { From: Base.Right; Height: 18mm; Angle: 90deg; Radius: 1.5mm; Relief: Rectangular; }
+ Flange Rear { From: Base.Rear; Height: 18mm; Angle: 90deg; Radius: 1.5mm; Relief: Rectangular; }
+ Flange Left { From: Base.Left; Height: 18mm; Angle: 90deg; Radius: 1.5mm; Relief: Rectangular; }
+}
diff --git a/fixtures/FirmamentV2/SheetMetal/m5-four-wall-tray-template.firmament b/fixtures/FirmamentV2/SheetMetal/m5-four-wall-tray-template.firmament
new file mode 100644
index 00000000..643c28a0
--- /dev/null
+++ b/fixtures/FirmamentV2/SheetMetal/m5-four-wall-tray-template.firmament
@@ -0,0 +1,13 @@
+Use SheetMetal.ProductFamilies;
+
+Static ProductionTray: TraySpec = TraySpec {
+ Width: 80mm
+ Depth: 60mm
+ WallHeight: 18mm
+ Thickness: 1.2mm
+ InsideRadius: 1.5mm
+ KFactor: 0.42
+ ReliefPolicy: Rectangular
+}
+
+SheetMetal ProductionTrayA = FourWallTray < Spec: ProductionTray >
diff --git a/fixtures/FirmamentV2/SheetMetal/m5-network-appliance-enclosure.firmament b/fixtures/FirmamentV2/SheetMetal/m5-network-appliance-enclosure.firmament
new file mode 100644
index 00000000..f93e68c7
--- /dev/null
+++ b/fixtures/FirmamentV2/SheetMetal/m5-network-appliance-enclosure.firmament
@@ -0,0 +1,30 @@
+Use SheetMetal.ProductFamilies;
+
+Static NetworkSpec: EnclosureSpec = EnclosureSpec {
+ Width: 160mm
+ Depth: 110mm
+ Height: 36mm
+ LidLipHeight: 7mm
+ Thickness: 1.2mm
+ InsideRadius: 1.5mm
+ KFactor: 0.42
+ ReliefPolicy: Rectangular
+}
+
+SheetMetal NetworkAppliance = ElectronicsEnclosure < Spec: NetworkSpec >
+
+// Ordinary downstream authoring against the specialized object's semantic regions.
+Extend SheetMetal NetworkAppliance {
+ Hole FrontIndicatorGreen { On: Front; Center: (45mm, 18mm); Diameter: 3mm; }
+ Hole FrontIndicatorAmber { On: Front; Center: (55mm, 18mm); Diameter: 3mm; }
+ Cut RearPowerInlet { On: Rear; At: (35mm, 18mm); Profile: Rectangle; Width: 18mm; Length: 12mm; }
+ Cut RearEthernet { On: Rear; At: (80mm, 18mm); Profile: Rectangle; Width: 16mm; Length: 14mm; }
+ Cut LeftVentA { On: Left; At: (30mm, 15mm); Profile: Slot; Width: 3mm; Length: 18mm; }
+ Cut LeftVentB { On: Left; At: (55mm, 15mm); Profile: Slot; Width: 3mm; Length: 18mm; }
+ Cut RightVentA { On: Right; At: (30mm, 15mm); Profile: Slot; Width: 3mm; Length: 18mm; }
+ Cut RightVentB { On: Right; At: (55mm, 15mm); Profile: Slot; Width: 3mm; Length: 18mm; }
+ Hole MountA { On: Body; Center: (25mm, 25mm); Diameter: 3.2mm; }
+ Hole MountB { On: Body; Center: (135mm, 25mm); Diameter: 3.2mm; }
+ Hole MountC { On: Body; Center: (25mm, 85mm); Diameter: 3.2mm; }
+ Hole MountD { On: Body; Center: (135mm, 85mm); Diameter: 3.2mm; }
+}
diff --git a/fixtures/FirmamentV2/SheetMetal/m5-network-appliance-lid.firmament b/fixtures/FirmamentV2/SheetMetal/m5-network-appliance-lid.firmament
new file mode 100644
index 00000000..42dd200c
--- /dev/null
+++ b/fixtures/FirmamentV2/SheetMetal/m5-network-appliance-lid.firmament
@@ -0,0 +1,14 @@
+Use SheetMetal.ProductFamilies;
+
+Static NetworkLidSpec: LidSpec = LidSpec {
+ Width: 162mm
+ Depth: 112mm
+ SkirtHeight: 9mm
+ Clearance: 1mm
+ Thickness: 1.2mm
+ InsideRadius: 1.5mm
+ KFactor: 0.42
+ ReliefPolicy: Rectangular
+}
+
+SheetMetal NetworkApplianceLid = RemovablePanLid < Spec: NetworkLidSpec >
diff --git a/fixtures/FirmamentV2/SheetMetal/m5-psu-enclosure.firmament b/fixtures/FirmamentV2/SheetMetal/m5-psu-enclosure.firmament
new file mode 100644
index 00000000..e371736e
--- /dev/null
+++ b/fixtures/FirmamentV2/SheetMetal/m5-psu-enclosure.firmament
@@ -0,0 +1,23 @@
+Use SheetMetal.ProductFamilies;
+
+Static PsuSpec: EnclosureSpec = EnclosureSpec {
+ Width: 150mm
+ Depth: 100mm
+ Height: 42mm
+ LidLipHeight: 7mm
+ Thickness: 1.2mm
+ InsideRadius: 1.5mm
+ KFactor: 0.42
+ ReliefPolicy: Rectangular
+}
+
+SheetMetal PsuEnclosure = ElectronicsEnclosure < Spec: PsuSpec >
+
+Extend SheetMetal PsuEnclosure {
+ Cut AcInlet { On: Rear; At: (32mm, 21mm); Profile: Rectangle; Width: 28mm; Length: 20mm; }
+ Cut DcOutlet { On: Front; At: (115mm, 21mm); Profile: Rectangle; Width: 24mm; Length: 14mm; }
+ Hole Mount1 { On: Body; Center: (20mm, 20mm); Diameter: 4mm; }
+ Hole Mount2 { On: Body; Center: (130mm, 20mm); Diameter: 4mm; }
+ Hole Mount3 { On: Body; Center: (20mm, 80mm); Diameter: 4mm; }
+ Hole Mount4 { On: Body; Center: (130mm, 80mm); Diameter: 4mm; }
+}