Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add profile modification templates and semantic delta support
Yuechen Li1da512373bc9
diff --git a/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj b/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csprojindex aaba8dc1..de4ea54f 100644--- a/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj+++ b/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj@@ -18,5 +18,6 @@<ItemGroup><EmbeddedResource Include="Resources\Inter-Regular.ttf" LogicalName="Aetheris.Drawing.Inter.ttf" />+ <EmbeddedResource Include="Resources\ProfileModifications.firmament" /></ItemGroup></Project>diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.csindex c4d8ca99..5fe2f0ac 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs@@ -301,6 +301,8 @@ public static class FirmamentV2ParserFirmamentV2ForgeConceptCatalog? conceptCatalog){ArgumentNullException.ThrowIfNull(sourceText);+ if(Regex.IsMatch(sourceText,@"\bUse\s+Profile\.Modifications\s*;",RegexOptions.CultureInvariant))+ sourceText=ProfileModificationTemplateLibrary.Source+Environment.NewLine+Regex.Replace(sourceText,@"\bUse\s+Profile\.Modifications\s*;",string.Empty,RegexOptions.CultureInvariant);var diagnostics = new List<string> { "firmament-v2-parser-invoked" };var source = StripLineComments(sourceText);var v2AdmissionCandidate = IsV2AdmissionCandidate(source);@@ -900,7 +902,7 @@ public static class FirmamentV2Parservar known = new HashSet<string>(StringComparer.Ordinal){"Box", "Cylinder", "RoundedBox", "Frustum", "StandardPart", "ExactCoaxialPart", "Concept", "Struct", "Construction", "Profile", "Compose", "EdgeFinish",- "Record", "Static", "Template", "Selection", "InlineStep", "Recognize", "Replace", "Pmi", "Modify", "Match", "Require", "Assert"+ "Record", "Static", "Template", "ProfileDelta", "Selection", "InlineStep", "Recognize", "Replace", "Pmi", "Modify", "Match", "Require", "Assert"};var compatibilityOnly = new HashSet<string>(StringComparer.Ordinal){diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.csindex 33a7830c..315d5549 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs@@ -253,7 +253,7 @@ internal static class FirmamentV2TemplateExpansionforeach (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|SheetMetal)\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|ProfileDelta)\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 FirmamentV2TemplateExpansionprivate 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|SheetMetal)\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|ProfileDelta)\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, '<', '>');@@ -399,13 +399,14 @@ internal static class FirmamentV2TemplateExpansion"Version" => Regex.IsMatch(value, @"^(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)$", RegexOptions.CultureInvariant),"Date" => DateOnly.TryParseExact(value, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out _),"ImportedStep" => Regex.IsMatch(value, @"^\$[A-Za-z_][A-Za-z0-9_]*$", RegexOptions.CultureInvariant),+ "ProfilePath" => Regex.IsMatch(value, @"^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)+$", RegexOptions.CultureInvariant),"int" => long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out _), "float" => double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out _), "bool" => value is "true" or "false",_ when enums.TryGetValue(type, out var variants) => variants.Contains(value),_ when recordTypes?.ContainsKey(type) == true && staticRecords?.TryGetValue(value, out var record) == true => record.TypeName == type,_ => false};private static bool IsBuiltInValueType(string type, IReadOnlyDictionary<string, ImmutableHashSet<string>> enums) =>- type is "Length" or "Angle" or "String" or "Version" or "Date" or "ImportedStep" or "int" or "float" or "bool" || enums.ContainsKey(type);+ type is "Length" or "Angle" or "String" or "Version" or "Date" or "ImportedStep" or "ProfilePath" or "int" or "float" or "bool" || enums.ContainsKey(type);private static IReadOnlyDictionary<string, TemplateRecordTypeIr> ParseRecordTypes(string source, List<string> diagnostics){diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.csindex 39e426aa..528001f1 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs@@ -184,12 +184,15 @@ public static class ProfileAuthoringParserprivate static void BindRectEdgeProfiles(string source, Dictionary<string, BoundPath> result, List<string> diagnostics){var programs = FindBlocks(source, @"\bEdgeProfile\s+(?<owner>[A-Za-z_]\w*)\.(?<edge>[A-Za-z_]\w*)\s*\{").ToArray();+ var parsedDeltas=SemanticProfileDeltaParser.Parse(source);+ diagnostics.AddRange(parsedDeltas.Diagnostics);var cornerPrograms = FindBlocks(source, @"\bCornerProfile\s+(?<owner>[A-Za-z_]\w*)\.(?<corner>[A-Za-z_]\w*)\s*\{").ToArray();foreach (Match rectangle in Rect.Matches(source)){var name = rectangle.Groups["n"].Value;var isProfileSource = Regex.IsMatch(source, $@"\bProfile\s+[A-Za-z_]\w*\s+From\s+{Regex.Escape(name)}\b", RegexOptions.CultureInvariant);- if (!isProfileSource && !programs.Any(x => x.Match.Groups["owner"].Value == name) && !cornerPrograms.Any(x => x.Match.Groups["owner"].Value == name)) continue;+ if (!isProfileSource && !programs.Any(x => x.Match.Groups["owner"].Value == name) && !cornerPrograms.Any(x => x.Match.Groups["owner"].Value == name)+ &&!parsedDeltas.Deltas.Any(delta=>delta.OwnerPath.StartsWith(name+".",StringComparison.Ordinal))) continue;if (!TryNumber(rectangle.Groups["w"].Value, out var width) || !TryNumber(rectangle.Groups["h"].Value, out var height) ||!TryNumber(rectangle.Groups["x"].Value, out var cx) || !TryNumber(rectangle.Groups["y"].Value, out var cy)) continue;if (result.ContainsKey(name)) { diagnostics.Add($"profile-edge-owner-name-collision:{name}"); continue; }@@ -244,13 +247,21 @@ public static class ProfileAuthoringParservar endCorner = cornerEdges.First(x => x.Value.EdgeA == edge).Key;resolvedCorners.TryGetValue(startCorner, out var startResolution);resolvedCorners.TryGetValue(endCorner, out var endResolution);- if (matching.Length == 0 && startResolution is null && endResolution is null)+ var edgeDeltas=parsedDeltas.Deltas.Where(delta=>delta.OwnerPath.Equals($"{name}.{edge}",StringComparison.Ordinal)).ToArray();+ if (matching.Length == 0 && edgeDeltas.Length==0 && startResolution is null && endResolution is null){path.Steps.Add(new(edge, "Span", $"{name}.{edge}", $"{name}.{edge}.End", [new LineArcLineSegment2D(start, end)], start, end, Heading(start, end)));return;}if (matching.Length > 1) { diagnostics.Add($"semantic-edge-duplicate-program:{name}.{edge}"); return; }var fragments = new List<SemanticEdgeFragmentIr>();+ foreach(var parsed in edgeDeltas)+ {+ var id=$"{name}.{edge}.{parsed.Delta.Name}";+ fragments.Add(parsed.Delta with { StableId=id,Side=-parsed.Delta.Side,+ Levels=parsed.Delta.Levels.Select(level=>level with { StableId=$"{id}.{level.Name}" }).ToArray(),+ Members=parsed.Delta.Members.Select(member=>member with { StableId=$"{id}.{member.Name}",ExposeAs=member.ExposeAs is null?null:$"{id}.{member.ExposeAs.Split('.').Last()}" }).ToArray() });+ }foreach (var step in matching.Length == 0 ? Enumerable.Empty<PathStep>() : FindPathSteps(matching[0].Body).Where(x => x.Kind is "Chamfer" or "Step" or "Notch" or "Cutback" or "Tab")){var id = $"{name}.{edge}.{step.Name}";@@ -275,6 +286,15 @@ public static class ProfileAuthoringParserif (!resolution.IsSuccess) { diagnostics.AddRange(resolution.Diagnostics); return; }foreach (var member in resolution.Profile!.OrderedMembers){+ if(member.Kind=="ProfileDelta")+ {+ foreach(var descendant in member.CurveDescendants)+ {+ var curveStart=Start(descendant.Geometry);var curveEnd=End(descendant.Geometry);var leaf=descendant.StableId.EndsWith(".curve00",StringComparison.Ordinal)?descendant.StableId[..^8]:descendant.StableId;+ path.Steps.Add(new($"{edge}.{leaf}","ProfileDeltaMember",leaf,$"{leaf}.End",[descendant.Geometry],curveStart,curveEnd,Heading(curveStart,curveEnd)));+ }+ continue;+ }var first = ((LineArcLineSegment2D)member.CurveDescendants.First().Geometry).Start; var last = ((LineArcLineSegment2D)member.CurveDescendants.Last().Geometry).End;path.Steps.Add(new($"{edge}.{member.Name}", member.Kind, $"{name}.{edge}.{member.Name}", $"{name}.{edge}.{member.Name}.End", member.CurveDescendants.Select(x => x.Geometry).ToArray(), first, last, Heading(first, last)));}@@ -511,6 +531,8 @@ public static class ProfileAuthoringParserprivate static double DegreesToRadians(double value) => value * Math.PI / 180d;private static double Heading((double X, double Y) from, (double X, double Y) to) => Math.Atan2(to.Y - from.Y, to.X - from.X) * 180d / Math.PI;private static double Distance((double X, double Y) a, (double X, double Y) b) => Math.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y));+ private static (double X,double Y) Start(LineArcProfileCurve2D curve)=>curve switch{LineArcLineSegment2D line=>line.Start,LineArcCircularArc2D arc=>(arc.Center.X+arc.Radius*Math.Cos(arc.StartAngleRadians),arc.Center.Y+arc.Radius*Math.Sin(arc.StartAngleRadians)),_=>throw new InvalidOperationException()};+ 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()};private static bool OnLine((double X, double Y) point, LineArcLineSegment2D line) => Math.Abs((line.End.X - line.Start.X) * (point.Y - line.Start.Y) - (line.End.Y - line.Start.Y) * (point.X - line.Start.X)) < 1e-7;private static bool OnCircle((double X, double Y) point, (double X, double Y) center, double radius) => Math.Abs(Distance(point, center) - radius) < 1e-7;diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileModificationTemplateLibrary.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileModificationTemplateLibrary.csnew file mode 100644index 00000000..449ec6b9--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileModificationTemplateLibrary.cs@@ -0,0 +1,17 @@+using System.Reflection;++namespace Aetheris.Kernel.Firmament.FirmamentV2;++public static class ProfileModificationTemplateLibrary+{+ private const string ResourceName="Aetheris.Kernel.Firmament.Resources.ProfileModifications.firmament";+ public static string Source+ {+ get+ {+ using var stream=typeof(ProfileModificationTemplateLibrary).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.Kernel.Firmament/FirmamentV2/SemanticEdgeProfileIr.cs b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticEdgeProfileIr.csindex d788a564..05eb7f9f 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/SemanticEdgeProfileIr.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticEdgeProfileIr.cs@@ -28,6 +28,36 @@ public sealed record SemanticEdgeSteppedNotchIr(double ShoulderDepth, double OuterChamfer, double InnerChamfer, int Side, string SourceSpan): SemanticEdgeFragmentIr(Name, StableId, "SteppedNotch", Anchor, Width, Depth, Side, SourceSpan);+public enum SemanticProfileDeltaMemberKind { Span, Diagonal, Step, Round }++/// <summary>A named offset in the local frame of a profile carrier.</summary>+public sealed record SemanticProfileDeltaLevelIr(string Name, string StableId, double Offset, string SourceSpan);++/// <summary>+/// One semantic move in a profile-delta program. Run is measured along the carrier;+/// Step permits a zero run, while Span must remain on the current level and Diagonal+/// moves to ToLevel over a positive run. ExposeAs creates a stable nested concept path.+/// </summary>+public sealed record SemanticProfileDeltaMemberIr(+ string Name, string StableId, SemanticProfileDeltaMemberKind Kind, double Run,+ string ToLevel, string? ExposeAs, IReadOnlyList<string> Capabilities, string SourceSpan,+ double? Radius = null, bool Concave = false);++/// <summary>+/// A bounded, baseline-returning profile modification program. This is deliberately+/// generic: user libraries name features through ordinary Firmament templates, while+/// the kernel only understands levels and finite span/transition primitives.+/// </summary>+public sealed record SemanticProfileDeltaIr(+ string Name, string StableId, SemanticEdgeAnchorIr Anchor, int Side,+ IReadOnlyList<SemanticProfileDeltaLevelIr> Levels,+ IReadOnlyList<SemanticProfileDeltaMemberIr> Members, string SourceSpan)+ : SemanticEdgeFragmentIr(+ Name, StableId, "ProfileDelta", Anchor,+ Members.Sum(member => member.Run),+ Levels.Count == 0 ? 0d : Levels.Max(level => Math.Abs(level.Offset)),+ Side, SourceSpan);+/// <summary>Semantic modification program for one directed, named carrier edge.</summary>public sealed record SemanticEdgeProfileIr(string OwnerPath, string StableId, SemanticProfilePoint Start, SemanticProfilePoint End,@@ -92,6 +122,11 @@ public static class SemanticEdgeProfileResolver!double.IsFinite(stepped.OuterChamfer) || stepped.OuterChamfer < -Tolerance || !double.IsFinite(stepped.InnerChamfer) || stepped.InnerChamfer <= Tolerance ||2d * (stepped.OuterChamfer + stepped.InnerChamfer) >= stepped.Width - Tolerance || stepped.ShoulderDepth + Tolerance < stepped.OuterChamfer)){ diagnostics.Add($"semantic-edge-invalid-stepped-notch:{fragment.StableId}"); continue; }+ if (fragment is SemanticProfileDeltaIr delta)+ {+ ValidateDelta(delta, diagnostics);+ if (diagnostics.Count > 0) continue;+ }if (!double.IsFinite(fragment.Anchor.Offset)) { diagnostics.Add($"semantic-edge-invalid-anchor:{fragment.StableId}"); continue; }var start = fragment.Anchor.Kind switch{@@ -138,6 +173,13 @@ public static class SemanticEdgeProfileResolverResolvedSemanticEdgeMemberIr Fragment(SemanticEdgeFragmentIr f, double a, double b){+ if(f is SemanticProfileDeltaIr delta)+ {+ var deltaCurves=ProfileDelta(delta,a);+ var descendants=delta.Members.Select((member,index)=>new ResolvedSemanticProfileCurveIr(+ $"{member.StableId}.curve00",0,deltaCurves[index],$"lowered-from:{member.StableId};profile-delta:{delta.StableId}" )).ToArray();+ return new(delta.Name,delta.StableId,delta.Kind,a,b,descendants,delta.SourceSpan,false);+ }var v = f.Side * f.Depth;IReadOnlyList<LineArcProfileCurve2D> curves = f switch{@@ -150,6 +192,17 @@ public static class SemanticEdgeProfileResolver};return Member(f.Name, f.StableId, f.Kind, a, b, curves, f.SourceSpan, false);}+ IReadOnlyList<LineArcProfileCurve2D> ProfileDelta(SemanticProfileDeltaIr delta, double a)+ {+ var levels=delta.Levels.ToDictionary(level=>level.Name,level=>delta.Side*level.Offset,StringComparer.Ordinal);+ var curves=new List<LineArcProfileCurve2D>();var u=a;var v=0d;+ foreach(var member in delta.Members)+ {+ var target=levels[member.ToLevel];var next=u+member.Run;+ curves.Add(member.Kind==SemanticProfileDeltaMemberKind.Round?Round(u,v,next,target,member.Radius!.Value,member.Concave?-1d:1d):Line(u,v,next,target));u=next;v=target;+ }+ return curves;+ }IReadOnlyList<LineArcProfileCurve2D> SteppedNotch(SemanticEdgeSteppedNotchIr f, double a, double b){var side = f.Side; var points = new List<(double U, double V)> { (a, 0) };@@ -165,6 +218,48 @@ public static class SemanticEdgeProfileResolverResolvedSemanticEdgeMemberIr Member(string name, string id, string kind, double a, double b, IReadOnlyList<LineArcProfileCurve2D> curves, string span, bool generated) =>new(name, id, kind, a, b, curves.Select((curve, ordinal) => new ResolvedSemanticProfileCurveIr($"{id}.curve{ordinal:D2}", ordinal, curve, generated ? $"generated-carrier:{source.OwnerPath}" : $"lowered-from:{id}")).ToArray(), span, generated);LineArcLineSegment2D Line(double u0, double v0, double u1, double v1) => new(ToWorld(u0, v0), ToWorld(u1, v1));+ LineArcCircularArc2D Round(double u0,double v0,double u1,double v1,double radius,double centerSide)+ {+ var du=u1-u0;var dv=v1-v0;var chord=Math.Sqrt(du*du+dv*dv);var h=Math.Sqrt(Math.Max(0,radius*radius-chord*chord/4d));+ var cu=(u0+u1)/2d+centerSide*(-dv/chord*h);var cv=(v0+v1)/2d+centerSide*(du/chord*h);var center=ToWorld(cu,cv);+ var start=Math.Atan2(v0-cv,u0-cu);var end=Math.Atan2(v1-cv,u1-cu);var sweep=end-start;while(sweep<=0)sweep+=2*Math.PI;if(sweep>Math.PI)sweep-=2*Math.PI;+ return new(center,radius,start+Math.Atan2(ty,tx),sweep);+ }(double X, double Y) ToWorld(double u, double v) => (source.Start.X + tx * u + nx * v, source.Start.Y + ty * u + ny * v);}++ private static void ValidateDelta(SemanticProfileDeltaIr delta,List<string> diagnostics)+ {+ var levelNames=new HashSet<string>(StringComparer.Ordinal);+ foreach(var level in delta.Levels)+ {+ if(!levelNames.Add(level.Name))diagnostics.Add($"semantic-profile-delta-duplicate-level:{delta.StableId}:{level.Name}");+ if(!double.IsFinite(level.Offset)||level.Offset<0)diagnostics.Add($"semantic-profile-delta-invalid-level:{level.StableId}");+ }+ var memberIds=new HashSet<string>(StringComparer.Ordinal);var exposed=new HashSet<string>(StringComparer.Ordinal);var current=0d;+ foreach(var member in delta.Members)+ {+ if(!memberIds.Add(member.StableId))diagnostics.Add($"semantic-profile-delta-duplicate-member:{member.StableId}");+ if(!levelNames.Contains(member.ToLevel))diagnostics.Add($"semantic-profile-delta-unknown-level:{member.StableId}:{member.ToLevel}");+ if(!double.IsFinite(member.Run)||member.Run<0||(member.Kind is not SemanticProfileDeltaMemberKind.Step&&member.Run<=Tolerance))+ diagnostics.Add($"semantic-profile-delta-invalid-run:{member.StableId}:{member.Run:R}");+ var target=delta.Levels.FirstOrDefault(level=>level.Name==member.ToLevel)?.Offset??double.NaN;+ if(member.Kind==SemanticProfileDeltaMemberKind.Span&&Math.Abs(target-current)>Tolerance)+ diagnostics.Add($"semantic-profile-delta-span-changes-level:{member.StableId}:{current:R}:{target:R}");+ if(member.Kind==SemanticProfileDeltaMemberKind.Diagonal&&Math.Abs(target-current)<=Tolerance)+ diagnostics.Add($"semantic-profile-delta-diagonal-same-level:{member.StableId}:{member.ToLevel}");+ if(member.Kind==SemanticProfileDeltaMemberKind.Step&&(member.Run>Tolerance||Math.Abs(target-current)<=Tolerance))+ diagnostics.Add($"semantic-profile-delta-invalid-step:{member.StableId}");+ if(member.Kind==SemanticProfileDeltaMemberKind.Round)+ {+ var chord=Math.Sqrt(member.Run*member.Run+(target-current)*(target-current));+ if(member.Radius is not { } radius||!double.IsFinite(radius)||radius<chord/2d-Tolerance)+ diagnostics.Add($"semantic-profile-delta-invalid-round:{member.StableId}:radius={member.Radius?.ToString("R")??"<missing>"}:chord={chord:R}");+ }+ if(member.ExposeAs is { Length:>0 } path&&!exposed.Add(path))diagnostics.Add($"semantic-profile-delta-duplicate-exposure:{delta.StableId}:{path}");+ current=target;+ }+ if(delta.Members.Count==0)diagnostics.Add($"semantic-profile-delta-empty:{delta.StableId}");+ if(Math.Abs(current)>Tolerance)diagnostics.Add($"semantic-profile-delta-open:{delta.StableId}:terminal-level={current:R}");+ }}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/SemanticProfileDeltaParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticProfileDeltaParser.csnew file mode 100644index 00000000..5899dc78--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticProfileDeltaParser.cs@@ -0,0 +1,98 @@+using System.Globalization;+using System.Text.RegularExpressions;++namespace Aetheris.Kernel.Firmament.FirmamentV2;++public sealed record ParsedSemanticProfileDelta(+ string OwnerPath,SemanticProfileDeltaIr Delta,+ IReadOnlyList<SemanticProfileDeltaExposure> Exposures);++public sealed record SemanticProfileDeltaExposure(+ string Path,string MemberPath,double StartU,double EndU,double Offset,+ IReadOnlyList<string> Capabilities);++public sealed record SemanticProfileDeltaParseResult(+ IReadOnlyList<ParsedSemanticProfileDelta> Deltas,IReadOnlyList<string> Diagnostics)+{+ public bool IsSuccess=>Diagnostics.Count==0;+}++/// <summary>Parser for the finite, template-friendly ProfileDelta semantic substrate.</summary>+public static class SemanticProfileDeltaParser+{+ private const RegexOptions Rx=RegexOptions.CultureInvariant|RegexOptions.Singleline;+ private const string Number=@"[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)";++ public static SemanticProfileDeltaParseResult Parse(string source)+ {+ var result=new List<ParsedSemanticProfileDelta>();var diagnostics=new List<string>();+ foreach(var block in Blocks(source,"ProfileDelta"))+ {+ var id=block.Name;var on=TokenPath(block.Body,"On");+ var anchorText=Field(block.Body,"Anchor");var sideText=Token(block.Body,"Side");+ if(on is null||anchorText is null||!TryAnchor(anchorText,out var anchor)||sideText is not ("Inward" or "Outward"))+ {diagnostics.Add($"semantic-profile-delta-header-invalid:{id}:requires On, Anchor, and Side");continue;}+ var side=sideText=="Outward"?1:-1;+ var levels=new List<SemanticProfileDeltaLevelIr>();+ foreach(var level in Blocks(block.Body,"Level"))+ {+ if(!Length(level.Body,"Offset",out var offset)||offset<0)+ {diagnostics.Add($"semantic-profile-delta-level-invalid:{id}.{level.Name}");continue;}+ levels.Add(new(level.Name,$"{id}.{level.Name}",offset,$"ProfileDelta {id}.Level {level.Name}"));+ }+ var members=new List<(int Index,SemanticProfileDeltaMemberIr Member)>();+ foreach(var member in Blocks(block.Body,"Span"))+ {+ if(!Length(member.Body,"Run",out var run)||Token(member.Body,"At") is not { } at)+ {diagnostics.Add($"semantic-profile-delta-span-invalid:{id}.{member.Name}");continue;}+ var expose=Token(member.Body,"Expose");var capabilities=List(member.Body,"Capabilities");+ if(expose is not null&&capabilities.Count==0)capabilities=["StableSemanticIdentity"];+ members.Add((member.Index,new(member.Name,$"{id}.{member.Name}",SemanticProfileDeltaMemberKind.Span,run,at,+ expose is null?null:$"{id}.{expose}",capabilities,$"ProfileDelta {id}.Span {member.Name}")));+ }+ foreach(var member in Blocks(block.Body,"Transition"))+ {+ var kindText=Token(member.Body,"Kind");var to=Token(member.Body,"To");+ var kind=kindText=="Diagonal"?SemanticProfileDeltaMemberKind.Diagonal:kindText=="Step"?SemanticProfileDeltaMemberKind.Step:kindText=="Round"?SemanticProfileDeltaMemberKind.Round:(SemanticProfileDeltaMemberKind?)null;+ var hasRun=Length(member.Body,"Run",out var run);+ var hasRadius=Length(member.Body,"Radius",out var radius);+ var concave=string.Equals(Token(member.Body,"Concave"),"true",StringComparison.OrdinalIgnoreCase);+ if(kind is null||to is null||(kind is SemanticProfileDeltaMemberKind.Diagonal or SemanticProfileDeltaMemberKind.Round&&!hasRun)||(kind==SemanticProfileDeltaMemberKind.Step&&hasRun&&Math.Abs(run)>1e-9)||(kind==SemanticProfileDeltaMemberKind.Round&&!hasRadius))+ {diagnostics.Add($"semantic-profile-delta-transition-invalid:{id}.{member.Name}");continue;}+ members.Add((member.Index,new(member.Name,$"{id}.{member.Name}",kind.Value,kind==SemanticProfileDeltaMemberKind.Step?0:run,to,null,[],+ $"ProfileDelta {id}.Transition {member.Name}",kind==SemanticProfileDeltaMemberKind.Round?radius:null,concave)));+ }+ var ordered=members.OrderBy(x=>x.Index).Select(x=>x.Member).ToArray();+ var delta=new SemanticProfileDeltaIr(id,id,anchor,side,levels,ordered,$"ProfileDelta {id}");+ var exposures=new List<SemanticProfileDeltaExposure>();var cursor=0d;var current=0d;+ var byLevel=levels.ToDictionary(x=>x.Name,x=>x.Offset,StringComparer.Ordinal);+ foreach(var member in ordered)+ {+ var start=cursor;cursor+=member.Run;if(byLevel.TryGetValue(member.ToLevel,out var target))current=target;+ if(member.ExposeAs is not null)exposures.Add(new(member.ExposeAs,member.StableId,start,cursor,side*current,member.Capabilities));+ }+ result.Add(new(on,delta,exposures));+ }+ return new(result,diagnostics);+ }++ private static bool TryAnchor(string text,out SemanticEdgeAnchorIr anchor)+ {+ var match=Regex.Match(text,$@"^(?<kind>FromStart|FromEnd|CenteredAt)\s+(?<v>{Number})mm$",Rx);+ anchor=new(SemanticEdgeAnchorKind.FromStart,0);if(!match.Success)return false;+ anchor=new(Enum.Parse<SemanticEdgeAnchorKind>(match.Groups["kind"].Value),double.Parse(match.Groups["v"].Value,CultureInfo.InvariantCulture));return true;+ }+ private static bool Length(string body,string name,out double value)+ {var m=Regex.Match(body,$@"\b{Regex.Escape(name)}\s*:\s*(?<v>{Number})mm\s*;",Rx);value=m.Success?double.Parse(m.Groups["v"].Value,CultureInfo.InvariantCulture):0;return m.Success&&double.IsFinite(value);}+ private static string? Field(string body,string name){var m=Regex.Match(body,$@"\b{Regex.Escape(name)}\s*:\s*(?<v>[^;]+)\s*;",Rx);return m.Success?m.Groups["v"].Value.Trim():null;}+ private static string? Token(string body,string name){var m=Regex.Match(body,$@"\b{Regex.Escape(name)}\s*:\s*(?<v>[A-Za-z_]\w*)\s*;",Rx);return m.Success?m.Groups["v"].Value:null;}+ private static string? TokenPath(string body,string name){var m=Regex.Match(body,$@"\b{Regex.Escape(name)}\s*:\s*(?<v>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)\s*;",Rx);return m.Success?m.Groups["v"].Value:null;}+ private static IReadOnlyList<string> List(string body,string name){var m=Regex.Match(body,$@"\b{Regex.Escape(name)}\s*:\s*\[(?<v>[^]]*)\]\s*;",Rx);return m.Success?m.Groups["v"].Value.Split(',',StringSplitOptions.RemoveEmptyEntries|StringSplitOptions.TrimEntries):[];}+ private static IReadOnlyList<Block> Blocks(string source,string keyword)+ {+ var result=new List<Block>();foreach(Match match in Regex.Matches(source,$@"\b{Regex.Escape(keyword)}\s+(?<name>[A-Za-z_]\w*)\s*\{{",Rx))+ {var open=source.IndexOf('{',match.Index);var close=Close(source,open);if(close>open)result.Add(new(match.Groups["name"].Value,source[(open+1)..close],match.Index));}return result;+ }+ private static int Close(string source,int open){var depth=0;for(var i=open;i<source.Length;i++){if(source[i]=='{')depth++;else if(source[i]=='}'&&--depth==0)return i;}return -1;}+ private sealed record Block(string Name,string Body,int Index);+}diff --git a/Aetheris.Kernel.Firmament/Resources/ProfileModifications.firmament b/Aetheris.Kernel.Firmament/Resources/ProfileModifications.firmamentnew file mode 100644index 00000000..74f6e18c--- /dev/null+++ b/Aetheris.Kernel.Firmament/Resources/ProfileModifications.firmament@@ -0,0 +1,41 @@+// Generic profile-modification standard library. User feature names are ordinary+// ProfileDelta template specializations; the compiler knows only semantic primitives.+Record ProfileRecessSpec {+ Center: Length+ Lead: Length+ Run: Length+ Depth: Length+ Land: Length+}++Template < P: ProfileRecessSpec, Owner: ProfilePath >+ProfileDelta Recess {+ On: Owner;+ Anchor: CenteredAt P.Center;+ Side: Inward;+ Level Carrier { Offset: 0mm; }+ Level Recessed { Offset: P.Depth; }+ Transition LeadIn { Kind: Diagonal; Run: P.Lead; To: Recessed; }+ Span LeftRun { Run: P.Run; At: Recessed; }+ Span Land { Run: P.Land; At: Recessed; }+ Span RightRun { Run: P.Run; At: Recessed; }+ Transition LeadOut { Kind: Diagonal; Run: P.Lead; To: Carrier; }+}++Record ProfileTabSpec {+ Center: Length+ Width: Length+ Extension: Length+}++Template < P: ProfileTabSpec, Owner: ProfilePath >+ProfileDelta Tab {+ On: Owner;+ Anchor: CenteredAt P.Center;+ Side: Outward;+ Level Carrier { Offset: 0mm; }+ Level Extended { Offset: P.Extension; }+ Transition Enter { Kind: Step; To: Extended; }+ Span Crown { Run: P.Width; At: Extended; }+ Transition Exit { Kind: Step; To: Carrier; }+}diff --git a/Aetheris.SheetMetal.Tests/SheetMetalM10Tests.cs b/Aetheris.SheetMetal.Tests/SheetMetalM10Tests.csnew file mode 100644index 00000000..40498696--- /dev/null+++ b/Aetheris.SheetMetal.Tests/SheetMetalM10Tests.cs@@ -0,0 +1,174 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Firmament.Materializer;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Xunit;++namespace Aetheris.SheetMetal.Tests;++public sealed class SheetMetalM10Tests+{+ private const string Library="""+Record RecessSpec {+ Center: Length+ Lead: Length+ Run: Length+ Depth: Length+ AttachmentInset: Length+ AttachmentSpan: Length+}++Template < P: RecessSpec, Owner: ProfilePath >+ProfileDelta Recess {+ On: Owner;+ Anchor: CenteredAt P.Center;+ Side: Inward;+ Level Carrier { Offset: 0mm; }+ Level Deep { Offset: P.Depth; }+ Level Attachment { Offset: P.AttachmentInset; }+ Transition LeadIn { Kind: Diagonal; Run: P.Lead; To: Deep; }+ Span LeftRun { Run: P.Run; At: Deep; }+ Transition RiseToAttachment { Kind: Step; To: Attachment; }+ Span AttachmentLand { Run: P.AttachmentSpan; At: Attachment; Expose: ServiceFlangeAttachment; Capabilities: [FlangeAttachable, BendAttachable, FeatureAttachable, StableSemanticIdentity]; }+ Transition FallFromAttachment { Kind: Step; To: Deep; }+ Span RightRun { Run: P.Run; At: Deep; }+ Transition LeadOut { Kind: Diagonal; Run: P.Lead; To: Carrier; }+}+""";++ [Fact]+ public void Unknown_user_named_template_feature_materializes_on_ordinary_extrusion()+ {+ var source=Library+"""+Static Chosen: RecessSpec = RecessSpec {+ Center: 50mm; Lead: 5mm; Run: 8mm; Depth: 6mm; AttachmentInset: 2mm; AttachmentSpan: 20mm;+}+Rect2 PlateBase { Center: [50mm, 20mm]; Size: [100mm, 40mm]; }+ProfileDelta AlienRabbet = Recess < P: Chosen, Owner: PlateBase.Bottom >+Profile Plate From PlateBase+Extrude Solid { Profile: Plate; From: 0mm; To: 3mm; }+""";+ var expanded=FirmamentTemplateSourceCompiler.Expand(source,out var expansionDiagnostics);+ Assert.NotNull(expanded);Assert.Empty(expansionDiagnostics);+ Assert.DoesNotContain("Recess <",expanded!.ExpandedSource,StringComparison.Ordinal);+ var parsed=ProfileAuthoringParser.Parse(expanded.ExpandedSource);+ Assert.Empty(parsed.Diagnostics);Assert.NotNull(parsed.Profile);+ var outer=Assert.Single(parsed.Profile!.Loops);+ Assert.Contains(outer.Segments,segment=>segment.Name.Contains("AlienRabbet",StringComparison.Ordinal));+ Assert.Contains(outer.Segments,segment=>segment.Provenance.ConceptStableId.Contains("AttachmentLand",StringComparison.Ordinal));+ }++ [Fact]+ public void Template_delta_drives_sheet_profile_and_exposed_attachment_path_once()+ {+ var source=Library+"""+Static Service: RecessSpec = RecessSpec {+ Center: 60mm; Lead: 6mm; Run: 10mm; Depth: 8mm; AttachmentInset: 3mm; AttachmentSpan: 40mm;+}+ProfileDelta UserServiceRecess = Recess < P: Service, Owner: Wall.Outer >+SheetMetal DeltaTray {+ Thickness: 1mm;+ Base Deck { Profile: Rectangle { Width: 120mm; Height: 80mm; }; }+ Flange Wall { From: Deck.Front; Height: 20mm; Angle: 90deg; Radius: 2mm; }+ Flange Child { From: Wall.ServiceFlangeAttachment; Height: 12mm; Angle: 45deg; Radius: 2mm; }+}+""";+ var result=SheetMetalFirmament.Compile(source);+ Assert.True(result.IsSuccess,string.Join("; ",result.Diagnostics.Select(x=>x.Message)));+ var delta=Assert.Single(result.Spec!.SemanticLayout.ProfileDeltas!);+ Assert.Equal("Wall.UserServiceRecess",delta.Path);+ var attachment=Assert.Single(result.Part!.AttachmentPaths!);+ Assert.Equal("Wall.ServiceFlangeAttachment",attachment.StableId);+ Assert.Equal(40,(attachment.End-attachment.Start).Length,8);Assert.Equal(3,attachment.Inset,8);+ Assert.Equal(40,result.Part.Regions.Single(x=>x.StableId=="ChildBendRegion").Cylinder!.AxisLength,8);+ var wall=result.Part.Regions.Single(x=>x.StableId=="Wall");+ Assert.Contains(wall.ExactContour!.OuterLoop.Segments,segment=>segment.StableId.Contains("AttachmentLand",StringComparison.Ordinal));+ }++ [Fact]+ public void Delta_conflicts_and_open_programs_fail_with_semantic_diagnostics()+ {+ var open=new SemanticProfileDeltaIr("Broken","Plate.Broken",new(SemanticEdgeAnchorKind.FromStart,2),-1,+ [new("Carrier","Plate.Broken.Carrier",0,"test"),new("Deep","Plate.Broken.Deep",4,"test")],+ [new("Enter","Plate.Broken.Enter",SemanticProfileDeltaMemberKind.Diagonal,3,"Deep",null,[],"test")],"test");+ var resolution=SemanticEdgeProfileResolver.Resolve(new("Plate.Bottom","Plate.Bottom",new(0,0),new(20,0),[open],"uv","test"));+ Assert.False(resolution.IsSuccess);+ Assert.Contains(resolution.Diagnostics,diagnostic=>diagnostic.StartsWith("semantic-profile-delta-open:",StringComparison.Ordinal));+ }++ [Fact]+ public void Multiple_delta_programs_compose_when_disjoint_and_report_both_paths_when_overlapping()+ {+ SemanticProfileDeltaIr Delta(string name,double center)=>new(name,$"Plate.{name}",new(SemanticEdgeAnchorKind.CenteredAt,center),-1,+ [new("Carrier",$"Plate.{name}.Carrier",0,"test"),new("Inset",$"Plate.{name}.Inset",2,"test")],+ [new("Enter",$"Plate.{name}.Enter",SemanticProfileDeltaMemberKind.Step,0,"Inset",null,[],"test"),+ new("Land",$"Plate.{name}.Land",SemanticProfileDeltaMemberKind.Span,10,"Inset",null,[],"test"),+ new("Exit",$"Plate.{name}.Exit",SemanticProfileDeltaMemberKind.Step,0,"Carrier",null,[],"test")],"test");+ var disjoint=SemanticEdgeProfileResolver.Resolve(new("Plate.Bottom","Plate.Bottom",new(0,0),new(100,0),[Delta("A",20),Delta("B",70)],"uv","test"));+ Assert.True(disjoint.IsSuccess,string.Join(';',disjoint.Diagnostics));+ var overlapping=SemanticEdgeProfileResolver.Resolve(new("Plate.Bottom","Plate.Bottom",new(0,0),new(100,0),[Delta("A",20),Delta("B",25)],"uv","test"));+ Assert.False(overlapping.IsSuccess);+ Assert.Contains("semantic-edge-fragment-overlap:Plate.Bottom:Plate.A:Plate.B",overlapping.Diagnostics);+ }++ [Fact]+ public void Local_round_transition_lowers_to_exact_arc_descendants()+ {+ var delta=new SemanticProfileDeltaIr("Rounded","Plate.Rounded",new(SemanticEdgeAnchorKind.FromStart,5),-1,+ [new("Carrier","Plate.Rounded.Carrier",0,"test"),new("Deep","Plate.Rounded.Deep",8,"test")],+ [new("EnterRound","Plate.Rounded.EnterRound",SemanticProfileDeltaMemberKind.Round,6,"Deep",null,[],"test",5),+ new("ExitRound","Plate.Rounded.ExitRound",SemanticProfileDeltaMemberKind.Round,6,"Carrier",null,[],"test",5)],"test");+ var resolution=SemanticEdgeProfileResolver.Resolve(new("Plate.Bottom","Plate.Bottom",new(0,0),new(30,0),[delta],"uv","test"));+ Assert.True(resolution.IsSuccess,string.Join(';',resolution.Diagnostics));+ var rounded=resolution.Profile!.OrderedMembers.Single(member=>member.StableId=="Plate.Rounded");+ Assert.All(rounded.CurveDescendants,curve=>Assert.IsType<Aetheris.Kernel.Firmament.Materializer.LineArcCircularArc2D>(curve.Geometry));+ }++ [Fact]+ public void Concave_round_selects_the_alternate_exact_arc_without_moving_endpoints()+ {+ SemanticProfileDeltaIr Delta(bool concave)=>new("Rounded","Plate.Rounded",new(SemanticEdgeAnchorKind.FromStart,5),-1,+ [new("Carrier","Plate.Rounded.Carrier",0,"test"),new("Deep","Plate.Rounded.Deep",8,"test")],+ [new("EnterRound","Plate.Rounded.EnterRound",SemanticProfileDeltaMemberKind.Round,6,"Deep",null,[],"test",6,concave),+ new("ExitRound","Plate.Rounded.ExitRound",SemanticProfileDeltaMemberKind.Round,6,"Carrier",null,[],"test",6,concave)],"test");+ LineArcCircularArc2D First(bool concave)=>Assert.IsType<LineArcCircularArc2D>(SemanticEdgeProfileResolver.Resolve(+ new("Plate.Bottom","Plate.Bottom",new(0,0),new(30,0),[Delta(concave)],"uv","test")).Profile!.OrderedMembers+ .Single(member=>member.StableId=="Plate.Rounded").CurveDescendants[0].Geometry);+ var convex=First(false);var concave=First(true);+ Assert.NotEqual(convex.Center,concave.Center);+ Assert.Equal(6,concave.Radius,8);+ }++ [Fact]+ public void Authored_slot_remains_an_exact_capsule_through_formed_and_flat_materialization()+ {+ const string source="""+ Concept Struct SlotLayout {+ Pattern Vents {+ On: Deck;+ Feature: Slot { Length: 10mm; Width: 40mm; };+ Center: Deck.Center;+ Count: 1;+ Pitch: (0mm, 0mm);+ }+ }+ SheetMetal SlotCoupon {+ Intent: SlotLayout;+ Thickness: 1mm;+ Base Deck { Profile: Rectangle { Width: 80mm; Height: 60mm; }; }+ Flange Wall { From: Deck.Front; Height: 10mm; Angle: 90deg; Radius: 2mm; }+ }+ """;+ var result=SheetMetalFirmament.Compile(source);+ Assert.True(result.IsSuccess,string.Join(';',result.Diagnostics.Select(x=>x.Message)));+ var feature=Assert.Single(result.Part!.Features);+ Assert.Equal(SheetFeatureKind.Slot,feature.Kind);+ Assert.Equal(2,feature.ExactContour!.OuterLoop.Segments.Count(x=>x.Geometry is LineArcCircularArc2D));+ Assert.All(feature.ExactContour.OuterLoop.Segments.Where(x=>x.Geometry is LineArcCircularArc2D),+ segment=>Assert.Equal(5,((LineArcCircularArc2D)segment.Geometry).Radius,8));+ var flatCut=Assert.Single(result.FlatPattern!.CutLoops);+ Assert.Equal(2,flatCut.ExactContour!.OuterLoop.Segments.Count(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)>=4);+ Assert.True(BrepExportPreflight.Validate(result.Part.FormedBody).IsValid);+ }+}diff --git a/Aetheris.SheetMetal.Tests/SheetMetalM8Tests.cs b/Aetheris.SheetMetal.Tests/SheetMetalM8Tests.csindex 8cacf0d5..ace0fca0 100644--- a/Aetheris.SheetMetal.Tests/SheetMetalM8Tests.cs+++ b/Aetheris.SheetMetal.Tests/SheetMetalM8Tests.cs@@ -1,5 +1,6 @@using Aetheris.Kernel.Core.Brep;using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.FirmamentV2;using Xunit;namespace Aetheris.SheetMetal.Tests;@@ -21,7 +22,7 @@ public sealed class SheetMetalM8Tests}[Fact]- public void Ctc03_FinalSemanticLayout_LowersAllOpeningsAndPartialTabFlangeWithoutSourceStep()+ public void Ctc03_FinalSemanticLayout_LowersAllOpeningsAndRoundedProfileFlangeWithoutSourceStep(){var isolated=Path.Combine(Path.GetTempPath(),$"ctc03-m8-{Guid.NewGuid():N}.firmament");try@@ -30,13 +31,17 @@ public sealed class SheetMetalM8TestsAssert.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(12,result.Spec.SemanticLayout.Corners!.Count);+ Assert.Equal(9,result.Spec!.SemanticLayout.Patterns.Count);Assert.Empty(result.Spec.SemanticLayout.Tabs);Assert.Empty(result.Spec.SemanticLayout.SteppedNotches!);Assert.Equal(4,result.Spec.SemanticLayout.ProfileDeltas!.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);+ var rearDelta=result.Spec.SemanticLayout.ProfileDeltas.Single(x=>x.Path=="RearMountingFlange.RearConnectorRelief");+ Assert.All(rearDelta.Program.Members.Where(x=>x.Kind==SemanticProfileDeltaMemberKind.Round),x=>Assert.True(x.Concave));+ var rearArcs=result.FlatPattern.Regions2D.Single(x=>x.SourceRegionId=="RearMountingFlange").ExactContour!.OuterLoop.Segments.Select(x=>x.Geometry).OfType<Aetheris.Kernel.Firmament.Materializer.LineArcCircularArc2D>().ToArray();+ Assert.Equal(2,rearArcs.Length);Assert.All(rearArcs,x=>Assert.True(x.SweepAngleRadians<0));Assert.True(BrepExportPreflight.Validate(result.Part.FormedBody!).IsValid);var paths=SheetMetalConceptPaths.Inspect(result.Spec,result.Part,result.FlatPattern).Select(x=>x.Path).ToArray();- Assert.Contains("Ctc03Layout.FrontConnectorRelief",paths);Assert.Contains("Flat.Ctc03Layout.FrontConnectorRelief",paths);+ Assert.Contains("FrontMountingFlange.FrontConnectorRelief",paths);Assert.Contains("Flat.FrontMountingFlange.FrontConnectorRelief",paths);Assert.Contains("Ctc03Layout.LeftWall.OuterStart.RearEndTaper",paths);Assert.Contains("Flat.Ctc03Layout.LeftWall.OuterStart.RearEndTaper",paths);}finally{if(File.Exists(isolated))File.Delete(isolated);}diff --git a/Aetheris.SheetMetal/SheetMetalAuthoredLowering.cs b/Aetheris.SheetMetal/SheetMetalAuthoredLowering.csindex 3933dd65..2284921b 100644--- a/Aetheris.SheetMetal/SheetMetalAuthoredLowering.cs+++ b/Aetheris.SheetMetal/SheetMetalAuthoredLowering.cs@@ -26,7 +26,7 @@ public sealed record AuthoredSheetFlangeSpec(double? SpanLength = null, double SpanOffset = 0d);public sealed record AuthoredSheetCutSpec(string Name, string RegionName, SheetFeatureKind Kind, double X, double Y,- double? Diameter, double? Width, double? Length);+ double? Diameter, double? Width, double? Length, bool ExactCapsule = false);public sealed record SheetMetalConstructionSpec(string Name, double Thickness, string? Material, double KFactor, AuthoredSheetBaseSpec Base,IReadOnlyList<AuthoredSheetFlangeSpec> Flanges, IReadOnlyList<AuthoredSheetCutSpec> Cuts,@@ -78,6 +78,13 @@ internal static class AuthoredSheetMetalCompiler.Where(x=>x.On.Success).Select(x=>$"{x.On.Groups["region"].Value}.{x.Block.Name}").ToHashSet(StringComparer.OrdinalIgnoreCase);+ var deltaDeclarations=SemanticProfileDeltaParser.Parse(source);+ foreach(var delta in deltaDeclarations.Deltas)+ {+ var region=delta.OwnerPath.Split('.')[0];+ foreach(var exposure in delta.Exposures.Where(exposure=>exposure.Capabilities.Contains("FlangeAttachable",StringComparer.OrdinalIgnoreCase)))+ declaredAttachmentPaths.Add($"{region}.{exposure.Path.Split('.').Last()}");+ }var flanges = new List<AuthoredSheetFlangeSpec>();foreach (var block in Blocks(source, "Flange"))@@ -336,6 +343,7 @@ internal static class AuthoredSheetMetalLoweringvar frame = new RegionFrame(flange.Name, tangentA, tangentB, direction, normal, flange.Length); frames[flange.Name] = frame;var tabs=spec.SemanticLayout.Tabs.Where(x=>x.Region.Equals(flange.Name,StringComparison.OrdinalIgnoreCase)&&x.Edge.Equals("Outer",StringComparison.OrdinalIgnoreCase)).ToArray();var steppedNotches=(spec.SemanticLayout.SteppedNotches??[]).Where(x=>x.Region.Equals(flange.Name,StringComparison.OrdinalIgnoreCase)&&x.Edge.Equals("Outer",StringComparison.OrdinalIgnoreCase)).ToArray();+ var profileDeltas=(spec.SemanticLayout.ProfileDeltas??[]).Where(x=>x.Region.Equals(flange.Name,StringComparison.OrdinalIgnoreCase)&&x.Edge.Equals("Outer",StringComparison.OrdinalIgnoreCase)).ToArray();var cornerPrograms=(spec.SemanticLayout.Corners??[]).Where(x=>x.Region.Equals(flange.Name,StringComparison.OrdinalIgnoreCase)).ToArray();var rootStartProgram=cornerPrograms.SingleOrDefault(x=>x.Corner.Equals("RootStart",StringComparison.OrdinalIgnoreCase));var rootEndProgram=cornerPrograms.SingleOrDefault(x=>x.Corner.Equals("RootEnd",StringComparison.OrdinalIgnoreCase));@@ -374,7 +382,8 @@ internal static class AuthoredSheetMetalLoweringtabs.Select(tab=>(SemanticEdgeFragmentIr)new SemanticEdgeTabIr(tab.Path.Split('.').Last(),tab.Path,new(SemanticEdgeAnchorKind.CenteredAt,ownerLength-tab.Center),tab.Width,tab.Extension,-1,"SheetMetalSemanticLayout")).Concat(steppedNotches.Select(notch=>(SemanticEdgeFragmentIr)new SemanticEdgeSteppedNotchIr(notch.Path.Split('.').Last(),notch.Path,- new(SemanticEdgeAnchorKind.CenteredAt,ownerLength-notch.Center),notch.Width,notch.Depth,notch.ShoulderDepth,notch.OuterChamfer,notch.InnerChamfer,-notch.Side,"SheetMetalSemanticLayout"))).ToArray(),+ new(SemanticEdgeAnchorKind.CenteredAt,ownerLength-notch.Center),notch.Width,notch.Depth,notch.ShoulderDepth,notch.OuterChamfer,notch.InnerChamfer,-notch.Side,"SheetMetalSemanticLayout")))+ .Concat(profileDeltas.Select(delta=>(SemanticEdgeFragmentIr)ReverseDelta(delta.Program,ownerLength))).ToArray(),"SheetRegionLocal[u=OuterB->OuterA,v=material-left]","Sheet Metal semantic edge attachment");SemanticEdgeProfileResolution Edge(string edgeName,SemanticProfilePoint start,SemanticProfilePoint end,IReadOnlyList<SemanticEdgeFragmentIr> fragments,ResolvedSemanticCornerProfileIr? startCorner,ResolvedSemanticCornerProfileIr? endCorner)=>SemanticEdgeProfileResolver.Resolve(new($"{flange.Name}.{edgeName}",$"{flange.Name}.{edgeName}",start,end,fragments,$"{flange.Name}.{edgeName}[u,v]","Sheet Metal profile edge"),@@ -393,7 +402,7 @@ internal static class AuthoredSheetMetalLowering{var descendants=profile.Profile!.OrderedMembers.SelectMany(member=>member.CurveDescendants).ToArray();if(descendants.Length==0)return;- Add(Map(((LineArcLineSegment2D)descendants[0].Geometry).Start));+ Add(Map(Start(descendants[0].Geometry)));foreach(var descendant in descendants){localCurves.Add((descendant.StableId,descendant.Geometry,descendant.Provenance));Add(Map(End(descendant.Geometry)));}}void AddCorner(ResolvedSemanticCornerProfileIr? corner)@@ -412,7 +421,7 @@ internal static class AuthoredSheetMetalLoweringcorrespondence.Add(new(corner.Source.CornerPath,"ProfileCorner",corner.Source.CornerPath,$"flat-{corner.Source.CornerPath}"));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);+ var fragmentArea=tabs.Sum(x=>x.Width*x.Extension)-steppedNotches.Sum(x=>x.Width*x.Depth)-profileDeltas.Sum(x=>DeltaArea(x.Program));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));@@ -437,12 +446,21 @@ internal static class AuthoredSheetMetalLoweringif (cut.RegionName.Equals(spec.Base.Name, StringComparison.OrdinalIgnoreCase)) { plane = basePlane; boundary = baseBoundary; }else { var region = regions.FirstOrDefault(r => r.StableId.Equals(stableRegions.GetValueOrDefault(cut.RegionName,cut.RegionName), StringComparison.OrdinalIgnoreCase)); plane = region?.Plane; boundary = region?.Boundary3D ?? []; }if (plane is null) return Failure($"Cut '{cut.Name}' references unknown planar region '{cut.RegionName}'.", SheetMetalDiagnosticCodes.FeatureMappingFailure);- var local=boundary.Select(p=>(U:(p-plane.Origin).Dot(plane.UAxis),V:(p-plane.Origin).Dot(plane.VAxis))).ToArray();var hu=(cut.Diameter??cut.Length)!.Value/2;var hv=(cut.Diameter??cut.Width)!.Value/2;+ var local=boundary.Select(p=>(U:(p-plane.Origin).Dot(plane.UAxis),V:(p-plane.Origin).Dot(plane.VAxis))).ToArray();+ var hu=cut.ExactCapsule&&cut.Length!.Value>=cut.Width!.Value?(cut.Length.Value+cut.Width.Value)/2:(cut.Diameter??cut.Length)!.Value/2;+ var hv=cut.ExactCapsule&&cut.Width!.Value>cut.Length!.Value?(cut.Width.Value+cut.Length.Value)/2:(cut.Diameter??cut.Width)!.Value/2;if(local.Length<3||cut.X-hu<=local.Min(p=>p.U)+1e-8||cut.X+hu>=local.Max(p=>p.U)-1e-8||cut.Y-hv<=local.Min(p=>p.V)+1e-8||cut.Y+hv>=local.Max(p=>p.V)-1e-8)return Failure($"Cut '{cut.Name}' reaches or crosses the boundary/bend zone of region '{cut.RegionName}'.",SheetMetalDiagnosticCodes.CutCrossesBend);var center = plane.Origin + plane.UAxis * cut.X + plane.VAxis * cut.Y;- IReadOnlyList<Point3D> loop = cut.Kind == SheetFeatureKind.CircularHole ? [] : RectangleLoop(center, plane.UAxis, plane.VAxis, cut.Length!.Value, cut.Width!.Value);- features.Add(new(cut.Name, cut.Kind, stableRegions.GetValueOrDefault(cut.RegionName,cut.RegionName), center, cut.Diameter, loop, source, evidence));+ IReadOnlyList<Point3D> loop;PlanarContour2? exactFeature=null;+ if(cut.Kind==SheetFeatureKind.CircularHole)loop=[];+ else if(cut.Kind==SheetFeatureKind.Slot&&cut.ExactCapsule)+ {+ var capsule=Capsule(cut.Name,cut.X,cut.Y,cut.Length!.Value,cut.Width!.Value,plane);+ loop=capsule.Boundary;exactFeature=capsule.Contour;+ }+ else loop=RectangleLoop(center, plane.UAxis, plane.VAxis, cut.Length!.Value, cut.Width!.Value);+ features.Add(new(cut.Name, cut.Kind, stableRegions.GetValueOrDefault(cut.RegionName,cut.RegionName), center, cut.Diameter, loop, source, evidence,exactFeature));correspondence.Add(new(cut.Name, "Cut", cut.Name, cut.Name));}@@ -509,12 +527,56 @@ 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 (IReadOnlyList<Point3D> Boundary,PlanarContour2 Contour) Capsule(string id,double cx,double cy,double length,double width,SheetPlaneReference plane)+ {+ var alongU=length>=width;var diameter=Math.Min(length,width);var run=Math.Max(length,width);var radius=diameter/2d;var straight=run/2d;+ var local=alongU+ ?new[]{(cx-straight,cy-radius),(cx+straight,cy-radius),(cx+straight,cy+radius),(cx-straight,cy+radius)}+ :new[]{(cx-radius,cy-straight),(cx+radius,cy-straight),(cx+radius,cy+straight),(cx-radius,cy+straight)};+ var boundary=local.Select(p=>plane.Origin+plane.UAxis*p.Item1+plane.VAxis*p.Item2).ToArray();+ var provenance=new ProfileSegmentProvenance($"{id}.capsule",id,id,"SheetMetal authored analytic capsule","SheetRegionLocal[u,v]");+ PlanarContourSegment2[] segments=alongU+ ?[new($"{id}.Bottom",new LineArcLineSegment2D(local[0],local[1]),provenance with { StableId=$"{id}.Bottom" }),+ new($"{id}.RightArc",new LineArcCircularArc2D((cx+straight,cy),radius,-Math.PI/2,Math.PI),provenance with { StableId=$"{id}.RightArc" }),+ new($"{id}.Top",new LineArcLineSegment2D(local[2],local[3]),provenance with { StableId=$"{id}.Top" }),+ new($"{id}.LeftArc",new LineArcCircularArc2D((cx-straight,cy),radius,Math.PI/2,Math.PI),provenance with { StableId=$"{id}.LeftArc" })]+ :[new($"{id}.BottomArc",new LineArcCircularArc2D((cx,cy-straight),radius,Math.PI,Math.PI),provenance with { StableId=$"{id}.BottomArc" }),+ new($"{id}.Right",new LineArcLineSegment2D(local[1],local[2]),provenance with { StableId=$"{id}.Right" }),+ new($"{id}.TopArc",new LineArcCircularArc2D((cx,cy+straight),radius,0,Math.PI),provenance with { StableId=$"{id}.TopArc" }),+ new($"{id}.Left",new LineArcLineSegment2D(local[3],local[0]),provenance with { StableId=$"{id}.Left" })];+ return(boundary,new(id,"SheetRegionLocal[u,v]",new($"{id}.Outer",true,segments),[],$"analytic capsule diameter={diameter:R} straight-run={run:R}"));+ }+ private static SemanticProfileDeltaIr ReverseDelta(SemanticProfileDeltaIr delta,double ownerLength)+ {+ var states=new List<string>{delta.Levels.FirstOrDefault(level=>Math.Abs(level.Offset)<1e-9)?.Name??"Carrier"};+ states.AddRange(delta.Members.Select(member=>member.ToLevel));+ var reversed=delta.Members.Select((member,index)=>(member,index)).Reverse().Select(pair=>pair.member with { ToLevel=states[pair.index] }).ToArray();+ var anchor=delta.Anchor.Kind switch+ {+ SemanticEdgeAnchorKind.FromStart=>new SemanticEdgeAnchorIr(SemanticEdgeAnchorKind.FromEnd,delta.Anchor.Offset),+ SemanticEdgeAnchorKind.FromEnd=>new SemanticEdgeAnchorIr(SemanticEdgeAnchorKind.FromStart,delta.Anchor.Offset),+ SemanticEdgeAnchorKind.CenteredAt=>new SemanticEdgeAnchorIr(SemanticEdgeAnchorKind.CenteredAt,ownerLength-delta.Anchor.Offset),+ _=>delta.Anchor+ };+ return delta with { Anchor=anchor,Side=-delta.Side,Members=reversed };+ }+ private static double DeltaArea(SemanticProfileDeltaIr delta)+ {+ var levels=delta.Levels.ToDictionary(level=>level.Name,level=>Math.Abs(level.Offset),StringComparer.Ordinal);var current=0d;var area=0d;+ foreach(var member in delta.Members){var target=levels.GetValueOrDefault(member.ToLevel);area+=(current+target)*member.Run/2d;current=target;}return area;+ }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 (double X,double Y) Start(LineArcProfileCurve2D curve)=>curve switch+ {+ LineArcLineSegment2D line=>line.Start,+ LineArcCircularArc2D arc=>(arc.Center.X+arc.Radius*Math.Cos(arc.StartAngleRadians),arc.Center.Y+arc.Radius*Math.Sin(arc.StartAngleRadians)),+ _=>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);@@ -645,7 +707,8 @@ internal static class AuthoredSheetMetalLoweringelse{positive=feature.Boundary3D.Select(p=>p+n*spec.Thickness/2).ToArray();negative=feature.Boundary3D.Select(p=>p-n*spec.Thickness/2).ToArray();- positiveEdges=Enumerable.Range(0,positive.Count).Select(i=>Edge(positive[i],positive[(i+1)%positive.Count])).ToArray();negativeEdges=Enumerable.Range(0,negative.Count).Select(i=>Edge(negative[i],negative[(i+1)%negative.Count])).ToArray();+ positiveEdges=Enumerable.Range(0,positive.Count).Select(i=>Edge(positive[i],positive[(i+1)%positive.Count],CutCurve(feature,plane,true,i,positive[i],positive[(i+1)%positive.Count]))).ToArray();+ negativeEdges=Enumerable.Range(0,negative.Count).Select(i=>Edge(negative[i],negative[(i+1)%negative.Count],CutCurve(feature,plane,false,i,negative[i],negative[(i+1)%negative.Count]))).ToArray();}var cut=new CutBoundary(feature,plane,positive,negative,positiveEdges,negativeEdges,circle);if(!cutsByRegion.TryGetValue(feature.OwningRegionId,out var list))cutsByRegion[feature.OwningRegionId]=list=[];list.Add(cut);}@@ -661,10 +724,29 @@ internal static class AuthoredSheetMetalLowering}else for(var i=0;i<cut.Positive.Count;i++){- var j=(i+1)%cut.Positive.Count;var loop=new[]{ExistingEdge(cut.PositiveEdges[i],cut.Positive[i]),DirectedEdge(cut.Positive[j],cut.Negative[j]),ExistingEdge(cut.NegativeEdges[i],cut.Negative[j]),DirectedEdge(cut.Negative[i],cut.Positive[i])};var u=cut.Positive[j]-cut.Positive[i];var v=cut.Negative[i]-cut.Positive[i];var normal=Unit(u.Cross(v));Face([loop],SurfaceGeometry.FromPlane(new PlaneSurface(cut.Positive[i],Direction3D.Create(normal),Direction3D.Create(Unit(u)))));+ var j=(i+1)%cut.Positive.Count;var loop=new[]{ExistingEdge(cut.PositiveEdges[i],cut.Positive[i]),DirectedEdge(cut.Positive[j],cut.Negative[j]),ExistingEdge(cut.NegativeEdges[i],cut.Negative[j]),DirectedEdge(cut.Negative[i],cut.Positive[i])};+ if(edgeGeometry[cut.PositiveEdges[i]].Curve is { Kind:CurveGeometryKind.Circle3,Circle3:{ } circle })+ {+ var axis=Unit(cut.Positive[i]-cut.Negative[i]);var center=circle.Center-axis*(spec.Thickness/2);+ Face([loop],SurfaceGeometry.FromCylinder(new CylinderSurface(center,Direction3D.Create(axis),circle.Radius,Direction3D.Create(cut.Positive[i]-circle.Center))));+ }+ else+ {+ var u=cut.Positive[j]-cut.Positive[i];var v=cut.Negative[i]-cut.Positive[i];var normal=Unit(u.Cross(v));Face([loop],SurfaceGeometry.FromPlane(new PlaneSurface(cut.Positive[i],Direction3D.Create(normal),Direction3D.Create(Unit(u)))));+ }}}}+ EdgeGeometry CutCurve(SheetFeatureIr feature,SheetPlaneReference plane,bool positive,int index,Point3D a,Point3D q)+ {+ if(feature.ExactContour is not null&&index<feature.ExactContour.OuterLoop.Segments.Count&&feature.ExactContour.OuterLoop.Segments[index].Geometry is LineArcCircularArc2D arc)+ {+ var n=Unit(plane.Normal);if(arc.SweepAngleRadians<0)n=-n;+ var center=plane.Origin+plane.UAxis*arc.Center.X+plane.VAxis*arc.Center.Y+Unit(plane.Normal)*(positive?spec.Thickness/2:-spec.Thickness/2);+ return new(CurveGeometry.FromCircle(new Circle3Curve(center,Direction3D.Create(n),arc.Radius,Direction3D.Create(a-center))),new(0,Math.Abs(arc.SweepAngleRadians)));+ }+ return Line(a,q);+ }EdgeGeometry Line(Point3D a,Point3D q){var d=q-a;return new(CurveGeometry.FromLine(new Line3Curve(a,Direction3D.Create(d))),new(0,d.Length));}Point3D ProjectToAxis(Point3D p,Point3D origin,Vector3D axis)=>origin+axis*((p-origin).Dot(axis));}diff --git a/Aetheris.SheetMetal/SheetMetalConceptPaths.cs b/Aetheris.SheetMetal/SheetMetalConceptPaths.csindex f6f285c9..84ddb2a3 100644--- a/Aetheris.SheetMetal/SheetMetalConceptPaths.cs+++ b/Aetheris.SheetMetal/SheetMetalConceptPaths.cs@@ -46,6 +46,12 @@ public static class SheetMetalConceptPathsvar 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 delta in spec.SemanticLayout.ProfileDeltas??[])+ {+ Add(delta.Path,"SemanticProfileDelta",delta.Program.StableId,delta.Region,$"flat-{delta.Region}","template-specialized local profile modification program","EdgeFeature","ManufacturingContour","StableSemanticIdentity");+ foreach(var level in delta.Program.Levels)Add($"{delta.Path}.{level.Name}","SemanticProfileLevel",level.StableId,delta.Region,$"flat-{delta.Region}","named local profile offset","ProfileLandmark","StableSemanticIdentity");+ foreach(var member in delta.Program.Members)Add($"{delta.Path}.{member.Name}","SemanticProfileDeltaMember",member.StableId,delta.Region,$"flat-{delta.Region}","exact descendant of semantic profile delta","ManufacturingContour","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/SheetMetalFirmament.cs b/Aetheris.SheetMetal/SheetMetalFirmament.csindex a73e6528..fc42b7db 100644--- a/Aetheris.SheetMetal/SheetMetalFirmament.cs+++ b/Aetheris.SheetMetal/SheetMetalFirmament.cs@@ -44,6 +44,11 @@ public static class SheetMetalFirmamentpublic static SheetMetalAuthoringResult Compile(string source,string sourcePath="authored.firmament"){ArgumentNullException.ThrowIfNull(source);+ if(Regex.IsMatch(source,@"\bUse\s+Profile\.Modifications\s*;",RegexOptions.CultureInvariant))+ {+ source=Regex.Replace(source,@"\bUse\s+Profile\.Modifications\s*;",string.Empty,RegexOptions.CultureInvariant);+ source=ProfileModificationTemplateLibrary.Source+Environment.NewLine+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);diff --git a/Aetheris.SheetMetal/SheetMetalFlattener.cs b/Aetheris.SheetMetal/SheetMetalFlattener.csindex 3e7d94a1..18b66026 100644--- a/Aetheris.SheetMetal/SheetMetalFlattener.cs+++ b/Aetheris.SheetMetal/SheetMetalFlattener.cs@@ -85,7 +85,7 @@ public static class SheetMetalFlattener{var exact=feature.Kind==SheetFeatureKind.CircularHole&&feature.Diameter is { } exactDiameter? CircleContour(feature.StableId,mapping.Map(feature.Center),exactDiameter/2d)- : Contour(feature.StableId,loop,"mapped exact feature boundary");+ : feature.ExactContour is not null?MapContour(feature.ExactContour,mapping):Contour(feature.StableId,loop,"mapped exact feature boundary");cuts.Add(new(feature.StableId,feature.Kind,loop,feature.OwningRegionId,exact));}else diagnostics.Add(new(SheetMetalDiagnosticCodes.FeatureMappingFailure,SheetMetalDiagnosticSeverity.Warning,$"Feature '{feature.StableId}' did not yield a closed 2D loop."));@@ -207,21 +207,67 @@ public static class SheetMetalFlattenerif(usable.Length!=regions.Count)return null;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))+ var depth=new Dictionary<string,int>(StringComparer.Ordinal) { [part.BaseRegionId]=0 };+ for(var pass=0;pass<part.Regions.Count;pass++)foreach(var bend in part.Bends)+ {+ if(depth.TryGetValue(bend.AdjacentRegionA,out var a)&&!depth.ContainsKey(bend.AdjacentRegionB))depth[bend.AdjacentRegionB]=a+2;+ if(depth.TryGetValue(bend.AdjacentRegionB,out var b)&&!depth.ContainsKey(bend.AdjacentRegionA))depth[bend.AdjacentRegionA]=b+2;+ var bendRegion=bend.StableId;+ if(!depth.ContainsKey(bendRegion))+ {+ if(depth.TryGetValue(bend.AdjacentRegionA,out var parentDepth))depth[bendRegion]=parentDepth+1;+ else if(depth.TryGetValue(bend.AdjacentRegionB,out parentDepth))depth[bendRegion]=parentDepth+1;+ }+ }+ var additions=usable.Where(x=>x!=baseRegion).OrderBy(x=>depth.GetValueOrDefault(x.SourceRegionId,int.MaxValue)).ThenBy(x=>x.StableId,StringComparer.Ordinal).ToArray();+ var planOperations=additions.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)+ var contour=TryComposeWholePlan(part,baseRegion,plan);+ if(contour is null){- foreach(var message in composed.Arrangement.Diagnostics)diagnostics.Add(new(SheetMetalDiagnosticCodes.ExactBlankContour,SheetMetalDiagnosticSeverity.Warning,$"Exact blank composition: {message}"));- return null;+ contour=baseRegion.ExactContour!;+ foreach(var operation in plan.OrderedOperations)+ {+ if(operation.Kind==BlankCompositionOperationKind.AddMaterialRegion&&TryMergeAlongSharedEdge(contour,operation.Contour,out var merged))+ {+ contour=merged with { StableId=$"flat-{part.StableId}.blank.{operation.Order}" };+ continue;+ }+ if(operation.Kind==BlankCompositionOperationKind.InsertThroughCut&&operation.Contour.InnerLoops.Count==0)+ {+ contour=contour with+ {+ StableId=$"flat-{part.StableId}.blank.{operation.Order}",+ InnerLoops=[..contour.InnerLoops,operation.Contour.OuterLoop with { IsOuter=false }],+ Provenance=$"{contour.Provenance}; exact nested through-cut:{operation.StableId}"+ };+ continue;+ }+ const string currentId="__current-blank";+ var profiles=new Dictionary<string,ResolvedProfile2D>(StringComparer.Ordinal)+ {+ [currentId]=PlanarContourKernel.ToResolvedProfile(contour,currentId),+ [operation.StableId]=PlanarContourKernel.ToResolvedProfile(operation.Contour,operation.StableId)+ };+ var intent=operation.Kind==BlankCompositionOperationKind.AddMaterialRegion?PrismaticProfileIntent.Add:PrismaticProfileIntent.Remove;+ var compositionOperations=new[]+ {+ new PrismaticProfileOperation(currentId,PrismaticProfileIntent.Base,currentId,0,1,"accumulated blank",part.BaseRegionId),+ new PrismaticProfileOperation(operation.StableId,intent,operation.StableId,0,1,operation.Kind.ToString(),operation.SemanticOwner)+ };+ var composed=ProfileArrangementBuilder.Compose("XY",compositionOperations,profiles,$"sheetmetal-blank:{part.StableId}:{operation.StableId}");+ if(composed.Region is null)+ {+ foreach(var message in composed.Arrangement.Diagnostics)diagnostics.Add(new(SheetMetalDiagnosticCodes.ExactBlankContour,SheetMetalDiagnosticSeverity.Warning,$"Exact blank composition at {operation.StableId}: {message}"));+ return null;+ }+ var regionProfile=new ResolvedProfile2D($"flat-{part.StableId}.blank.{operation.Order}","XY",[composed.Region.Outer.Loops.Single(),..composed.Region.Holes.Select(x=>x.Loops.Single())]);+ contour=PlanarContourKernel.FromResolvedProfile(regionProfile,$"SheetMetal exact semantic composition step:{operation.StableId}") with { StableId=$"flat-{part.StableId}.blank.{operation.Order}" };+ }}- 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 { 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),@@ -234,6 +280,41 @@ public static class SheetMetalFlattenerforeach(var item in validation.Diagnostics)diagnostics.Add(new(SheetMetalDiagnosticCodes.ExactBlankContour,SheetMetalDiagnosticSeverity.Warning,$"Exact blank composition: {item.Code}: {item.Message}"));return null;}+ private static PlanarContour2? TryComposeWholePlan(SheetMetalPartIr part,FlatRegion2D baseRegion,BlankCompositionPlan plan)+ {+ 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)return null;+ var regionProfile=new ResolvedProfile2D($"flat-{part.StableId}.blank","XY",[composed.Region.Outer.Loops.Single(),..composed.Region.Holes.Select(x=>x.Loops.Single())]);+ return PlanarContourKernel.FromResolvedProfile(regionProfile,$"SheetMetal exact semantic composition plan:{part.StableId}");+ }+ private static bool TryMergeAlongSharedEdge(PlanarContour2 accumulated,PlanarContour2 addition,out PlanarContour2 merged)+ {+ const double tolerance=1e-7;+ var a=accumulated.OuterLoop.Segments;var b=addition.OuterLoop.Segments;+ for(var ai=0;ai<a.Count;ai++)+ {+ if(a[ai].Geometry is not LineArcLineSegment2D al)continue;+ for(var bi=0;bi<b.Count;bi++)+ {+ if(b[bi].Geometry is not LineArcLineSegment2D bl||!Near(al.Start,bl.End)||!Near(al.End,bl.Start))continue;+ var segments=new List<PlanarContourSegment2>(a.Count+b.Count-2);+ for(var offset=1;offset<a.Count;offset++)segments.Add(a[(ai+offset)%a.Count]);+ for(var offset=1;offset<b.Count;offset++)segments.Add(b[(bi+offset)%b.Count]);+ var candidate=accumulated with+ {+ OuterLoop=accumulated.OuterLoop with { Segments=segments },+ InnerLoops=[..accumulated.InnerLoops,..addition.InnerLoops],+ Provenance=$"{accumulated.Provenance}; exact shared-edge material attachment:{addition.StableId}"+ };+ if(PlanarContourKernel.Validate(candidate).IsValid){merged=candidate;return true;}+ }+ }+ merged=accumulated;return false;+ static bool Near((double X,double Y) x,(double X,double Y) y)=>Math.Abs(x.X-y.X)<=tolerance&&Math.Abs(x.Y-y.Y)<=tolerance;+ }private static IReadOnlyList<SheetPoint2> ContourVertices(PlanarContour2 contour)=>contour.OuterLoop.Segments.Select(segment=>segment.Geometry switch{LineArcLineSegment2D line=>new SheetPoint2(line.Start.X,line.Start.Y),diff --git a/Aetheris.SheetMetal/SheetMetalIr.cs b/Aetheris.SheetMetal/SheetMetalIr.csindex f800b08b..e11c921e 100644--- a/Aetheris.SheetMetal/SheetMetalIr.cs+++ b/Aetheris.SheetMetal/SheetMetalIr.cs@@ -136,7 +136,8 @@ public sealed record SheetFeatureIr(double? Diameter,IReadOnlyList<Point3D> Boundary3D,SheetSourceBinding Source,- IReadOnlyList<SheetEvidence> Evidence);+ IReadOnlyList<SheetEvidence> Evidence,+ PlanarContour2? ExactContour = null);public sealed record SheetMetalCornerIr(string StableId,diff --git a/Aetheris.SheetMetal/SheetMetalSemanticLayout.cs b/Aetheris.SheetMetal/SheetMetalSemanticLayout.csindex 2442f749..4c9d1f5a 100644--- a/Aetheris.SheetMetal/SheetMetalSemanticLayout.cs+++ b/Aetheris.SheetMetal/SheetMetalSemanticLayout.cs@@ -1,5 +1,6 @@using System.Globalization;using System.Text.RegularExpressions;+using Aetheris.Kernel.Firmament.FirmamentV2;namespace Aetheris.SheetMetal;@@ -7,7 +8,9 @@ public enum SheetMetalSemanticConstraintKind { RequiredMembers, EqualSize, Equalpublic 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);+ string Path,string Region,string CarrierEdge,double Inset,double Span,double SpanOffset,bool ReleaseToCarrier,+ string? ProfileDeltaPath = null,string? DeltaMemberPath = null);+public sealed record SheetMetalSemanticProfileDelta(string Path,string Region,string Edge,SemanticProfileDeltaIr Program);public sealed record SheetMetalSemanticTab(string Path,string Region,string Edge,double Center,double Width,double Extension);public sealed record SheetMetalSemanticSteppedNotch(@@ -28,7 +31,8 @@ public sealed record SheetMetalSemanticLayout(IReadOnlyList<SheetMetalSemanticPattern> Patterns,IReadOnlyList<SheetMetalSemanticConstraint> Constraints,IReadOnlyList<SheetMetalSemanticSteppedNotch>? SteppedNotches = null,IReadOnlyList<SheetMetalSemanticCornerProfile>? Corners = null,- IReadOnlyList<SheetMetalSemanticAttachmentPath>? AttachmentPaths = null)+ IReadOnlyList<SheetMetalSemanticAttachmentPath>? AttachmentPaths = null,+ IReadOnlyList<SheetMetalSemanticProfileDelta>? ProfileDeltas = null){public static SheetMetalSemanticLayout Empty { get; } = new([],[],[],[],[]);}@@ -65,6 +69,7 @@ internal static class SheetMetalSemanticLayoutParservar generated=new List<AuthoredSheetCutSpec>();var constraints=new List<SheetMetalSemanticConstraint>();var regionSizes=RegionSizes(baseSpec,flanges);+ var profileDeltas=new List<SheetMetalSemanticProfileDelta>();var attachmentPaths=new List<SheetMetalSemanticAttachmentPath>();foreach(var block in Blocks(source,"AttachmentPath",structs))@@ -93,6 +98,39 @@ internal static class SheetMetalSemanticLayoutParserreturn Fail("sheetmetal-attachment-path-duplicate",$"Attachment path '{path}' is declared more than once.");attachmentPaths.Add(new(path,region,edge,inset,span,spanOffset,releaseToCarrier));}+ var parsedDeltas=SemanticProfileDeltaParser.Parse(source);+ if(!parsedDeltas.IsSuccess)return Fail("sheetmetal-profile-delta-parse",string.Join("; ",parsedDeltas.Diagnostics));+ foreach(var parsed in parsedDeltas.Deltas)+ {+ var owner=Regex.Match(parsed.OwnerPath,@"^(?<region>[A-Za-z_][A-Za-z0-9_]*)\.(?<edge>Outer)$",Rx);+ if(!owner.Success||!regionSizes.TryGetValue(owner.Groups["region"].Value,out var size))+ return Fail("sheetmetal-profile-delta-owner",$"ProfileDelta '{parsed.Delta.StableId}' requires On: <planar-region>.Outer.");+ var length=size.Width;var span=parsed.Delta.Span;+ var start=parsed.Delta.Anchor.Kind switch+ {+ SemanticEdgeAnchorKind.FromStart=>parsed.Delta.Anchor.Offset,+ SemanticEdgeAnchorKind.FromEnd=>length-parsed.Delta.Anchor.Offset-span,+ SemanticEdgeAnchorKind.CenteredAt=>parsed.Delta.Anchor.Offset-span/2d,+ _=>double.NaN+ };+ if(start< -1e-8||start+span>length+1e-8)+ return Fail("sheetmetal-profile-delta-outside",$"ProfileDelta '{parsed.Delta.StableId}' lies outside '{parsed.OwnerPath}'.");+ var region=owner.Groups["region"].Value;+ var path=$"{region}.{parsed.Delta.StableId}";+ profileDeltas.Add(new(path,region,"Outer",parsed.Delta with { StableId=path,Name=parsed.Delta.Name,+ Levels=parsed.Delta.Levels.Select(level=>level with { StableId=$"{path}.{level.Name}" }).ToArray(),+ Members=parsed.Delta.Members.Select(member=>member with { StableId=$"{path}.{member.Name}",ExposeAs=member.ExposeAs is null?null:$"{path}.{member.ExposeAs.Split('.').Last()}" }).ToArray() }));+ foreach(var exposure in parsed.Exposures)+ {+ var publicName=exposure.Path.Split('.').Last();var publicPath=$"{region}.{publicName}";+ var exposureSpan=exposure.EndU-exposure.StartU;var exposureCenter=start+(exposure.StartU+exposure.EndU)/2d;+ if(exposureSpan<=1e-8||Math.Abs(exposure.Offset)<=1e-8)+ return Fail("sheetmetal-profile-delta-exposure",$"ProfileDelta exposure '{publicPath}' must be a non-zero inset span.");+ if(!exposure.Capabilities.Contains("FlangeAttachable",StringComparer.OrdinalIgnoreCase))+ return Fail("sheetmetal-profile-delta-capability",$"ProfileDelta exposure '{publicPath}' must explicitly include FlangeAttachable.");+ attachmentPaths.Add(new(publicPath,region,"Outer",Math.Abs(exposure.Offset),exposureSpan,exposureCenter-length/2d,false,path,$"{path}.{exposure.MemberPath.Split('.').Last()}"));+ }+ }foreach(var flange in flanges){var attachment=attachmentPaths.SingleOrDefault(x=>x.Path.Equals($"{flange.ParentRegion}.{flange.EdgeName}",StringComparison.OrdinalIgnoreCase));@@ -180,7 +218,7 @@ internal static class SheetMetalSemanticLayoutParserfor(var i=0;i<count;i++){var member=$"{path}[{i}]";var offset=i-(count-1)/2d;- generated.Add(new(member,region,kind,center.X+offset*pitch.X,center.Y+offset*pitch.Y,diameter,width,length));members.Add(member);+ generated.Add(new(member,region,kind,center.X+offset*pitch.X,center.Y+offset*pitch.Y,diameter,width,length,kind==SheetFeatureKind.Slot));members.Add(member);}patterns.Add(new(path,block.Name,region,kind,count,center.X,center.Y,pitch.X,pitch.Y,diameter,width,length,members));constraints.Add(new($"{path}.EqualPitch",SheetMetalSemanticConstraintKind.EqualPitch,members,"Satisfied",$"generated at pitch ({pitch.X:G9} mm, {pitch.Y:G9} mm)"));@@ -229,7 +267,7 @@ internal static class SheetMetalSemanticLayoutParserconstraints.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(),attachmentPaths.OrderBy(x=>x.Path,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(),profileDeltas.OrderBy(x=>x.Path,StringComparer.Ordinal).ToArray()),generated,diagnostics);SheetMetalSemanticLayoutParseResult Fail(string code,string message)=>new(false,SheetMetalSemanticLayout.Empty,[],[new(code,SheetMetalDiagnosticSeverity.Error,message)]);}diff --git a/docs/language/generic-profile-modifications-m10.md b/docs/language/generic-profile-modifications-m10.mdnew file mode 100644index 00000000..5100e877--- /dev/null+++ b/docs/language/generic-profile-modifications-m10.md@@ -0,0 +1,56 @@+# Generic profile modifications (M10)++M10 adds `ProfileDelta` as the semantic substrate below user-programmed profile+features. A delta is a bounded program in one named carrier's local `u/v` frame:++- `Level` names a persistent offset from the carrier.+- `Span` advances at the current named level.+- `Transition` changes level by `Diagonal`, zero-run `Step`, or radius-checked+ exact `Round` geometry. `Concave: true` selects the alternate bounded circular+ solution for an inward/re-entrant profile corner; omission retains the default+ convex solution.+- `Anchor` places the bounded program with `FromStart`, `FromEnd`, or `CenteredAt`.+- `Expose` publishes a named span with explicit capabilities such as+ `FlangeAttachable`.++The exact line descendants are derived by the resolver. Authors do not sequence+anonymous global points or SVG-style commands. Programs must return to the carrier;+impossible levels, open programs, duplicate identities, invalid transitions, corner+consumption conflicts, and overlapping delta domains are rejected before BRep+materialization.++Ordinary typed Firmament templates specialize `ProfileDelta`:++```firmament+Template < P: RecessSpec, Owner: ProfilePath >+ProfileDelta Recess {+ On: Owner;+ Anchor: CenteredAt P.Center;+ Side: Inward;+ Level Carrier { Offset: 0mm; }+ Level Deep { Offset: P.Depth; }+ Transition Enter { Kind: Diagonal; Run: P.Lead; To: Deep; }+ Span Floor { Run: P.Width; At: Deep; }+ Transition Exit { Kind: Diagonal; Run: P.Lead; To: Carrier; }+}++ProfileDelta MyUnknownFeature = Recess < P: Chosen, Owner: Plate.Bottom >+```++`ProfilePath` is a typed template value, not a macro string. Template expansion+still occurs in the existing Firmament specialization pass. The kernel dispatches+only on `ProfileDelta`, levels, spans, and transitions; it contains no branch for+`Recess`, `Tab`, the specialization name, or CTC-03.++`Use Profile.Modifications;` loads the embedded generic `Recess<T>` and `Tab<T>`+library. User-authored templates use the same mechanism and can introduce names the+compiler has never seen. The canonical ordinary-extrusion dogfood is+`fixtures/FirmamentV2/Canonical/valid/profile-template-delta-extrusion.firmament`;+the Sheet Metal library dogfood is+`fixtures/FirmamentV2/SheetMetal/m10-profile-delta-recess.firmament`.++Sheet Metal consumes the same resolved delta on a flange `Outer` carrier. Delta,+level, member, exposed attachment, formed-region, and flat-region paths retain stable+correspondence. A child flange may consume an exposed `FlangeAttachable` land; because+that land is already physical owner-boundary geometry, no second release/removal is+created.diff --git a/docs/modules/sheet-metal.md b/docs/modules/sheet-metal.mdindex 4c963134..9c1fb9b3 100644--- a/docs/modules/sheet-metal.md+++ b/docs/modules/sheet-metal.md@@ -18,6 +18,14 @@ SheetMetalPartIr`PlanarContour2` is shared with normal Firmament Profiles. It owns one ordered outer loop, ordered inner loops, a plane frame, stable IDs, and segment provenance. Supported native curves are line segments, bounded circular arcs, and full circles. Validation rejects open chains, endpoint mismatches, duplicate IDs, wrong winding, self-intersection, invalid inner-loop nesting, and zero-length/zero-area topology.+Semantic `Pattern Feature: Slot` accepts either orientation: the smaller of `Length`/`Width` is the+rounded-end diameter and the larger is the tangent-to-tangent straight span. The+resulting capsule's overall major span is their sum; its two semicircular ends remain+analytic in formed BRep, flat STEP, and SVG rather than being reduced to a rectangular+opening. Direct legacy `Cut ... Profile: Slot` remains on its established rectangular+compatibility lowering until its dimension contract can be migrated without changing+existing fixtures.+The bounded kernel publishes line/line, line/arc, and arc/arc intersection; normalized-parameter split/trim; explicit-side line/arc offset with miter joins; and known-topology arrangement/stitching. It does not expose a universal arbitrary Boolean or silently polygonize analytic curves.## Authoring and Concept Paths@@ -115,6 +123,8 @@ Canonical M4 dogfood is [`m4-psu-enclosure.firmament`](../../fixtures/FirmamentVThe [M8 CTC-03 evidence bundle](sheetmetal/artifacts/m8/README.md) records full opening recovery, semantic-layout authoring, independent regeneration, comparison, PMI evidence, generalization, timings, and the remaining outer-contour blocker.+The [M10 generic profile-programming report](sheetmetal/artifacts/m10/README.md) documents typed `ProfileDelta` template specialization, reusable `Tab<T>`/`Recess<T>` library dogfood, the materialized CTC-03 right-wall service profile, and the remaining non-right-wall contour residuals.+The [recognized-import recovery M1 report](sheetmetal/artifacts/recovery-m1/README.md) separates detected bend candidates from accepted recognition authority and adds direct imported-body geometric mid-surface unfolding. Its CTC-03 run preserves exact per-region line/arc contours, all 17 source openings, seven bend lines, and source edge ancestry before any native reconstruction. Exact single-loop stitching remains partial at three source point-tangent junctions and is reported as such.## Bounded capability verdictdiff --git a/docs/modules/sheetmetal/artifacts/m10/README.md b/docs/modules/sheetmetal/artifacts/m10/README.mdnew file mode 100644index 00000000..87772847--- /dev/null+++ b/docs/modules/sheetmetal/artifacts/m10/README.md@@ -0,0 +1,92 @@+# Sheet Metal M10 — generic profile programming++Status: **meaningful progression**. The requested generic programming substrate and+the motivating CTC-03 right-wall service profile work through the real authored,+formed, flat, exact-blank, STEP, and comparison paths. CTC-03 as a whole remains+`NeedsReview`; this report does not call it complete.++## What changed++- Existing typed `Template <...>` specialization now accepts `ProfileDelta` targets+ and the typed `ProfilePath` value.+- `SemanticProfileDeltaIr` carries named local levels, ordered semantic members,+ bounded carrier ownership, polarity through inward/outward side, stable descendant+ identities, and exposed-path capabilities.+- The shared semantic-edge resolver supplies deterministic placement, untouched+ carriers, overlap/corner conflict rejection, exact descendants, and provenance.+- Ordinary Profile extrusion and Sheet Metal use the same IR/resolver.+- The embedded `Use Profile.Modifications;` library supplies generic `Tab<T>` and+ `Recess<T>` examples.+- CTC-03's user template constructs both the full right-wall recessed outline and+ `RightWall.ServiceFlangeAttachment`; the compiler contains no CTC/recess feature+ switch.+- The review corrections use the same substrate for two R12.7 service-tab rounds,+ two rear and four front R6.35 mounting-recess rounds. Authored `Slot` features now+ remain analytic capsules through formed BRep, flat STEP, and SVG materialization.+- The four base-flange `Auto` relief requests were removed from this source because+ the recovered blank has open stitched corners, not separate relief cut loops.++## CTC-03 evidence++The canonical source remains+[`../m8/ctc03-final.firmament`](../m8/ctc03-final.firmament), now advanced to the+M10 program while preserving its source-independent construction contract.++- formed STEP: `artifacts/sheetmetal-m10-review/ctc03-m10-formed.step`+- flat STEP/SVG: `artifacts/sheetmetal-m10-review/ctc03-m10-flat.step` and `.svg`+- exact flat status: `Valid`; exact blank and DFM exact-contour checks pass+- topology: one closed body/shell, 15 semantic regions, seven bends, 17 openings+- attachment: 127 mm at 2.6416 mm inset and 2.3876 mm span offset+- all seven bend comparisons and all 17 opening comparisons pass+- two vent profiles contain exact R9.525 semicircular ends; the empty SVG+ `corner-reliefs` group confirms that no extra corner cuts are emitted++The first M10 review and the corrected review compare as follows. The corrections+remove the visible false details; the point-sampled global statistic is not monotonic+because removing four false relief vertices and adding analytic arcs changes both+sample populations.++| Direction | First M10 review RMS / p95 / max (mm) | Corrected M10 RMS / p95 / max (mm) |+|---|---:|---:|+| source → native | 3.286634 / 8.941152 / 9.141310 | 3.546889 / 8.941152 / 9.141310 |+| native → source | 2.790436 / 8.940881 / 12.735724 | 2.667873 / 6.423564 / 8.940881 |++Flat comparison also improved:++| Direction | First M10 review RMS / p95 / max (mm) | Corrected M10 RMS / p95 / max (mm) |+|---|---:|---:|+| source → native | 2.816233 / 5.667441 / 10.563949 | 2.954972 / 8.901978 / 9.094054 |+| native → source | 3.178755 / 6.976011 / 13.258954 | 2.472902 / 4.548127 / 8.945418 |++Width/height residuals remain only 0.002447/0.007820 mm.++## Honest remaining limitation++The global flat comparison is still `NeedsReview`. Eight recovered source-region+outer contours retain localized residuals from 0.972277 to 9.09405 mm, led by+`region-p-0065-0069.Outer`. The visible review targets are now materialized, but the+sampled historical per-region boundaries still differ at shared/released edges.+Therefore M10 completes the generic substrate and this review's explicit corrections,+but not full CTC-03 geometric parity.++The generic `aetheris validate` entry point still routes this module-shaped source to+an older parser fallback and reports `firmament-v2-phase3-edge-finish-syntax-invalid`.+The authoritative Sheet Metal `build`, `inspect`, `paths`, and `flatten` paths all+recognize and materialize it. This command-routing inconsistency remains open and is+not treated as a geometry failure.++## Follow-up profile/corner review++`Round` transitions now admit `Concave: true`. The front mounting recess uses it on+the two re-entrant inner transitions, and the rear mounting recess uses it on both+transitions. All six mounting-recess arc directions now match the recovered CTC-03+contours. Exact blank construction composes material attachments in bend-graph order+and splices authored regions along their shared analytic bend edge; nested through-cuts+become inner loops directly. This preserves the concave outline while keeping exact+flat STEP generation valid.++TODO: add partial base-edge attachment/root-trim programs. The four deck/wall junction+spikes cannot be removed faithfully with current flange-outer `ProfileDelta`, endpoint+`CornerProfile`, or automatic relief operations: `Auto` produces separate diagonal+relief cuts that do not exist in the recovered blank. Partial base attachment paths+must own those shared-edge trims.diff --git a/docs/modules/sheetmetal/artifacts/m8/ctc03-final.firmament b/docs/modules/sheetmetal/artifacts/m8/ctc03-final.firmamentindex b0558c1c..d7f616b1 100644--- a/docs/modules/sheetmetal/artifacts/m8/ctc03-final.firmament+++ b/docs/modules/sheetmetal/artifacts/m8/ctc03-final.firmament@@ -1,6 +1,92 @@-// M8 independent reconstruction of NIST CTC-03.+// M10 independent reconstruction of NIST CTC-03.// Construction reads no STEP, recovery provider, face ID, edge ID, or recovered polygon.// Dimensions below are source-derived unless explicitly described as a flattening policy.+Record CtcServiceRecessSpec {+ Center: Length+ Lead: Length+ Run: Length+ Depth: Length+ AttachmentInset: Length+ AttachmentSpan: Length+}++Template < P: CtcServiceRecessSpec, Owner: ProfilePath >+ProfileDelta CtcServiceRecess {+ On: Owner;+ Anchor: CenteredAt P.Center;+ Side: Inward;+ Level Carrier { Offset: 0mm; }+ Level Deep { Offset: P.Depth; }+ Level Attachment { Offset: P.AttachmentInset; }+ Transition LeadIn { Kind: Diagonal; Run: P.Lead; To: Deep; }+ Span LeftRecessRun { Run: P.Run; At: Deep; }+ Transition RiseToAttachment { Kind: Step; To: Attachment; }+ Span AttachmentLand { Run: P.AttachmentSpan; At: Attachment; Expose: ServiceFlangeAttachment; Capabilities: [FlangeAttachable, BendAttachable, FeatureAttachable, StableSemanticIdentity]; }+ Transition FallFromAttachment { Kind: Step; To: Deep; }+ Span RightRecessRun { Run: P.Run; At: Deep; }+ Transition LeadOut { Kind: Diagonal; Run: P.Lead; To: Carrier; }+}++Static CtcServiceProfile: CtcServiceRecessSpec = CtcServiceRecessSpec {+ Center: 186.5376mm;+ Lead: 15.24mm;+ Run: 63.5mm;+ Depth: 15.24mm;+ AttachmentInset: 2.6416mm;+ AttachmentSpan: 127mm;+}++Record RoundedTabSpec { Center: Length Radius: Length Crown: Length Extension: Length }+Template < P: RoundedTabSpec, Owner: ProfilePath >+ProfileDelta RoundedTab {+ On: Owner;+ Anchor: CenteredAt P.Center;+ Side: Outward;+ Level Carrier { Offset: 0mm; }+ Level Extended { Offset: P.Extension; }+ Transition EnterRound { Kind: Round; Run: P.Radius; To: Extended; Radius: P.Radius; }+ Span Crown { Run: P.Crown; At: Extended; }+ Transition ExitRound { Kind: Round; Run: P.Radius; To: Carrier; Radius: P.Radius; }+}+Static ServiceConnectorSpec: RoundedTabSpec = RoundedTabSpec { Center: 63.5mm; Radius: 12.7mm; Crown: 101.6mm; Extension: 12.7mm; }++Record TwoRoundRecessSpec { Center: Length Radius: Length Floor: Length Shoulder: Length Depth: Length }+Template < P: TwoRoundRecessSpec, Owner: ProfilePath >+ProfileDelta TwoRoundRecess {+ On: Owner;+ Anchor: CenteredAt P.Center;+ Side: Inward;+ Level Carrier { Offset: 0mm; }+ Level Shoulder { Offset: P.Shoulder; }+ Level Deep { Offset: P.Depth; }+ Transition EnterShoulder { Kind: Step; To: Shoulder; }+ Transition EnterRound { Kind: Round; Run: P.Radius; To: Deep; Radius: P.Radius; Concave: true; }+ Span Floor { Run: P.Floor; At: Deep; }+ Transition ExitRound { Kind: Round; Run: P.Radius; To: Shoulder; Radius: P.Radius; Concave: true; }+ Transition ExitShoulder { Kind: Step; To: Carrier; }+}+Static RearConnectorSpec: TwoRoundRecessSpec = TwoRoundRecessSpec { Center: 120.65mm; Radius: 6.35mm; Floor: 114.3mm; Shoulder: 25.4mm; Depth: 31.75mm; }++Record FourRoundRecessSpec { Center: Length Radius: Length Floor: Length OuterShoulder: Length InnerShoulder: Length Depth: Length }+Template < P: FourRoundRecessSpec, Owner: ProfilePath >+ProfileDelta FourRoundRecess {+ On: Owner;+ Anchor: CenteredAt P.Center;+ Side: Inward;+ Level Carrier { Offset: 0mm; }+ Level OuterShoulder { Offset: P.OuterShoulder; }+ Level InnerShoulder { Offset: P.InnerShoulder; }+ Level Deep { Offset: P.Depth; }+ Transition EnterOuterRound { Kind: Round; Run: P.Radius; To: OuterShoulder; Radius: P.Radius; }+ Transition EnterShoulder { Kind: Step; To: InnerShoulder; }+ Transition EnterInnerRound { Kind: Round; Run: P.Radius; To: Deep; Radius: P.Radius; Concave: true; }+ Span Floor { Run: P.Floor; At: Deep; }+ Transition ExitInnerRound { Kind: Round; Run: P.Radius; To: InnerShoulder; Radius: P.Radius; Concave: true; }+ Transition ExitShoulder { Kind: Step; To: OuterShoulder; }+ Transition ExitOuterRound { Kind: Round; Run: P.Radius; To: Carrier; Radius: P.Radius; }+}+Static FrontConnectorSpec: FourRoundRecessSpec = FourRoundRecessSpec { Center: 120.65mm; Radius: 6.35mm; Floor: 114.3mm; OuterShoulder: 6.35mm; InnerShoulder: 25.4mm; Depth: 31.75mm; }+Concept Ctc03ManufacturedIntent {MainDeck: SheetRegionBaseFastenerPattern: SheetPattern@@ -14,52 +100,24 @@ 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;- }+ // One user-programmed semantic construction owns the complete right-wall+ // recess and exposes its central land as the child-flange attachment path.+ ProfileDelta RightWallServiceProfile = CtcServiceRecess < P: CtcServiceProfile, Owner: RightWall.Outer >// 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); }Datum ServiceHoleCenter { On: AngledServiceFlange; At: (63.5mm, 30.735796052mm); }- // Source contour: the 127 mm partial flange grows a centered 101.6 x 12.7 mm tab.- Tab ServiceConnectorTab {- On: AngledServiceFlange.Outer;- Center: 63.5mm;- Width: 101.6mm;- Extension: 12.7mm;- }+ // Source contour: the 127 mm partial flange grows a centered 101.6 mm tab+ // through two tangent R12.7 transitions rather than sharp shoulders.+ ProfileDelta ServiceConnectorProfile = RoundedTab < P: ServiceConnectorSpec, Owner: AngledServiceFlange.Outer >- // Source free-edge programs. Both are symmetric bounded removals from the- // mounting-flange outer carrier; carrier spans are generated by the compiler.- SteppedNotch FrontConnectorRelief {- On: FrontMountingFlange.Outer;- Center: 120.65mm;- Width: 127mm;- Depth: 31.75mm;- ShoulderDepth: 25.4mm;- OuterChamfer: 0mm;- InnerChamfer: 6.35mm;- Side: Inward;- }+ // Source free-edge programs. These retain the vertical shoulders while+ // expressing the six tangent R6.35 transitions visible in the recovered blank.+ ProfileDelta RearConnectorRelief = TwoRoundRecess < P: RearConnectorSpec, Owner: RearMountingFlange.Outer >- SteppedNotch RearConnectorRelief {- On: RearMountingFlange.Outer;- Center: 120.65mm;- Width: 139.7mm;- Depth: 31.75mm;- ShoulderDepth: 25.4mm;- OuterChamfer: 6.35mm;- InnerChamfer: 6.35mm;- Side: Inward;- }+ ProfileDelta FrontConnectorRelief = FourRoundRecess < P: FrontConnectorSpec, Owner: FrontMountingFlange.Outer >// Cross-edge region-profile corners. Each operation consumes the named// side-edge endpoint and the adjacent Outer-edge endpoint as one feature.@@ -163,10 +221,10 @@ SheetMetal Ctc03 : Ctc03ManufacturedIntent {Origin: (-241.3mm, 58.08726mm, 76.2mm);}- 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: 31.75254mm; Angle: 90deg; Radius: 6.35mm; Direction: Up; Relief: Auto; }+ Flange FrontWall { From: MainDeck.Front; Height: 61.59254mm; Angle: 90deg; Radius: 6.35mm; Direction: Down; }+ Flange RearWall { From: MainDeck.Rear; Height: 61.59254mm; Angle: 90deg; Radius: 6.35mm; Direction: Down; }+ Flange LeftWall { From: MainDeck.Left; Height: 44.45mm; Angle: 90deg; Radius: 6.35mm; Direction: Up; }+ Flange RightWall { From: MainDeck.Right; Height: 31.75254mm; Angle: 90deg; Radius: 6.35mm; Direction: Up; }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; }diff --git a/fixtures/FirmamentV2/Canonical/valid/profile-template-delta-extrusion.firmament b/fixtures/FirmamentV2/Canonical/valid/profile-template-delta-extrusion.firmamentnew file mode 100644index 00000000..39e97096--- /dev/null+++ b/fixtures/FirmamentV2/Canonical/valid/profile-template-delta-extrusion.firmament@@ -0,0 +1,33 @@+Model ProfileDeltaPlate {+ Units: mm++ Record LocalRecessSpec { Center: Length Lead: Length Run: Length Depth: Length Land: Length }+ Template < P: LocalRecessSpec, Owner: ProfilePath >+ ProfileDelta LocalRecess {+ On: Owner;+ Anchor: CenteredAt P.Center;+ Side: Inward;+ Level Carrier { Offset: 0mm; }+ Level Recessed { Offset: P.Depth; }+ Transition LeadIn { Kind: Diagonal; Run: P.Lead; To: Recessed; }+ Span LeftRun { Run: P.Run; At: Recessed; }+ Span Land { Run: P.Land; At: Recessed; }+ Span RightRun { Run: P.Run; At: Recessed; }+ Transition LeadOut { Kind: Diagonal; Run: P.Lead; To: Carrier; }+ }++ Static PlateRecess: LocalRecessSpec = LocalRecessSpec {+ Center: 50mm;+ Lead: 5mm;+ Run: 8mm;+ Depth: 6mm;+ Land: 20mm;+ }++ Concept Struct Layout On XY {+ Rect2 PlateBase { Center: [50mm, 20mm]; Size: [100mm, 40mm]; }+ }+ ProfileDelta UserDefinedCableRelief = LocalRecess < P: PlateRecess, Owner: PlateBase.Bottom >+ Profile Plate From PlateBase+ Struct PlateBody { Extrude Solid { Profile: Plate; From: 0mm; To: 3mm; } }+}diff --git a/fixtures/FirmamentV2/SheetMetal/m10-profile-delta-recess.firmament b/fixtures/FirmamentV2/SheetMetal/m10-profile-delta-recess.firmamentnew file mode 100644index 00000000..3982c1fe--- /dev/null+++ b/fixtures/FirmamentV2/SheetMetal/m10-profile-delta-recess.firmament@@ -0,0 +1,17 @@+Use Profile.Modifications;++Static WallRecess: ProfileRecessSpec = ProfileRecessSpec {+ Center: 60mm;+ Lead: 6mm;+ Run: 10mm;+ Depth: 8mm;+ Land: 40mm;+}++ProfileDelta UserDefinedWallRecess = Recess < P: WallRecess, Owner: Wall.Outer >++SheetMetal DeltaTray {+ Thickness: 1mm;+ Base Deck { Profile: Rectangle { Width: 120mm; Height: 80mm; }; }+ Flange Wall { From: Deck.Front; Height: 20mm; Angle: 90deg; Radius: 2mm; }+}