Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add rounded corner support and expose attachment paths

Yuechen Lieea71137cb64
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index 4290981b..6a5500cf 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -545,7 +545,7 @@ 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 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,semanticLayout=authoredSpec?.SemanticLayout,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,semanticResolve=authoredTimings?.SemanticResolveMilliseconds,formedLower=authoredTimings?.FormedLowerMilliseconds,authoredFlatLower=authoredTimings?.FlatLowerMilliseconds,import=importTime.TotalMilliseconds,recognition=recognitionTime.TotalMilliseconds,flatten=flattenClock.Elapsed.TotalMilliseconds}};
+ 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}),attachmentPaths=(part.AttachmentPaths??[]).Select(p=>new{p.StableId,p.OwningRegionId,p.CarrierPath,p.Inset,length=(p.End-p.Start).Length,p.SpanOffset,p.Start,p.End,p.Tangent,p.InPlaneNormal,p.RegionNormal,p.Capabilities}),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,semanticLayout=authoredSpec?.SemanticLayout,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,semanticResolve=authoredTimings?.SemanticResolveMilliseconds,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/SemanticCornerProfileIr.cs b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticCornerProfileIr.cs
index 18470628..c09ee4b3 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/SemanticCornerProfileIr.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticCornerProfileIr.cs
@@ -37,6 +37,11 @@ public sealed record SemanticCornerTaperIr(
string Name, string StableId, double SetbackA, double SetbackB, string SourceSpan)
: SemanticCornerOperationIr(Name, StableId, "Taper", SetbackA, SetbackB, SourceSpan);
+/// <summary>An analytic circular fillet between two orthogonal profile members.</summary>
+public sealed record SemanticCornerRoundIr(
+ string Name, string StableId, double Radius, string SourceSpan)
+ : SemanticCornerOperationIr(Name, StableId, "Round", Radius, Radius, SourceSpan);
+
/// <summary>A rectangular material-removal step in the bounded corner u/v frame.</summary>
public sealed record SemanticCornerNotchIr(
string Name, string StableId, double SetbackA, double SetbackB, string SourceSpan)
@@ -99,6 +104,8 @@ public static class SemanticCornerProfileResolver
SemanticCornerNotchIr =>
[new LineArcLineSegment2D(ToTuple(a), ToTuple(new(a.X + v.X * operation.SetbackB, a.Y + v.Y * operation.SetbackB))),
new LineArcLineSegment2D(ToTuple(new(a.X + v.X * operation.SetbackB, a.Y + v.Y * operation.SetbackB)), ToTuple(b))],
+ SemanticCornerRoundIr round when Math.Abs(u.X*v.X+u.Y*v.Y)<=Tolerance =>
+ Round(a,b,u,v,round.Radius),
_ => []
};
if (curves.Count == 0) return new(null, [$"semantic-corner-operation-unsupported:{operation.StableId}:{operation.Kind}"]);
@@ -115,4 +122,13 @@ public static class SemanticCornerProfileResolver
private static double Length(SemanticProfilePoint value) => Math.Sqrt(value.X * value.X + value.Y * value.Y);
private static SemanticProfilePoint Add(SemanticProfilePoint origin, SemanticProfilePoint direction, double distance) => new(origin.X + direction.X * distance, origin.Y + direction.Y * distance);
private static (double X, double Y) ToTuple(SemanticProfilePoint point) => (point.X, point.Y);
+ private static IReadOnlyList<LineArcProfileCurve2D> Round(SemanticProfilePoint a,SemanticProfilePoint b,SemanticProfilePoint u,SemanticProfilePoint v,double radius)
+ {
+ var center=new SemanticProfilePoint(a.X+v.X*radius,a.Y+v.Y*radius);
+ var start=Math.Atan2(a.Y-center.Y,a.X-center.X);var end=Math.Atan2(b.Y-center.Y,b.X-center.X);
+ var incoming=new SemanticProfilePoint(-u.X,-u.Y);var startTangentCcw=new SemanticProfilePoint(-Math.Sin(start),Math.Cos(start));
+ var ccw=incoming.X*startTangentCcw.X+incoming.Y*startTangentCcw.Y>0;
+ var sweep=end-start;if(ccw){while(sweep<=0)sweep+=2*Math.PI;}else{while(sweep>=0)sweep-=2*Math.PI;}
+ return [new LineArcCircularArc2D(ToTuple(center),radius,start,sweep)];
+ }
}
diff --git a/Aetheris.SheetMetal.Tests/SheetMetalM8Tests.cs b/Aetheris.SheetMetal.Tests/SheetMetalM8Tests.cs
index 26351ec0..8cacf0d5 100644
--- a/Aetheris.SheetMetal.Tests/SheetMetalM8Tests.cs
+++ b/Aetheris.SheetMetal.Tests/SheetMetalM8Tests.cs
@@ -30,7 +30,8 @@ public sealed class SheetMetalM8Tests
Assert.True(result.IsSuccess,string.Join('\n',result.Diagnostics.Select(x=>x.Message)));
Assert.Equal(15,result.Part!.Features.Count(x=>x.Kind==SheetFeatureKind.CircularHole));
Assert.Equal(2,result.Part.Features.Count(x=>x.Kind==SheetFeatureKind.Slot));
- Assert.Equal(9,result.Spec!.SemanticLayout.Patterns.Count);Assert.Single(result.Spec.SemanticLayout.Tabs);Assert.Equal(2,result.Spec.SemanticLayout.SteppedNotches!.Count);Assert.Equal(10,result.Spec.SemanticLayout.Corners!.Count);
+ Assert.Equal(9,result.Spec!.SemanticLayout.Patterns.Count);Assert.Single(result.Spec.SemanticLayout.Tabs);Assert.Equal(2,result.Spec.SemanticLayout.SteppedNotches!.Count);Assert.Equal(12,result.Spec.SemanticLayout.Corners!.Count);
+ var attachment=Assert.Single(result.Part.AttachmentPaths!);Assert.Equal("RightWall.ServiceFlangeAttachment",attachment.StableId);Assert.Equal(2.6416,attachment.Inset,8);
Assert.Equal(127,result.Part.Regions.Single(x=>x.StableId=="AngledServiceFlangeBendRegion").Cylinder!.AxisLength,8);
Assert.NotNull(result.FlatPattern!.ExactBlankContour);Assert.Equal(17,result.FlatPattern.CutLoops.Count);
Assert.True(BrepExportPreflight.Validate(result.Part.FormedBody!).IsValid);
diff --git a/Aetheris.SheetMetal.Tests/SheetMetalM9Tests.cs b/Aetheris.SheetMetal.Tests/SheetMetalM9Tests.cs
new file mode 100644
index 00000000..2968971e
--- /dev/null
+++ b/Aetheris.SheetMetal.Tests/SheetMetalM9Tests.cs
@@ -0,0 +1,116 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Firmament.Materializer;
+using Xunit;
+
+namespace Aetheris.SheetMetal.Tests;
+
+public sealed class SheetMetalM9Tests
+{
+ private const string InsetPartialFlange = """
+ SheetMetal InsetPartialFlange {
+ Thickness: 1mm;
+ KFactor: 0.5;
+ Base Panel { Profile: Rectangle { Width: 100mm; Height: 60mm; }; }
+ Flange Wall { From: Panel.Rear; Height: 20mm; Angle: 90deg; Radius: 2mm; }
+ AttachmentPath ServiceFlangeAttachment {
+ On: Wall.Outer;
+ Inset: 2mm;
+ Span: 40mm;
+ SpanOffset: 5mm;
+ Release: ToCarrier;
+ }
+ Flange ServiceFlange { From: Wall.ServiceFlangeAttachment; Height: 12mm; Angle: 45deg; Radius: 2mm; }
+ }
+ """;
+
+ [Fact]
+ public void InsetPartialAttachmentPath_IsDistinctStableAndDrivesOrdinaryFlange()
+ {
+ var result=SheetMetalFirmament.Compile(InsetPartialFlange);
+ Assert.True(result.IsSuccess,string.Join('\n',result.Diagnostics.Select(x=>$"{x.Code}: {x.Message}")));
+ var path=Assert.Single(result.Part!.AttachmentPaths!);
+ Assert.Equal("Wall.ServiceFlangeAttachment",path.StableId);
+ Assert.Equal("Wall",path.OwningRegionId);
+ Assert.Equal("Wall.Outer",path.CarrierPath);
+ Assert.Equal(2,path.Inset,8);Assert.Equal(40,(path.End-path.Start).Length,8);
+ Assert.Contains(SheetPathCapability.FlangeAttachable,path.Capabilities);
+ Assert.Equal(40,result.Part.Regions.Single(x=>x.StableId=="ServiceFlangeBendRegion").Cylinder!.AxisLength,8);
+ Assert.Contains(result.Part.Correspondence!,x=>x.SemanticId==path.StableId&&x.Kind=="AttachmentPath");
+ var concepts=SheetMetalConceptPaths.Inspect(result.Spec!,result.Part,result.FlatPattern!);
+ Assert.Contains(concepts,x=>x.Path=="Wall.Outer"&&x.Capabilities.Contains("FreeEdge"));
+ Assert.Contains(concepts,x=>x.Path==path.StableId&&x.Kind=="SheetAttachmentPath"&&x.Capabilities.Contains("FlangeAttachable"));
+ Assert.True(BrepExportPreflight.Validate(result.Part.FormedBody!).IsValid);
+ var flat=Assert.IsType<SheetMetalFlatPatternIr>(result.FlatPattern);
+ var flatValidation=SheetMetalFlatPatternValidation.Validate(flat);
+ Assert.True(flatValidation.ExactContoursValid,string.Join('\n',flatValidation.Diagnostics.Select(x=>$"{x.Code}: {x.Message}")));
+ var repeated=SheetMetalFirmament.Compile(InsetPartialFlange);
+ Assert.Equal(flat.DeterministicHash,repeated.FlatPattern!.DeterministicHash);
+ var repeatedPath=Assert.Single(repeated.Part!.AttachmentPaths!);
+ Assert.Equal((path.StableId,path.Start,path.End,path.Inset,path.SpanOffset),(repeatedPath.StableId,repeatedPath.Start,repeatedPath.End,repeatedPath.Inset,repeatedPath.SpanOffset));
+ Assert.Equal(path.Capabilities,repeatedPath.Capabilities);
+ }
+
+ [Theory]
+ [InlineData("Inset: -1mm; Span: 20mm;","sheetmetal-attachment-path-offset")]
+ [InlineData("Inset: 2mm; Span: 0mm;","sheetmetal-attachment-path-span")]
+ [InlineData("Inset: 25mm; Span: 20mm;","sheetmetal-attachment-path-offset")]
+ [InlineData("Inset: 2mm; Span: 110mm;","sheetmetal-attachment-path-span")]
+ public void AttachmentPath_RejectsImpossibleGeometry(string geometry,string code)
+ {
+ var source=$$"""
+ SheetMetal InvalidPath {
+ Thickness: 1mm;
+ Base Panel { Profile: Rectangle { Width: 100mm; Height: 60mm; }; }
+ Flange Wall { From: Panel.Rear; Height: 20mm; Angle: 90deg; Radius: 2mm; }
+ AttachmentPath Service { On: Wall.Outer; {{geometry}} Release: ToCarrier; }
+ Flange Lip { From: Wall.Service; Height: 12mm; Angle: 45deg; Radius: 2mm; }
+ }
+ """;
+ var result=SheetMetalFirmament.Compile(source);
+ Assert.False(result.IsSuccess);Assert.Contains(result.Diagnostics,x=>x.Code==code);
+ }
+
+ [Fact]
+ public void InsetPath_RequiresExplicitReleaseGeometry()
+ {
+ var result=SheetMetalFirmament.Compile(InsetPartialFlange.Replace("Release: ToCarrier;",string.Empty));
+ Assert.False(result.IsSuccess);Assert.Contains(result.Diagnostics,x=>x.Code=="sheetmetal-attachment-path-release");
+ }
+
+ [Fact]
+ public void FullEdgeFlangeSyntax_RemainsUnchanged()
+ {
+ var result=SheetMetalFirmament.Compile("""
+ SheetMetal LegacySurface {
+ Thickness: 1mm;
+ Base Panel { Profile: Rectangle { Width: 100mm; Height: 60mm; }; }
+ Flange Wall { From: Panel.Rear; Height: 20mm; Angle: 90deg; Radius: 2mm; }
+ Flange Lip { From: Wall.Outer; Height: 12mm; Angle: 45deg; Radius: 2mm; }
+ }
+ """);
+ Assert.True(result.IsSuccess,string.Join('\n',result.Diagnostics.Select(x=>x.Message)));
+ Assert.Empty(result.Part!.AttachmentPaths!);
+ }
+
+ [Fact]
+ public void RoundedSemanticCorner_RemainsAnalyticInRegionFormedAndFlat()
+ {
+ var result=SheetMetalFirmament.Compile("""
+ SheetMetal RoundedWall {
+ Thickness: 1mm;
+ Base Panel { Profile: Rectangle { Width: 100mm; Height: 60mm; }; }
+ Flange Wall { From: Panel.Rear; Height: 20mm; Angle: 90deg; Radius: 2mm; }
+ CornerProfile Wall.OuterStart { Round EndRound { Radius: 5mm; } }
+ }
+ """);
+ Assert.True(result.IsSuccess,string.Join('\n',result.Diagnostics.Select(x=>$"{x.Code}: {x.Message}")));
+ var region=result.Part!.Regions.Single(x=>x.StableId=="Wall");
+ var regionArc=Assert.Single(region.ExactContour!.OuterLoop.Segments,x=>x.Geometry is LineArcCircularArc2D);
+ Assert.Equal("Wall.OuterStart.EndRound.curve00",regionArc.StableId);
+ var flatRegion=result.FlatPattern!.Regions2D.Single(x=>x.SourceRegionId=="Wall");
+ Assert.Single(flatRegion.ExactContour!.OuterLoop.Segments,x=>x.Geometry is LineArcCircularArc2D);
+ Assert.True(result.Part.FormedBody!.Geometry.Curves.Count(x=>x.Value.Kind==CurveGeometryKind.Circle3&&Math.Abs(x.Value.Circle3!.Value.Radius-5)<1e-8)>=2);
+ Assert.Contains(result.Part.Correspondence!,x=>x.SemanticId=="Wall.OuterStart"&&x.Kind=="ProfileCorner");
+ }
+}
diff --git a/Aetheris.SheetMetal.Tests/SheetMetalProfileCornerM3Tests.cs b/Aetheris.SheetMetal.Tests/SheetMetalProfileCornerM3Tests.cs
index 8ad21d12..a03f013d 100644
--- a/Aetheris.SheetMetal.Tests/SheetMetalProfileCornerM3Tests.cs
+++ b/Aetheris.SheetMetal.Tests/SheetMetalProfileCornerM3Tests.cs
@@ -66,7 +66,7 @@ public sealed class SheetMetalProfileCornerM3Tests
var authored = SheetMetalFirmament.CompileFile(intent);
Assert.True(authored.IsSuccess, string.Join('\n', authored.Diagnostics.Select(x => x.Message)));
- Assert.Equal(10, authored.Spec!.SemanticLayout.Corners!.Count);
+ Assert.Equal(12, authored.Spec!.SemanticLayout.Corners!.Count);
var comparison = SheetMetalIntentComparer.Compare(source, authored.Part!);
Assert.All(comparison.Bends, x => Assert.Equal(SheetMetalComparisonStatus.Pass, x.Status));
Assert.All(comparison.Features, x => Assert.Equal(SheetMetalComparisonStatus.Pass, x.Status));
diff --git a/Aetheris.SheetMetal/SheetMetalAuthoredLowering.cs b/Aetheris.SheetMetal/SheetMetalAuthoredLowering.cs
index 9bf2ccb2..3933dd65 100644
--- a/Aetheris.SheetMetal/SheetMetalAuthoredLowering.cs
+++ b/Aetheris.SheetMetal/SheetMetalAuthoredLowering.cs
@@ -70,6 +70,15 @@ internal static class AuthoredSheetMetalCompiler
if (baseSpec is null || baseSpec.Width <= 0 || baseSpec.Depth <= 0)
return Fail("A positive rectangular base is required (`Base: Rectangle(w, d)` or named `Base <Name> { Profile: Rectangle { Width; Height; } }`).");
+ // Attachment paths are resolved fully by the semantic-layout pass after
+ // all region dimensions are known. This small pre-scan exists only so
+ // Flange.From capability checking can admit their public member names.
+ var declaredAttachmentPaths=Blocks(source,"AttachmentPath")
+ .Select(b=>(Block:b,On:Regex.Match(b.Body,@"\bOn\s*:\s*(?<region>[A-Za-z_][A-Za-z0-9_]*)\.(?<edge>[A-Za-z_][A-Za-z0-9_]*)\s*;",Rx)))
+ .Where(x=>x.On.Success)
+ .Select(x=>$"{x.On.Groups["region"].Value}.{x.Block.Name}")
+ .ToHashSet(StringComparer.OrdinalIgnoreCase);
+
var flanges = new List<AuthoredSheetFlangeSpec>();
foreach (var block in Blocks(source, "Flange"))
{
@@ -82,9 +91,11 @@ internal static class AuthoredSheetMetalCompiler
if(parentName.Equals(baseSpec.Name,StringComparison.OrdinalIgnoreCase)&&authoredMember.Equals("Center",StringComparison.OrdinalIgnoreCase))
return Fail($"`{parentName}.Center` has capability PointCapable; `Flange.From` requires FlangeAttachable SheetEdge. Available public edge members: Front, Right, Rear, Left.","sheetmetal-incompatible-edge-capability");
var available=parentName.Equals(baseSpec.Name,StringComparison.OrdinalIgnoreCase)?SheetMetalConceptPaths.AvailableMembers("SheetRegion.Rectangle"):SheetMetalConceptPaths.AvailableMembers("SheetFlange");
- var allowed=parentName.Equals(baseSpec.Name,StringComparison.OrdinalIgnoreCase)
+ var isAttachmentPath=declaredAttachmentPaths.Contains($"{parentName}.{authoredMember}");
+ var allowed=isAttachmentPath||parentName.Equals(baseSpec.Name,StringComparison.OrdinalIgnoreCase)
? new[]{"Front","Right","Rear","Left"}.Contains(authoredMember,StringComparer.OrdinalIgnoreCase)
: new[]{"Outer","Top"}.Contains(authoredMember,StringComparer.OrdinalIgnoreCase);
+ if(isAttachmentPath)allowed=true;
if(!allowed)return Fail($"`{parentName}.{authoredMember}` is not a FlangeAttachable public member. Available public members: {string.Join(", ",available)}.","sheetmetal-concept-member-not-exposed");
var direction = Token(block.Body, "Direction")?.Equals("Down", StringComparison.OrdinalIgnoreCase) == true ? SheetBendDirection.Down : SheetBendDirection.Up;
var corner = Token(block.Body, "Corner")?.ToLowerInvariant() switch
@@ -103,6 +114,7 @@ internal static class AuthoredSheetMetalCompiler
if(length<=radius+thickness)return Fail($"Flange '{block.Name}' length {length:G6} mm is not greater than inside radius + thickness ({radius+thickness:G6} mm). Increase `{block.Name}` Height/Length above {radius+thickness:G6} mm.",legacyBase.Success?"sheetmetal-firmament-invalid":SheetMetalDiagnosticCodes.FlangeBelowMinimum);
if(hasSpan&&spanLength<=0)return Fail($"Flange '{block.Name}' Span must be positive when supplied.","sheetmetal-flange-span-invalid");
if(hasSpanOffset&&!hasSpan)return Fail($"Flange '{block.Name}' SpanOffset requires Span.","sheetmetal-flange-span-invalid");
+ if(isAttachmentPath&&(hasSpan||hasSpanOffset))return Fail($"Flange '{block.Name}' consumes bounded path '{parentName}.{authoredMember}'; put Span and SpanOffset on the AttachmentPath, not the flange.","sheetmetal-attachment-path-span-conflict");
flanges.Add(new(block.Name, parentName, NormalizeEdge(authoredMember), length,
degrees * Math.PI / 180d, radius, direction, corner, relief,
reliefWidth > 0 ? reliefWidth : null, reliefDepth > 0 ? reliefDepth : null,
@@ -218,7 +230,8 @@ internal static class AuthoredSheetMetalLowering
public Point3D OuterB => B + Outward * Length;
}
private sealed record Patch(string Id, SheetRegionKind Kind, IReadOnlyList<Point3D> Positive, IReadOnlyList<Point3D> Negative,
- SurfaceGeometry PositiveSurface, SurfaceGeometry NegativeSurface, Point3D? CylinderCenter = null, Vector3D? CylinderAxis = null);
+ SurfaceGeometry PositiveSurface, SurfaceGeometry NegativeSurface, Point3D? CylinderCenter = null, Vector3D? CylinderAxis = null,
+ SheetPlaneReference? Plane = null,PlanarContour2? ExactContour = null);
public static AuthoredSheetLoweringResult Lower(SheetMetalConstructionSpec spec, string sourcePath)
{
@@ -226,6 +239,7 @@ internal static class AuthoredSheetMetalLowering
var source = new SheetSourceBinding("Firmament declaration", "sole construction authority", [], [], sourcePath);
var evidence = new[] { new SheetEvidence(SheetEvidenceKind.Authored, "source-independent-construction", "All dimensions, adjacency, cuts, corners, and bend policy come from this Firmament source.") };
var regions = new List<SheetRegionIr>(); var bends = new List<SheetBendIr>(); var features = new List<SheetFeatureIr>();
+ var attachmentPaths = new List<SheetAttachmentPathIr>();
var corners = new List<SheetMetalCornerIr>(); var reliefs = new List<SheetMetalReliefIr>(); var correspondence = new List<SheetMetalCorrespondence>();
var patches = new List<Patch>(); var frames = new Dictionary<string, RegionFrame>(StringComparer.OrdinalIgnoreCase);
var stableRegions = new Dictionary<string,string>(StringComparer.OrdinalIgnoreCase) { [spec.Base.Name] = spec.LegacySyntax ? "region-base" : spec.Base.Name };
@@ -266,7 +280,7 @@ internal static class AuthoredSheetMetalLowering
var basePlane = new SheetPlaneReference(origin+new Vector3D(0,0,mid), z, x, y, true);
var baseId=stableRegions[spec.Base.Name];
regions.Add(new(baseId, SheetRegionKind.Planar, Developable("Authored planar base."), basePlane, null, baseBoundary, w * d, source, evidence));
- patches.Add(PlanePatch(baseId, SheetRegionKind.Planar, baseBoundary, z, t));
+ patches.Add(PlanePatch(baseId, SheetRegionKind.Planar, baseBoundary, z, t,basePlane));
correspondence.Add(new(spec.Base.Name, "Region", baseId, $"flat-{baseId}"));
var pending = new List<AuthoredSheetFlangeSpec>(spec.Flanges); var guard = 0;
@@ -276,7 +290,33 @@ internal static class AuthoredSheetMetalLowering
foreach (var flange in pending.ToArray())
{
EdgeFrame? parentEdge = null; Vector3D parentNormal;
- if (flange.ParentRegion.Equals(spec.Base.Name, StringComparison.OrdinalIgnoreCase) && baseEdges.TryGetValue(flange.EdgeName, out var be)) { parentEdge = be; parentNormal = z; }
+ var attachment=spec.SemanticLayout.AttachmentPaths?.SingleOrDefault(x=>x.Path.Equals($"{flange.ParentRegion}.{flange.EdgeName}",StringComparison.OrdinalIgnoreCase));
+ if(attachment is not null)
+ {
+ EdgeFrame? carrier=null;
+ if(attachment.Region.Equals(spec.Base.Name,StringComparison.OrdinalIgnoreCase)&&baseEdges.TryGetValue(attachment.CarrierEdge,out var baseCarrier)){carrier=baseCarrier;parentNormal=z;}
+ else if(frames.TryGetValue(attachment.Region,out var ownerFrame)&&attachment.CarrierEdge.Equals("Outer",StringComparison.OrdinalIgnoreCase)){carrier=new(ownerFrame.OuterA,ownerFrame.OuterB,ownerFrame.Outward);parentNormal=ownerFrame.Normal;}
+ else continue;
+ var carrierAxis=Unit(carrier.B-carrier.A);var pathCenter=Mid(carrier.A,carrier.B)+carrierAxis*attachment.SpanOffset-carrier.Outward*attachment.Inset;
+ parentEdge=new(pathCenter-carrierAxis*(attachment.Span/2d),pathCenter+carrierAxis*(attachment.Span/2d),carrier.Outward);
+ var ownerId=stableRegions.GetValueOrDefault(attachment.Region,attachment.Region);
+ if(attachment.ReleaseToCarrier&&attachment.Inset>1e-8)
+ {
+ var ownerIndex=regions.FindIndex(x=>x.StableId.Equals(ownerId,StringComparison.Ordinal));
+ var patchIndex=patches.FindIndex(x=>x.Id.Equals(ownerId,StringComparison.Ordinal));
+ if(ownerIndex<0||patchIndex<0)return Failure($"Attachment path '{attachment.Path}' could not locate owning planar region '{attachment.Region}'.","sheetmetal-attachment-path-owner");
+ var released=ReleaseToCarrier(regions[ownerIndex].Boundary3D,carrier,parentEdge);
+ if(released is null)return Failure($"Attachment path '{attachment.Path}' carrier is not an exact physical boundary segment of '{attachment.Region}'.","sheetmetal-attachment-path-release");
+ var ownerRegion=regions[ownerIndex];var releasedContour=ownerRegion.ExactContour is null?null:ReleaseContourToCarrier(ownerRegion.ExactContour,ownerRegion.Plane!,carrier,parentEdge,attachment.Path);
+ regions[ownerIndex]=ownerRegion with { Boundary3D=released,ApproximateArea=ownerRegion.ApproximateArea-attachment.Span*attachment.Inset,ExactContour=releasedContour };
+ patches[patchIndex]=PlanePatch(ownerId,SheetRegionKind.Planar,released,parentNormal,t,ownerRegion.Plane!,releasedContour);
+ }
+ attachmentPaths.Add(new(attachment.Path,ownerId,$"{attachment.Region}.{attachment.CarrierEdge}",parentEdge.A,parentEdge.B,carrierAxis,carrier.Outward,parentNormal,attachment.Inset,attachment.SpanOffset,
+ [SheetPathCapability.FlangeAttachable,SheetPathCapability.BendAttachable,SheetPathCapability.FeatureAttachable],source,
+ [new(SheetEvidenceKind.Authored,"bounded-attachment-path","Path geometry derives from its physical carrier, inset, span, and span offset without changing carrier identity.",attachment.Span)]));
+ correspondence.Add(new(attachment.Path,"AttachmentPath",attachment.Path,$"flat-{attachment.Path}"));
+ }
+ else if (flange.ParentRegion.Equals(spec.Base.Name, StringComparison.OrdinalIgnoreCase) && baseEdges.TryGetValue(flange.EdgeName, out var be)) { parentEdge = be; parentNormal = z; }
else if (frames.TryGetValue(flange.ParentRegion, out var pf) && flange.EdgeName.Equals("Outer", StringComparison.OrdinalIgnoreCase)) { parentEdge = new(pf.OuterA, pf.OuterB, pf.Outward); parentNormal = pf.Normal; }
else continue;
progressed = true; pending.Remove(flange);
@@ -311,6 +351,7 @@ internal static class AuthoredSheetMetalLowering
"CUTBACK"=>new SemanticCornerCutbackIr(program.OperationPath.Split('.').Last(),program.OperationPath,program.SetbackA,program.SetbackB,"SheetMetalSemanticLayout"),
"TAPER"=>new SemanticCornerTaperIr(program.OperationPath.Split('.').Last(),program.OperationPath,program.SetbackA,program.SetbackB,"SheetMetalSemanticLayout"),
"NOTCHCORNER"=>new SemanticCornerNotchIr(program.OperationPath.Split('.').Last(),program.OperationPath,program.SetbackA,program.SetbackB,"SheetMetalSemanticLayout"),
+ "ROUND"=>new SemanticCornerRoundIr(program.OperationPath.Split('.').Last(),program.OperationPath,program.SetbackA,"SheetMetalSemanticLayout"),
_=>throw new InvalidOperationException()
};
var request=program.Corner.ToUpperInvariant() switch
@@ -346,23 +387,25 @@ internal static class AuthoredSheetMetalLowering
if(edgeFailures.Length>0)return Failure($"Profile edge composition for '{flange.Name}' failed: {string.Join("; ",edgeFailures)}","sheetmetal-edge-profile-invalid");
Point3D Map((double X,double Y) point)=>tangentA+axis*point.X+direction*point.Y;
var points=new List<Point3D>();
+ var localCurves=new List<(string Id,LineArcProfileCurve2D Geometry,string Provenance)>();
void Add(Point3D point){if(points.Count==0||(point-points[^1]).Length>1e-8)points.Add(point);}
void AddEdge(SemanticEdgeProfileResolution profile)
{
var descendants=profile.Profile!.OrderedMembers.SelectMany(member=>member.CurveDescendants).ToArray();
if(descendants.Length==0)return;
Add(Map(((LineArcLineSegment2D)descendants[0].Geometry).Start));
- foreach(var descendant in descendants)Add(Map(((LineArcLineSegment2D)descendant.Geometry).End));
+ foreach(var descendant in descendants){localCurves.Add((descendant.StableId,descendant.Geometry,descendant.Provenance));Add(Map(End(descendant.Geometry)));}
}
void AddCorner(ResolvedSemanticCornerProfileIr? corner)
{
if(corner is null)return;
Add(Map((corner.EdgeAEndpoint.X,corner.EdgeAEndpoint.Y)));
- foreach(var descendant in corner.CurveDescendants)Add(Map(((LineArcLineSegment2D)descendant.Geometry).End));
+ foreach(var descendant in corner.CurveDescendants){localCurves.Add((descendant.StableId,descendant.Geometry,descendant.Provenance));Add(Map(End(descendant.Geometry)));}
}
AddEdge(rootEdge);AddCorner(rootEndCorner);AddEdge(endBEdge);AddCorner(outerStartCorner);AddEdge(composed);AddCorner(outerEndCorner);AddEdge(endAEdge);AddCorner(rootStartCorner);
if(points.Count>1&&(points[^1]-points[0]).Length<=1e-8)points.RemoveAt(points.Count-1);
IReadOnlyList<Point3D> boundary=points;
+ var exactContour=new PlanarContour2($"{flange.Name}.Profile",$"{flange.Name}[u,v]",new($"{flange.Name}.OuterLoop",true,localCurves.Select(x=>new PlanarContourSegment2(x.Id,x.Geometry,new(x.Id,flange.Name,x.Id,x.Provenance,$"{flange.Name}[u,v]"))).ToArray()),[],$"semantic Sheet Metal profile:{flange.Name}");
foreach(var fragment in composed.Profile!.OrderedMembers.Where(member=>!member.IsGeneratedCarrier))
correspondence.Add(new(fragment.StableId,"EdgeFragment",fragment.StableId,$"flat-{fragment.StableId}"));
foreach(var corner in new[]{rootStartCorner,rootEndCorner,outerStartCorner,outerEndCorner}.OfType<ResolvedSemanticCornerProfileIr>())
@@ -370,8 +413,8 @@ internal static class AuthoredSheetMetalLowering
var plane = new SheetPlaneReference(tangentA, normal, axis, direction, true);
var flangeId=stableRegions[flange.Name];
var fragmentArea=tabs.Sum(x=>x.Width*x.Extension)-steppedNotches.Sum(x=>x.Width*x.Depth);
- regions.Add(new(flangeId, SheetRegionKind.Planar, Developable("Authored planar flange."), plane, null, boundary, (edge.B-edge.A).Length * flange.Length+fragmentArea, source, evidence));
- patches.Add(PlanePatch(flangeId, SheetRegionKind.Planar, boundary, normal, t));
+ regions.Add(new(flangeId, SheetRegionKind.Planar, Developable("Authored planar flange."), plane, null, boundary, (edge.B-edge.A).Length * flange.Length+fragmentArea, source, evidence,exactContour));
+ patches.Add(PlanePatch(flangeId, SheetRegionKind.Planar, boundary, normal, t,plane,exactContour));
var bendId = spec.LegacySyntax ? $"bend-{flange.EdgeName.ToLowerInvariant()}" : $"{flange.Name}Bend"; var bendRegionId = spec.LegacySyntax ? $"region-{flange.EdgeName.ToLowerInvariant()}-bend" : $"{flange.Name}BendRegion"; var centerA = edge.A + parentNormal * (sign * rMid); var center = Mid(centerA, edge.B + parentNormal * (sign * rMid));
var cylinder = new SheetCylinderReference(center, axis, rMid, flange.InsideRadius, angle, (edge.B-edge.A).Length, sign > 0);
@@ -412,7 +455,7 @@ internal static class AuthoredSheetMetalLowering
var authorityText = spec.Authority == SheetMetalProvenanceCategory.Reconstructed ? "Reconstructed Firmament engineering intent" : "Authored Firmament engineering intent";
var part = new SheetMetalPartIr($"sheetmetal-{spec.Name}", t, spec.Material, baseId, regions, bends, features, new(spec.KFactor), status,
$"{authorityText}; source-independent exact formed lowering.", [new(SheetEvidenceKind.Authored, "construction-authority", authorityText)], diagnostics, bodyResult.Value,
- corners, reliefs, correspondence, SheetFlangeLengthMode.TangentToEdge);
+ corners, reliefs, correspondence, SheetFlangeLengthMode.TangentToEdge,attachmentPaths);
return new(true, part, diagnostics);
void AddCorners()
@@ -444,11 +487,11 @@ internal static class AuthoredSheetMetalLowering
AuthoredSheetLoweringResult Failure(string message, string code) => new(false, null, [new(code, SheetMetalDiagnosticSeverity.Error, message)]);
}
- private static Patch PlanePatch(string id, SheetRegionKind kind, IReadOnlyList<Point3D> mid, Vector3D normal, double thickness)
+ private static Patch PlanePatch(string id, SheetRegionKind kind, IReadOnlyList<Point3D> mid, Vector3D normal, double thickness,SheetPlaneReference plane,PlanarContour2? exactContour=null)
{
var n = Unit(normal); var positive = mid.Select(p => p + n * (thickness/2)).ToArray(); var negative = mid.Select(p => p - n * (thickness/2)).ToArray();
var u = Unit(mid[1]-mid[0]);
- return new(id, kind, positive, negative, SurfaceGeometry.FromPlane(new PlaneSurface(positive[0], Direction3D.Create(n), Direction3D.Create(u))), SurfaceGeometry.FromPlane(new PlaneSurface(negative[0], Direction3D.Create(-n), Direction3D.Create(u))));
+ return new(id, kind, positive, negative, SurfaceGeometry.FromPlane(new PlaneSurface(positive[0], Direction3D.Create(n), Direction3D.Create(u))), SurfaceGeometry.FromPlane(new PlaneSurface(negative[0], Direction3D.Create(-n), Direction3D.Create(u))),Plane:plane,ExactContour:exactContour);
}
private static Patch BendPatch(string id, EdgeFrame edge, Vector3D parentNormal, AuthoredSheetFlangeSpec flange, double thickness)
{
@@ -466,6 +509,50 @@ internal static class AuthoredSheetMetalLowering
}
private static DevelopabilityEvidence Developable(string note)=>new(DevelopabilityKind.Developable,"authored analytic construction",0,0,note);
private static IReadOnlyList<Point3D> RectangleLoop(Point3D c,Vector3D u,Vector3D v,double length,double width)=>[c-u*(length/2)-v*(width/2),c+u*(length/2)-v*(width/2),c+u*(length/2)+v*(width/2),c-u*(length/2)+v*(width/2)];
+ private static (double X,double Y) End(LineArcProfileCurve2D curve)=>curve switch
+ {
+ LineArcLineSegment2D line=>line.End,
+ LineArcCircularArc2D arc=>(arc.Center.X+arc.Radius*Math.Cos(arc.StartAngleRadians+arc.SweepAngleRadians),arc.Center.Y+arc.Radius*Math.Sin(arc.StartAngleRadians+arc.SweepAngleRadians)),
+ _=>throw new InvalidOperationException($"Unsupported profile curve '{curve.GetType().Name}'.")
+ };
+ private static IReadOnlyList<Point3D>? ReleaseToCarrier(IReadOnlyList<Point3D> boundary,EdgeFrame carrier,EdgeFrame path)
+ {
+ var axis=Unit(carrier.B-carrier.A);
+ var outerStart=carrier.A+axis*((path.A-carrier.A).Dot(axis));
+ var outerEnd=carrier.A+axis*((path.B-carrier.A).Dot(axis));
+ for(var i=0;i<boundary.Count;i++)
+ {
+ var j=(i+1)%boundary.Count;var a=boundary[i];var b=boundary[j];
+ var ta=(a-carrier.A).Dot(axis);var tb=(b-carrier.A).Dot(axis);var ts=(outerStart-carrier.A).Dot(axis);var te=(outerEnd-carrier.A).Dot(axis);
+ var onCarrier=((a-carrier.A)-axis*ta).Length<1e-7&&((b-carrier.A)-axis*tb).Length<1e-7;
+ if(!onCarrier||Math.Min(ta,tb)>ts+1e-8||Math.Max(ta,tb)<te-1e-8)continue;
+ if(tb>ta)return CleanLoop(boundary.Take(i+1).Concat(new[]{outerStart,path.A,path.B,outerEnd}).Concat(boundary.Skip(i+1)).ToList());
+ return CleanLoop(boundary.Take(i+1).Concat(new[]{outerEnd,path.B,path.A,outerStart}).Concat(boundary.Skip(i+1)).ToList());
+ }
+ return null;
+ }
+ private static PlanarContour2? ReleaseContourToCarrier(PlanarContour2 contour,SheetPlaneReference plane,EdgeFrame carrier,EdgeFrame path,string pathId)
+ {
+ (double X,double Y) Local(Point3D p){var d=p-plane.Origin;return(d.Dot(plane.UAxis),d.Dot(plane.VAxis));}
+ var ca=Local(carrier.A);var cb=Local(carrier.B);var pa=Local(path.A);var pb=Local(path.B);var dx=cb.X-ca.X;var dy=cb.Y-ca.Y;var length=Math.Sqrt(dx*dx+dy*dy);if(length<1e-8)return null;dx/=length;dy/=length;
+ var oa=(ca.X+dx*((pa.X-ca.X)*dx+(pa.Y-ca.Y)*dy),ca.Y+dy*((pa.X-ca.X)*dx+(pa.Y-ca.Y)*dy));
+ var ob=(ca.X+dx*((pb.X-ca.X)*dx+(pb.Y-ca.Y)*dy),ca.Y+dy*((pb.X-ca.X)*dx+(pb.Y-ca.Y)*dy));
+ var segments=new List<PlanarContourSegment2>();var replaced=false;
+ foreach(var segment in contour.OuterLoop.Segments)
+ {
+ if(!replaced&&segment.Geometry is LineArcLineSegment2D line&&Contains(line,oa,ob))
+ {
+ var forward=Projection(line.End)>Projection(line.Start);var chain=forward?new[]{line.Start,oa,pa,pb,ob,line.End}:new[]{line.Start,ob,pb,pa,oa,line.End};
+ for(var i=0;i<chain.Length-1;i++)if(Distance(chain[i],chain[i+1])>1e-8)segments.Add(new($"{pathId}.release{i:D2}",new LineArcLineSegment2D(chain[i],chain[i+1]),segment.Provenance with { StableId=$"{pathId}.release{i:D2}",ConceptStableId=pathId,SourceSpan="AttachmentPath Release: ToCarrier" }));
+ replaced=true;
+ }
+ else segments.Add(segment);
+ }
+ return replaced?contour with { OuterLoop=contour.OuterLoop with { Segments=segments } }:null;
+ double Projection((double X,double Y) p)=>(p.X-ca.X)*dx+(p.Y-ca.Y)*dy;
+ bool Contains(LineArcLineSegment2D line,(double X,double Y) a,(double X,double Y) b){var crossA=Math.Abs((a.X-line.Start.X)*(line.End.Y-line.Start.Y)-(a.Y-line.Start.Y)*(line.End.X-line.Start.X));var crossB=Math.Abs((b.X-line.Start.X)*(line.End.Y-line.Start.Y)-(b.Y-line.Start.Y)*(line.End.X-line.Start.X));var min=Math.Min(Projection(line.Start),Projection(line.End))-1e-7;var max=Math.Max(Projection(line.Start),Projection(line.End))+1e-7;return crossA<1e-6&&crossB<1e-6&&Projection(a)>=min&&Projection(b)<=max;}
+ static double Distance((double X,double Y) a,(double X,double Y)b)=>Math.Sqrt((a.X-b.X)*(a.X-b.X)+(a.Y-b.Y)*(a.Y-b.Y));
+ }
private static string Previous(string edge)=>edge switch{"Front"=>"Left","Right"=>"Front","Rear"=>"Right",_=>"Rear"};
private static string Next(string edge)=>edge switch{"Front"=>"Right","Right"=>"Rear","Rear"=>"Left",_=>"Front"};
private static double CornerGap(AuthoredSheetFlangeSpec a,AuthoredSheetFlangeSpec b,double t)=>a.CornerPolicy==SheetCornerPolicy.Mitered&&b.CornerPolicy==SheetCornerPolicy.Mitered?Math.Max(a.InsideRadius,b.InsideRadius)+t/2:Math.Max(Math.Max(a.InsideRadius,b.InsideRadius)+t, a.ReliefWidth??0);
@@ -486,7 +573,7 @@ internal static class AuthoredSheetMetalLowering
{
var b=new TopologyBuilder();var g=new BrepGeometryStore();var bindings=new BrepBindingModel();var points=new Dictionary<VertexId,Point3D>();
var vertices=new Dictionary<Key,VertexId>();var edges=new Dictionary<EdgeKey,EdgeId>();var edgeGeometry=new Dictionary<EdgeId,EdgeGeometry>();var useCount=new Dictionary<EdgeId,int>();var faces=new List<FaceId>();
- var boundaryCandidates=new List<(EdgeId Positive,EdgeId Negative,Point3D PA,Point3D PB,Point3D NA,Point3D NB)>();
+ var boundaryCandidates=new List<(EdgeId Positive,EdgeId Negative,Point3D PA,Point3D PB,Point3D NA,Point3D NB,bool ProfileArc)>();
var cutsByRegion=new Dictionary<string,List<CutBoundary>>(StringComparer.Ordinal);
VertexId Vertex(Point3D p){var key=Key.Of(p);if(vertices.TryGetValue(key,out var id))return id;id=b.AddVertex();vertices[key]=id;points[id]=p;return id;}
EdgeId Edge(Point3D a,Point3D q,EdgeGeometry? geometry=null){var key=EdgeKey.Of(a,q);if(edges.TryGetValue(key,out var id))return id;id=b.AddEdge(Vertex(a),Vertex(q));edges[key]=id;edgeGeometry[id]=geometry??Line(a,q);return id;}
@@ -502,14 +589,18 @@ internal static class AuthoredSheetMetalLowering
{
var j=(i+1)%count;var pg=CurveFor(patch,true,i,patch.Positive[i],patch.Positive[j]);var ng=CurveFor(patch,false,i,patch.Negative[i],patch.Negative[j]);
var pe=Edge(patch.Positive[i],patch.Positive[j],pg);var ne=Edge(patch.Negative[i],patch.Negative[j],ng);
- boundaryCandidates.Add((pe,ne,patch.Positive[i],patch.Positive[j],patch.Negative[i],patch.Negative[j]));
+ boundaryCandidates.Add((pe,ne,patch.Positive[i],patch.Positive[j],patch.Negative[i],patch.Negative[j],patch.Kind==SheetRegionKind.Planar&&pg.Curve.Kind==CurveGeometryKind.Circle3));
}
}
foreach(var candidate in boundaryCandidates)
{
if(useCount.GetValueOrDefault(candidate.Positive)!=1||useCount.GetValueOrDefault(candidate.Negative)!=1)continue;
var loop=new[]{DirectedEdge(candidate.PA,candidate.PB),DirectedEdge(candidate.PB,candidate.NB),DirectedEdge(candidate.NB,candidate.NA),DirectedEdge(candidate.NA,candidate.PA)};
- var u=candidate.PB-candidate.PA;var v=candidate.NA-candidate.PA;var normal=Unit(u.Cross(v));Face([loop],SurfaceGeometry.FromPlane(new PlaneSurface(candidate.PA,Direction3D.Create(normal),Direction3D.Create(Unit(u)))));
+ if(candidate.ProfileArc&&edgeGeometry[candidate.Positive].Curve is { Kind:CurveGeometryKind.Circle3,Circle3:{ } arcCircle })
+ {
+ var axis=Unit(candidate.PA-candidate.NA);Face([loop],SurfaceGeometry.FromCylinder(new CylinderSurface(arcCircle.Center,Direction3D.Create(axis),arcCircle.Radius,Direction3D.Create(candidate.PA-arcCircle.Center))));
+ }
+ else{var u=candidate.PB-candidate.PA;var v=candidate.NA-candidate.PA;var normal=Unit(u.Cross(v));Face([loop],SurfaceGeometry.FromPlane(new PlaneSurface(candidate.PA,Direction3D.Create(normal),Direction3D.Create(Unit(u)))));}
}
AddCutWalls();
foreach(var (edge,geometry) in edgeGeometry.OrderBy(x=>x.Key.Value)){var cid=new CurveGeometryId(g.Curves.Count()+1);g.AddCurve(cid,geometry.Curve);bindings.AddEdgeBinding(new(edge,cid,geometry.Interval));}
@@ -531,6 +622,13 @@ internal static class AuthoredSheetMetalLowering
}
EdgeGeometry CurveFor(Patch patch,bool positive,int index,Point3D a,Point3D q)
{
+ if(patch.Kind==SheetRegionKind.Planar&&patch.ExactContour is not null&&patch.Plane is not null&&index<patch.ExactContour.OuterLoop.Segments.Count&&patch.ExactContour.OuterLoop.Segments[index].Geometry is LineArcCircularArc2D planarArc)
+ {
+ var plane=patch.Plane;var n=Unit(plane.Normal);var planarCenter=plane.Origin+plane.UAxis*planarArc.Center.X+plane.VAxis*planarArc.Center.Y+n*(positive?spec.Thickness/2:-spec.Thickness/2);
+ var planarVa=Unit(a-planarCenter);var planarVq=Unit(q-planarCenter);var planarSigned=Math.Atan2(n.Dot(planarVa.Cross(planarVq)),planarVa.Dot(planarVq));if(planarSigned<0){n=-n;planarSigned=-planarSigned;}
+ var planarCircle=new Circle3Curve(planarCenter,Direction3D.Create(n),planarArc.Radius,Direction3D.Create(a-planarCenter));
+ return new(CurveGeometry.FromCircle(planarCircle),new(0,Math.Max(planarSigned,1e-12)));
+ }
if(patch.Kind!=SheetRegionKind.CylindricalBend||index is 0 or 2)return Line(a,q);
var center=patch.CylinderCenter!.Value;var axis=Unit(patch.CylinderAxis!.Value);var endpointCenter=ProjectToAxis(a,center,axis);var radius=(a-endpointCenter).Length;var va=a-endpointCenter;var vq=q-ProjectToAxis(q,center,axis);var signed=Math.Atan2(axis.Dot(Unit(va).Cross(Unit(vq))),Unit(va).Dot(Unit(vq)));if(signed<0){axis=-axis;signed=-signed;}var circle=new Circle3Curve(endpointCenter,Direction3D.Create(axis),radius,Direction3D.Create(va));return new(CurveGeometry.FromCircle(circle),new(0,Math.Max(signed,1e-12)));
}
diff --git a/Aetheris.SheetMetal/SheetMetalConceptPaths.cs b/Aetheris.SheetMetal/SheetMetalConceptPaths.cs
index fcedc0d0..f6f285c9 100644
--- a/Aetheris.SheetMetal/SheetMetalConceptPaths.cs
+++ b/Aetheris.SheetMetal/SheetMetalConceptPaths.cs
@@ -41,6 +41,11 @@ public static class SheetMetalConceptPaths
}
foreach(var datum in spec.SemanticLayout.Datums)
Add(datum.Path,"SheetDatum",datum.Path,null,null,datum.Provenance,"PointCapable","StableSemanticIdentity");
+ foreach(var attachment in spec.SemanticLayout.AttachmentPaths??[])
+ {
+ var ir=part.AttachmentPaths?.FirstOrDefault(x=>x.StableId.Equals(attachment.Path,StringComparison.Ordinal));
+ Add(attachment.Path,"SheetAttachmentPath",attachment.Path,ir?.StableId,$"flat-{attachment.Path}","bounded region-owned path derived from a physical carrier","FlangeAttachable","BendAttachable","FeatureAttachable","StableSemanticIdentity");
+ }
foreach(var tab in spec.SemanticLayout.Tabs)
Add(tab.Path,"SheetTab",tab.Path,tab.Region,$"flat-{tab.Region}","exact outer-edge contour extension","EdgeFeature","ManufacturingContour","StableSemanticIdentity");
foreach(var notch in spec.SemanticLayout.SteppedNotches??[])
diff --git a/Aetheris.SheetMetal/SheetMetalFlattener.cs b/Aetheris.SheetMetal/SheetMetalFlattener.cs
index 642e4e51..3e7d94a1 100644
--- a/Aetheris.SheetMetal/SheetMetalFlattener.cs
+++ b/Aetheris.SheetMetal/SheetMetalFlattener.cs
@@ -67,7 +67,8 @@ public static class SheetMetalFlattener
var flatRegions=mappings.Values.OrderBy(m=>m.Region.StableId,StringComparer.Ordinal).Select(m=>
{
var boundary=NormalizeSourcePolygon(m.Region.Boundary3D.Select(m.Map));
- return new FlatRegion2D($"flat-{m.Region.StableId}",m.Region.StableId,SheetRegionKind.Planar,boundary,"exact ordered source-edge vertices through composed analytic plane-to-flat transform",Contour($"flat-{m.Region.StableId}",boundary,"analytic plane-to-flat transform"));
+ var exact=m.Region.ExactContour is null?Contour($"flat-{m.Region.StableId}",boundary,"analytic plane-to-flat transform"):MapContour(m.Region.ExactContour,m);
+ return new FlatRegion2D($"flat-{m.Region.StableId}",m.Region.StableId,SheetRegionKind.Planar,boundary,"exact ordered source-edge vertices through composed analytic plane-to-flat transform",exact);
}).ToList();
flatRegions.AddRange(bendRegions.OrderBy(r=>r.StableId,StringComparer.Ordinal));
var cuts=new List<FlatCutLoop>();
@@ -127,6 +128,36 @@ public static class SheetMetalFlattener
var d=anchor-p.Origin;var contribution=Add(Scale(flatU,d.Dot(p.UAxis)),Scale(flatV,d.Dot(p.VAxis)));
return new(region,Sub(target,contribution),flatU,flatV);
}
+ private static PlanarContour2 MapContour(PlanarContour2 contour,Mapping mapping)
+ {
+ var plane=mapping.Region.Plane!;
+ SheetPoint2 Map((double X,double Y) p)=>mapping.Map(plane.Origin+plane.UAxis*p.X+plane.VAxis*p.Y);
+ var orientation=mapping.FlatU.X*mapping.FlatV.Y-mapping.FlatU.Y*mapping.FlatV.X;
+ PlanarContourLoop2 Loop(PlanarContourLoop2 loop)
+ {
+ var mapped=loop.Segments.Select(segment=>
+ {
+ LineArcProfileCurve2D geometry=segment.Geometry switch
+ {
+ LineArcLineSegment2D line=>new LineArcLineSegment2D(ToTuple(Map(line.Start)),ToTuple(Map(line.End))),
+ LineArcCircularArc2D arc=>MapArc(arc),
+ _=>throw new InvalidOperationException($"Unsupported exact Sheet Metal curve '{segment.Geometry.GetType().Name}'.")
+ };
+ return new PlanarContourSegment2($"flat-{segment.StableId}",geometry,segment.Provenance with { StableId=$"flat-{segment.Provenance.StableId}",Derivation=segment.Provenance.Derivation+"; exact plane-to-flat transform",SourceFrame="XY" });
+ }).ToArray();
+ if(orientation<0)mapped=mapped.Reverse().Select(x=>x with { Geometry=Reverse(x.Geometry) }).ToArray();
+ return new($"flat-{loop.StableId}",loop.IsOuter,mapped);
+ }
+ LineArcCircularArc2D MapArc(LineArcCircularArc2D arc){var center=Map(arc.Center);var start=Map((arc.Center.X+arc.Radius*Math.Cos(arc.StartAngleRadians),arc.Center.Y+arc.Radius*Math.Sin(arc.StartAngleRadians)));return new(ToTuple(center),arc.Radius,Math.Atan2(start.Y-center.Y,start.X-center.X),orientation>=0?arc.SweepAngleRadians:-arc.SweepAngleRadians);}
+ static (double X,double Y) ToTuple(SheetPoint2 p)=>(p.X,p.Y);
+ static LineArcProfileCurve2D Reverse(LineArcProfileCurve2D curve)=>curve switch
+ {
+ LineArcLineSegment2D line=>new LineArcLineSegment2D(line.End,line.Start),
+ LineArcCircularArc2D arc=>arc with { StartAngleRadians=arc.StartAngleRadians+arc.SweepAngleRadians,SweepAngleRadians=-arc.SweepAngleRadians },
+ _=>throw new InvalidOperationException()
+ };
+ return new($"flat-{contour.StableId}","XY",Loop(contour.OuterLoop),contour.InnerLoops.Select(Loop).ToArray(),contour.Provenance+"; exact plane-to-flat transform");
+ }
private static double FindBendAxisLength(SheetMetalPartIr part,SheetBendIr bend)=>part.Regions
.Where(r=>r.Cylinder is not null)
diff --git a/Aetheris.SheetMetal/SheetMetalIr.cs b/Aetheris.SheetMetal/SheetMetalIr.cs
index ab70d7ea..f800b08b 100644
--- a/Aetheris.SheetMetal/SheetMetalIr.cs
+++ b/Aetheris.SheetMetal/SheetMetalIr.cs
@@ -21,6 +21,7 @@ public enum SheetReliefKind { Rectangular, Round, Unknown }
public enum SheetCornerPolicy { Open, Mitered, RectangularRelief, RoundRelief, Relief = RectangularRelief }
public enum SheetReliefPolicy { None, Auto, Rectangular, Round }
public enum SheetFlangeLengthMode { TangentToEdge }
+public enum SheetPathCapability { FlangeAttachable, BendAttachable, FeatureAttachable }
public static class SheetMetalDiagnosticCodes
{
@@ -105,7 +106,8 @@ public sealed record SheetRegionIr(
IReadOnlyList<Point3D> Boundary3D,
double ApproximateArea,
SheetSourceBinding Source,
- IReadOnlyList<SheetEvidence> Evidence);
+ IReadOnlyList<SheetEvidence> Evidence,
+ PlanarContour2? ExactContour = null);
public sealed record SheetNeutralAxisPolicy(string Kind, double KFactor)
{
@@ -165,6 +167,26 @@ public sealed record SheetMetalCorrespondence(
string FormedId,
string FlatId);
+/// <summary>
+/// An oriented, bounded path owned by a planar sheet region. Unlike a region
+/// boundary this is feature intent: it may be shorter than, or inset from, the
+/// physical carrier edge from which it was authored.
+/// </summary>
+public sealed record SheetAttachmentPathIr(
+ string StableId,
+ string OwningRegionId,
+ string CarrierPath,
+ Point3D Start,
+ Point3D End,
+ Vector3D Tangent,
+ Vector3D InPlaneNormal,
+ Vector3D RegionNormal,
+ double Inset,
+ double SpanOffset,
+ IReadOnlyList<SheetPathCapability> Capabilities,
+ SheetSourceBinding Source,
+ IReadOnlyList<SheetEvidence> Evidence);
+
public sealed record SheetMetalFlattenPolicy(double KFactor)
{
public static SheetMetalFlattenPolicy Default { get; } = new(0.5d);
@@ -224,7 +246,8 @@ public sealed record SheetMetalPartIr(
IReadOnlyList<SheetMetalCornerIr>? Corners = null,
IReadOnlyList<SheetMetalReliefIr>? Reliefs = null,
IReadOnlyList<SheetMetalCorrespondence>? Correspondence = null,
- SheetFlangeLengthMode FlangeLengthMode = SheetFlangeLengthMode.TangentToEdge);
+ SheetFlangeLengthMode FlangeLengthMode = SheetFlangeLengthMode.TangentToEdge,
+ IReadOnlyList<SheetAttachmentPathIr>? AttachmentPaths = null);
public readonly record struct SheetPoint2(double X, double Y);
diff --git a/Aetheris.SheetMetal/SheetMetalSemanticLayout.cs b/Aetheris.SheetMetal/SheetMetalSemanticLayout.cs
index 4aae2a30..2442f749 100644
--- a/Aetheris.SheetMetal/SheetMetalSemanticLayout.cs
+++ b/Aetheris.SheetMetal/SheetMetalSemanticLayout.cs
@@ -6,6 +6,8 @@ namespace Aetheris.SheetMetal;
public enum SheetMetalSemanticConstraintKind { RequiredMembers, EqualSize, EqualPitch, Mirror }
public sealed record SheetMetalSemanticDatum(string Path,string Region,double X,double Y,string Provenance);
+public sealed record SheetMetalSemanticAttachmentPath(
+ string Path,string Region,string CarrierEdge,double Inset,double Span,double SpanOffset,bool ReleaseToCarrier);
public sealed record SheetMetalSemanticTab(string Path,string Region,string Edge,double Center,double Width,double Extension);
public sealed record SheetMetalSemanticSteppedNotch(
@@ -25,7 +27,8 @@ public sealed record SheetMetalSemanticLayout(
IReadOnlyList<string> Structs,IReadOnlyList<SheetMetalSemanticDatum> Datums,IReadOnlyList<SheetMetalSemanticTab> Tabs,
IReadOnlyList<SheetMetalSemanticPattern> Patterns,IReadOnlyList<SheetMetalSemanticConstraint> Constraints,
IReadOnlyList<SheetMetalSemanticSteppedNotch>? SteppedNotches = null,
- IReadOnlyList<SheetMetalSemanticCornerProfile>? Corners = null)
+ IReadOnlyList<SheetMetalSemanticCornerProfile>? Corners = null,
+ IReadOnlyList<SheetMetalSemanticAttachmentPath>? AttachmentPaths = null)
{
public static SheetMetalSemanticLayout Empty { get; } = new([],[],[],[],[]);
}
@@ -63,6 +66,39 @@ internal static class SheetMetalSemanticLayoutParser
var constraints=new List<SheetMetalSemanticConstraint>();
var regionSizes=RegionSizes(baseSpec,flanges);
+ var attachmentPaths=new List<SheetMetalSemanticAttachmentPath>();
+ foreach(var block in Blocks(source,"AttachmentPath",structs))
+ {
+ var on=TokenPath(block.Body,"On");
+ var owner=on is null?Match.Empty:Regex.Match(on,@"^(?<region>[A-Za-z_][A-Za-z0-9_]*)\.(?<edge>Front|Right|Rear|Left|Outer)$",Rx);
+ if(!owner.Success||!regionSizes.TryGetValue(owner.Groups["region"].Value,out var size))
+ return Fail("sheetmetal-attachment-path-owner",$"AttachmentPath '{block.Name}' requires On: <planar-region>.<physical-edge>.");
+ if(!Scalar(block.Body,"Inset",out var inset)||!Scalar(block.Body,"Span",out var span))
+ return Fail("sheetmetal-attachment-path-properties",$"AttachmentPath '{block.Name}' requires Inset and Span.");
+ Scalar(block.Body,"SpanOffset",out var spanOffset);
+ var edge=owner.Groups["edge"].Value;var carrierLength=edge is "Front" or "Rear"?size.Width:edge is "Right" or "Left"?size.Height:size.Width;
+ var maxInset=edge.Equals("Outer",StringComparison.OrdinalIgnoreCase)?size.Height:edge is "Front" or "Rear"?size.Height:size.Width;
+ if(!double.IsFinite(inset)||inset<0||inset>=maxInset-1e-8)
+ return Fail("sheetmetal-attachment-path-offset",$"AttachmentPath '{block.Name}' Inset must be finite, non-negative, and inside owning region '{owner.Groups["region"].Value}'.");
+ if(!double.IsFinite(span)||span<=0||span>carrierLength+1e-8||Math.Abs(spanOffset)>(carrierLength-span)/2d+1e-8)
+ return Fail("sheetmetal-attachment-path-span",$"AttachmentPath '{block.Name}' Span {span:G9} mm with offset {spanOffset:G9} mm does not fit carrier length {carrierLength:G9} mm.");
+ var release=Token(block.Body,"Release");var releaseToCarrier=release?.Equals("ToCarrier",StringComparison.OrdinalIgnoreCase)==true;
+ if(inset>1e-8&&!releaseToCarrier)
+ return Fail("sheetmetal-attachment-path-release",$"Inset AttachmentPath '{block.Name}' requires `Release: ToCarrier;` so the owner and child do not describe double material.");
+ if(release is not null&&!releaseToCarrier)
+ return Fail("sheetmetal-attachment-path-release",$"AttachmentPath '{block.Name}' uses unsupported Release '{release}'. Supported: ToCarrier.");
+ var region=owner.Groups["region"].Value;
+ var path=$"{region}.{block.Name}";
+ if(attachmentPaths.Any(x=>x.Path.Equals(path,StringComparison.Ordinal)))
+ return Fail("sheetmetal-attachment-path-duplicate",$"Attachment path '{path}' is declared more than once.");
+ attachmentPaths.Add(new(path,region,edge,inset,span,spanOffset,releaseToCarrier));
+ }
+ foreach(var flange in flanges)
+ {
+ var attachment=attachmentPaths.SingleOrDefault(x=>x.Path.Equals($"{flange.ParentRegion}.{flange.EdgeName}",StringComparison.OrdinalIgnoreCase));
+ if(attachment is not null)regionSizes[flange.Name]=(attachment.Span,flange.Length);
+ }
+
foreach(var block in Blocks(source,"Datum",structs))
{
var region=Token(block.Body,"On");
@@ -102,10 +138,12 @@ internal static class SheetMetalSemanticLayoutParser
{
var owner=Regex.Match(block.Name,@"^(?<region>[A-Za-z_][A-Za-z0-9_]*)\.(?<corner>RootStart|RootEnd|OuterStart|OuterEnd)$",Rx);
if(!owner.Success||!regionSizes.ContainsKey(owner.Groups["region"].Value))return Fail("sheetmetal-corner-owner",$"CornerProfile '{Path(block)}' requires <planar-region>.RootStart, .RootEnd, .OuterStart, or .OuterEnd.");
- var operations=Regex.Matches(block.Body,@"\b(?<kind>Chamfer|Cutback|Taper|NotchCorner)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{",Rx).Cast<Match>().ToArray();
- if(operations.Length!=1)return Fail("sheetmetal-corner-operation",$"CornerProfile '{Path(block)}' requires exactly one Chamfer, Cutback, Taper, or NotchCorner operation.");
+ var operations=Regex.Matches(block.Body,@"\b(?<kind>Chamfer|Cutback|Taper|NotchCorner|Round)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{",Rx).Cast<Match>().ToArray();
+ if(operations.Length!=1)return Fail("sheetmetal-corner-operation",$"CornerProfile '{Path(block)}' requires exactly one Chamfer, Cutback, Taper, NotchCorner, or Round operation.");
var operation=operations[0];var open=block.Body.IndexOf('{',operation.Index);var close=Close(block.Body,open);var operationBody=close>open?block.Body[(open+1)..close]:string.Empty;
+ var isRound=operation.Groups["kind"].Value.Equals("Round",StringComparison.OrdinalIgnoreCase);var hasRadius=Scalar(operationBody,"Radius",out var radius);
var hasEqual=Scalar(operationBody,"Setback",out var equal);var hasA=Scalar(operationBody,"SetbackA",out var setbackA);var hasB=Scalar(operationBody,"SetbackB",out var setbackB);
+ if(isRound){hasEqual=hasRadius;equal=radius;}
if(!hasA){setbackA=equal;}if(!hasB){setbackB=equal;}
var cornerPath=Path(block);var operationPath=$"{cornerPath}.{operation.Groups["name"].Value}";
if((!hasEqual&&(!hasA||!hasB))||setbackA<=0||setbackB<=0)return Fail("sheetmetal-corner-setback",$"Corner operation '{operationPath}' requires positive Setback or SetbackA and SetbackB.");
@@ -191,12 +229,12 @@ internal static class SheetMetalSemanticLayoutParser
constraints.Add(new(path,kind,members,"Satisfied",detail));
}
- return new(true,new(structNames,datums.OrderBy(x=>x.Path,StringComparer.Ordinal).ToArray(),tabs.OrderBy(x=>x.Path,StringComparer.Ordinal).ToArray(),patterns.OrderBy(x=>x.Path,StringComparer.Ordinal).ToArray(),constraints.OrderBy(x=>x.Path,StringComparer.Ordinal).ToArray(),steppedNotches.OrderBy(x=>x.Path,StringComparer.Ordinal).ToArray(),corners.OrderBy(x=>x.CornerPath,StringComparer.Ordinal).ToArray()),generated,diagnostics);
+ return new(true,new(structNames,datums.OrderBy(x=>x.Path,StringComparer.Ordinal).ToArray(),tabs.OrderBy(x=>x.Path,StringComparer.Ordinal).ToArray(),patterns.OrderBy(x=>x.Path,StringComparer.Ordinal).ToArray(),constraints.OrderBy(x=>x.Path,StringComparer.Ordinal).ToArray(),steppedNotches.OrderBy(x=>x.Path,StringComparer.Ordinal).ToArray(),corners.OrderBy(x=>x.CornerPath,StringComparer.Ordinal).ToArray(),attachmentPaths.OrderBy(x=>x.Path,StringComparer.Ordinal).ToArray()),generated,diagnostics);
SheetMetalSemanticLayoutParseResult Fail(string code,string message)=>new(false,SheetMetalSemanticLayout.Empty,[],[new(code,SheetMetalDiagnosticSeverity.Error,message)]);
}
- private static IReadOnlyDictionary<string,(double Width,double Height)> RegionSizes(AuthoredSheetBaseSpec baseSpec,IReadOnlyList<AuthoredSheetFlangeSpec> flanges)
+ private static Dictionary<string,(double Width,double Height)> RegionSizes(AuthoredSheetBaseSpec baseSpec,IReadOnlyList<AuthoredSheetFlangeSpec> flanges)
{
var result=new Dictionary<string,(double Width,double Height)>(StringComparer.OrdinalIgnoreCase){{baseSpec.Name,(baseSpec.Width,baseSpec.Depth)}};
var pending=flanges.ToList();var guard=0;
diff --git a/docs/modules/sheet-metal.md b/docs/modules/sheet-metal.md
index a8bdf53b..4c963134 100644
--- a/docs/modules/sheet-metal.md
+++ b/docs/modules/sheet-metal.md
@@ -39,6 +39,31 @@ SheetMetal Tray {
A rectangular authored base exposes `Front`, `Right`, `Rear`, `Left`, and `Center`. A flange exposes `Root`, `Outer`, `Left`, `Right`, `LeftCorner`, `RightCorner`, and `Bend`. `Outer` is `FlangeAttachable`; `Center` is `PointCapable`, so using `Main.Center` in `Flange.From` produces a capability diagnostic rather than a topology-ID failure.
+An `AttachmentPath` is a distinct, bounded feature path owned by a planar
+region. It derives its oriented line from a physical carrier, but may be inset
+and shorter without changing the carrier's `FreeEdge` identity. An inset path
+must explicitly say `Release: ToCarrier;`; lowering then places the two release
+cuts and removes the bounded carrier strip before the ordinary flange/bend
+lowering runs. Full-edge flange syntax remains unchanged.
+
+```firmament
+AttachmentPath ServiceFlangeAttachment {
+ On: Wall.Outer;
+ Inset: 2mm;
+ Span: 40mm;
+ SpanOffset: 5mm;
+ Release: ToCarrier;
+}
+Flange ServiceFlange {
+ From: Wall.ServiceFlangeAttachment;
+ Height: 12mm; Angle: 45deg; Radius: 2mm;
+}
+```
+
+`Round` is an analytic cross-edge profile operation. Its semantic descendant,
+region `PlanarContour2` arc, formed circular edges/cylindrical thickness wall,
+and flat arc retain the same ancestry rather than being replaced by a chord.
+
Formed/flat correspondence uses the same semantic identity: `FrontWall.Bend` maps to `Flat.FrontWall.Bend`; `Main.Front` maps to `Flat.Main.Front`. Inspect the public surface with:
```text
diff --git a/docs/modules/sheetmetal/artifacts/m8/ctc03-final.firmament b/docs/modules/sheetmetal/artifacts/m8/ctc03-final.firmament
index 24426bf6..b0558c1c 100644
--- a/docs/modules/sheetmetal/artifacts/m8/ctc03-final.firmament
+++ b/docs/modules/sheetmetal/artifacts/m8/ctc03-final.firmament
@@ -14,6 +14,16 @@ Concept Ctc03ManufacturedIntent {
}
Concept Struct Ctc03Layout {
+ // The physical RightWall outer carrier and the service bend root are not
+ // coincident. The explicit release removes the bounded strip between them.
+ AttachmentPath ServiceFlangeAttachment {
+ On: RightWall.Outer;
+ Inset: 2.6416mm;
+ Span: 127mm;
+ SpanOffset: 2.3876mm;
+ Release: ToCarrier;
+ }
+
// Named local workpoints isolate measured formed coordinates from feature generation.
Datum RearMountCenter { On: RearMountingFlange; At: (120.65mm, 25.40254mm); }
Datum FrontMountCenter { On: FrontMountingFlange; At: (120.65mm, 24.43226mm); }
@@ -60,6 +70,8 @@ Concept Struct Ctc03Layout {
CornerProfile LeftWall.OuterStart { Chamfer RearEndTaper { Setback: 25.4mm; } }
CornerProfile LeftWall.OuterEnd { Chamfer FrontEndTaper { Setback: 25.4mm; } }
+ CornerProfile RightWall.OuterStart { Round RearEndRound { Radius: 12.7mm; } }
+ CornerProfile RightWall.OuterEnd { Round FrontEndRound { Radius: 12.7mm; } }
CornerProfile FrontMountingFlange.OuterStart { Chamfer RightEndChamfer { Setback: 12.7mm; } }
CornerProfile FrontMountingFlange.OuterEnd { Chamfer LeftEndChamfer { Setback: 12.7mm; } }
@@ -154,9 +166,9 @@ SheetMetal Ctc03 : Ctc03ManufacturedIntent {
Flange FrontWall { From: MainDeck.Front; Height: 61.59254mm; Angle: 90deg; Radius: 6.35mm; Direction: Down; Relief: Auto; }
Flange RearWall { From: MainDeck.Rear; Height: 61.59254mm; Angle: 90deg; Radius: 6.35mm; Direction: Down; Relief: Auto; }
Flange LeftWall { From: MainDeck.Left; Height: 44.45mm; Angle: 90deg; Radius: 6.35mm; Direction: Up; Relief: Auto; }
- Flange RightWall { From: MainDeck.Right; Height: 29.11094mm; Angle: 90deg; Radius: 6.35mm; Direction: Up; Relief: Auto; }
+ Flange RightWall { From: MainDeck.Right; Height: 31.75254mm; Angle: 90deg; Radius: 6.35mm; Direction: Up; Relief: Auto; }
Flange FrontMountingFlange { From: FrontWall.Outer; Length: 43.47972mm; Angle: 90deg; Radius: 6.35mm; Direction: Up; }
Flange RearMountingFlange { From: RearWall.Outer; Length: 44.45mm; Angle: 90deg; Radius: 6.35mm; Direction: Up; }
- Flange AngledServiceFlange { From: RightWall.Outer; Length: 48.514mm; Span: 127mm; SpanOffset: 2.3876mm; Angle: 45deg; Radius: 6.35mm; Direction: Down; }
+ Flange AngledServiceFlange { From: RightWall.ServiceFlangeAttachment; Length: 48.514mm; Angle: 45deg; Radius: 6.35mm; Direction: Down; }
}
diff --git a/docs/modules/sheetmetal/artifacts/m9/README.md b/docs/modules/sheetmetal/artifacts/m9/README.md
new file mode 100644
index 00000000..331f4dac
--- /dev/null
+++ b/docs/modules/sheetmetal/artifacts/m9/README.md
@@ -0,0 +1,59 @@
+# Sheet Metal M9 — attachment paths and analytic profile rounds
+
+## Verdict
+
+**Meaningful progression.** Physical free edges and bounded attachment paths
+are now separate authored/IR concepts, including inset and partial paths,
+explicit release-to-carrier material semantics, ordinary bend/flat lowering,
+stable formed/flat correspondence, inspection paths, validation, and generic
+dogfood. Analytic `Round` corner descendants now survive region, formed BRep,
+flat `PlanarContour2`, and STEP-capable geometry.
+
+CTC-03 is not complete. Its service bend now uses
+`RightWall.ServiceFlangeAttachment` at the source axis while `RightWall.Outer`
+is 2.6416 mm farther out. Both R12.7 wall-end rounds are analytic. The remaining
+right-wall mismatch is the two source-specific 15.24 x 15.24 diagonal entries
+and adjacent 63.5 mm deep-recess runs around the shallow service release. The
+current generic release produces vertical release cuts directly from the outer
+carrier. Encoding the missing compound approach profile as unrelated raw
+coordinates would be brittle, so this milestone does not claim completion.
+
+## Measured CTC comparison
+
+Recovery-M2 baseline to M9 native flat:
+
+| direction | baseline RMS / p95 / max (mm) | M9 RMS / p95 / max (mm) |
+|---|---:|---:|
+| source to native | 4.413550 / 9.554765 / 17.448908 | 4.310304 / 9.554765 / 19.478294 |
+| native to source | 3.769455 / 8.898990 / 14.341517 | 3.452142 / 8.315259 / 17.168461 |
+
+Width/height residual remains 0.002447/0.007820 mm; 17 openings and seven bend
+lines remain present. The worse maximum is localized evidence that the compound
+right-wall approach profile is still absent, not grounds to call the part done.
+
+Recovery-M2 formed baseline to M9:
+
+| direction | baseline RMS / p95 / max (mm) | M9 RMS / p95 / max (mm) |
+|---|---:|---:|
+| source to native | 8.500190 / 12.478269 / 52.816066 | 7.636925 / 9.141310 / 49.263886 |
+| native to source | 3.607855 / 8.940881 / 12.735724 | 2.865211 / 8.940881 / 12.735724 |
+
+All seven bend comparisons and all 17 opening comparisons pass. The service
+bend axis residual is 0.00254 mm and service-hole center residuals are at most
+0.000527 mm. Construction remains source-independent.
+
+## Architecture
+
+```text
+SheetRegionIr
+ +- physical Boundary3D / ExactContour
+ +- SheetAttachmentPathIr[]
+ +- carrier identity, owner, start/end, tangent
+ +- in-plane/region normals, inset, span offset
+ +- FlangeAttachable/BendAttachable/FeatureAttachable
+ +- ordinary SheetBendIr and child SheetRegionIr
+```
+
+Known debt: the regex-backed dialect pre-scans attachment declarations for
+capability admission before the semantic layout pass. It is localized and
+deterministic, but should eventually become one typed parser pass.
diff --git a/fixtures/FirmamentV2/SheetMetal/m9-inset-partial-flange.firmament b/fixtures/FirmamentV2/SheetMetal/m9-inset-partial-flange.firmament
new file mode 100644
index 00000000..a5c37033
--- /dev/null
+++ b/fixtures/FirmamentV2/SheetMetal/m9-inset-partial-flange.firmament
@@ -0,0 +1,22 @@
+// Generic M9 dogfood: a bounded bend path is feature intent, not a free edge.
+SheetMetal InsetPartialFlange {
+ Thickness: 1mm;
+ KFactor: 0.5;
+ Base Panel { Profile: Rectangle { Width: 100mm; Height: 60mm; }; }
+ Flange Wall { From: Panel.Rear; Height: 20mm; Angle: 90deg; Radius: 2mm; }
+
+ AttachmentPath ServiceFlangeAttachment {
+ On: Wall.Outer;
+ Inset: 2mm;
+ Span: 40mm;
+ SpanOffset: 5mm;
+ Release: ToCarrier;
+ }
+
+ Flange ServiceFlange {
+ From: Wall.ServiceFlangeAttachment;
+ Height: 12mm;
+ Angle: 45deg;
+ Radius: 2mm;
+ }
+}