Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Expose immutable Profile boundary edit evidence

Yuechen Li392ce79dd04b
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index 0919a1cf..7ae8c4fa 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -576,6 +576,7 @@ public static class CliRunner
SectionChainMaterializationResult materialized;
SectionChain chain;
IReadOnlyList<SectionChainProfileDerivation>? profileDerivations = null;
+ IReadOnlyList<SectionChainBoundaryEditInspection>? boundaryEdits = null;
if (File.Exists(witness))
{
var authored = SectionChainAuthoringParser.CompileFile(witness);
@@ -587,6 +588,7 @@ public static class CliRunner
}
chain = authored.Chain; materialized = authored.Materialization;
profileDerivations = authored.ProfileDerivations;
+ boundaryEdits = authored.BoundaryEdits;
}
else
{
@@ -614,6 +616,7 @@ public static class CliRunner
{
command = $"section-chain {operation}", success = true, chain.StableId,
profileDerivations,
+ boundaryEdits,
sections = chain.Sections.Select(section => new { section.SectionId, section.Frame, profile = section.Profile.StableId, spans = section.Profile.Spans.Select(span => span.SpanId), seam = section.Profile.SeamSpanId }),
chain.Correspondence,
resolvedCorrespondence = Enumerable.Range(0, chain.Sections.Count - 1).Select(index => new
diff --git a/Aetheris.Kernel.Firmament.Tests/ProfileBoundaryAuthoringTests.cs b/Aetheris.Kernel.Firmament.Tests/ProfileBoundaryAuthoringTests.cs
new file mode 100644
index 00000000..e13d868b
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/ProfileBoundaryAuthoringTests.cs
@@ -0,0 +1,149 @@
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.Materializer;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class ProfileBoundaryAuthoringTests
+{
+ private const string Panel = """
+ Model Test {
+ Units: mm
+ Rect2 Blank { Center: [0mm,0mm]; Size: [120mm,80mm] }
+ Profile Original { Loop Outer { Blank |> TraceLoop } }
+ Profile Panel {
+ From: Blank
+ Replace Grip {
+ On: Blank.Right
+ Range: [20mm,60mm]
+ Through: [[48mm,-10mm], [48mm,10mm]]
+ Join: Tangent
+ }
+ }
+ Extrude Body { Profile: Panel From: 0mm To: 3mm }
+ }
+ """;
+
+ [Fact]
+ public void DerivationPreservesSeedAndMaterializesThroughTheRealCompiler()
+ {
+ var original = ProfileAuthoringParser.ResolveNamedProfile(Panel, "Original", out var originalErrors);
+ var derived = ProfileAuthoringParser.ResolveNamedProfile(Panel, "Panel", out var errors);
+ Assert.Empty(originalErrors); Assert.Empty(errors); Assert.NotNull(derived);
+ Assert.Equal(9600, ResolvedProfile2DValidator.Validate(original!).SignedArea, 7);
+ Assert.True(ResolvedProfile2DValidator.Validate(derived).SignedArea < 9600);
+ Assert.Equal(8, derived.Loops[0].Segments.Count);
+ var curves = derived.Loops[0].Segments.Where(s => s.Geometry is LineArcCubicBezier2D).ToArray();
+ Assert.Equal(3, curves.Length);
+ var first = (LineArcCubicBezier2D)curves[0].Geometry;
+ Assert.Equal((60d, -20d), first.Start);
+ Assert.Equal(first.Start.X, first.Control1.X);
+ Assert.Single(derived.BoundaryEdits!);
+ var build = FirmamentBuildAndExport.CompileSource(Panel);
+ Assert.True(build.IsSuccess, string.Join("\n", build.Diagnostics));
+ }
+
+ [Theory]
+ [InlineData("Range: [20mm,60mm]", "Range: [-1mm,60mm]", "profile-edit-range-invalid")]
+ [InlineData("On: Blank.Right", "On: Blank.Missing", "profile-edit-target-missing")]
+ [InlineData("Join: Tangent", "Join: Tangent; Join: Position", "profile-edit-field-invalid")]
+ [InlineData("Join: Tangent", "StartTangent: [0,0]", "profile-edit-tangent-invalid")]
+ [InlineData("Through: [[48mm,-10mm], [48mm,10mm]]", "Through: [[60mm,-20mm]]", "profile-edit-knots-invalid")]
+ [InlineData("Through: [[48mm,-10mm], [48mm,10mm]]", "Through: [[48deg,-10mm]]", "profile-edit-vector-invalid")]
+ [InlineData("Join: Tangent", "Equation: t => t", "profile-edit-field-invalid")]
+ [InlineData("From: Blank", "From: Panel", "concept-profile-dependency-cycle")]
+ [InlineData("Through: [[48mm,-10mm], [48mm,10mm]]", "Through: [[-100mm,0mm]]", "profile-edit-self-intersection")]
+ [InlineData("Range: [20mm,60mm]", "Range: [0mm,80mm]", "profile-edit-join-mismatch")]
+ public void InvalidEditsFailBeforeMaterialization(string before, string after, string diagnostic)
+ {
+ var profile = ProfileAuthoringParser.ResolveNamedProfile(Panel.Replace(before, after), "Panel", out var errors);
+ Assert.Null(profile); Assert.Contains(errors, e => e.Contains(diagnostic, StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void OverlapIsRejectedAndDisjointEditOrderDoesNotChangeGeometry()
+ {
+ const string second = "Replace Other { On: Blank.Right; Range: [30mm,70mm]; Through: [[50mm,0mm]] }";
+ var source = Panel.Replace("From: Blank", "From: Blank\n" + second);
+ Assert.Null(ProfileAuthoringParser.ResolveNamedProfile(source, "Panel", out var errors));
+ Assert.Contains(errors, e => e.StartsWith("profile-edit-overlap:"));
+ const string disjoint = "Replace LeftGrip { On: Blank.Left; Through: [[-50mm,0mm]] }";
+ var a = ProfileAuthoringParser.ResolveNamedProfile(Panel.Replace("From: Blank", "From: Blank\n" + disjoint), "Panel", out var ae);
+ var b = ProfileAuthoringParser.ResolveNamedProfile(Panel.Replace("Join: Tangent\n }", "Join: Tangent\n }\n" + disjoint), "Panel", out var be);
+ Assert.Empty(ae); Assert.Empty(be);
+ Assert.Equal(a!.Loops[0].Segments.Select(s => s.Geometry), b!.Loops[0].Segments.Select(s => s.Geometry));
+ }
+
+ [Fact]
+ public void AppliedDeltaAndFurtherDerivationKeepNamedDescendants()
+ {
+ const string source = """
+ Rect2 Blank { Center: [0mm,0mm]; Size: [120mm,80mm] }
+ ProfileDelta ServiceTab {
+ On: Blank.Top; Anchor: CenteredAt 60mm; Side: Outward;
+ Level Carrier { Offset: 0mm; }
+ Level Extended { Offset: 8mm; }
+ Transition Enter { Kind: Step; To: Extended; }
+ Span Crown { Run: 24mm; At: Extended; }
+ Transition Exit { Kind: Step; To: Carrier; }
+ }
+ Profile Panel { From: Blank; Apply ServiceTab }
+ Profile Finished { From: Panel; Replace Rounded {
+ On: Panel.ServiceTab.Crown; Through: [[0mm,52mm]]
+ } }
+ """;
+ var result = ProfileAuthoringParser.ResolveNamedProfile(source, "Finished", out var errors);
+ Assert.Empty(errors); Assert.NotNull(result);
+ Assert.Contains(result.Loops[0].Segments, s => s.Name == "Rounded_Span0");
+ Assert.DoesNotContain(result.Loops[0].Segments, s => s.Name == "ServiceTab.Crown");
+ var panel = ProfileAuthoringParser.ResolveNamedProfile(source, "Panel", out var panelErrors);
+ Assert.Empty(panelErrors);
+ Assert.Equal(9600 + 24 * 8, ResolvedProfile2DValidator.Validate(panel!).SignedArea, 7);
+ }
+
+ [Fact]
+ public void ExplicitDerivativesConstructExactCubics()
+ {
+ var source = Panel.Replace("Join: Tangent", "Derivatives: [[0mm,20mm], [-10mm,15mm], [10mm,15mm], [0mm,20mm]]");
+ var result = ProfileAuthoringParser.ResolveNamedProfile(source, "Panel", out var errors);
+ Assert.Empty(errors); Assert.NotNull(result);
+ var cubic = Assert.IsType<LineArcCubicBezier2D>(result.Loops[0].Segments.Single(s => s.Name == "Grip_Span0").Geometry);
+ Assert.Equal(-20 + 20d / 3, cubic.Control1.Y, 10);
+ Assert.Equal("ExplicitHermite", result.BoundaryEdits![0].Construction);
+ }
+
+ [Theory]
+ [InlineData("[[-270mm,300mm],[270mm,300mm]]", "profile-edit-self-intersection")]
+ [InlineData("[[0mm,200mm],[0mm,200mm]]", "profile-edit-cusp")]
+ public void IndividualCubicLoopsAndRetracingAreRejected(string derivatives, string diagnostic)
+ {
+ var source = Panel.Replace("Through: [[48mm,-10mm], [48mm,10mm]]", "Through: []")
+ .Replace("Join: Tangent", "Derivatives: " + derivatives);
+ Assert.Null(ProfileAuthoringParser.ResolveNamedProfile(source, "Panel", out var errors));
+ Assert.Contains(errors, e => e.StartsWith(diagnostic + ":"));
+ }
+
+ [Fact]
+ public void LibraryTemplateFixtureBuildsAndSeedCommentsAreAccepted()
+ {
+ var path = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/Boundary2/edited-panel.firmament");
+ var source = File.ReadAllText(path);
+ var profile = ProfileAuthoringParser.ResolveNamedProfile(source, "Panel", out var errors);
+ Assert.Empty(errors); Assert.NotNull(profile);
+ Assert.Equal(2, profile.BoundaryEdits!.Count);
+ var compiled = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(compiled.IsSuccess, string.Join("\n", compiled.Diagnostics));
+ Assert.NotNull(ProfileAuthoringParser.ResolveNamedProfile(Panel.Replace("From: Blank", "// closed seed\n From: Blank"), "Panel", out errors));
+ Assert.Empty(errors);
+ }
+
+ [Theory]
+ [InlineData("Circle2 Blank { Center: [0mm,0mm]; Radius: 10mm }")]
+ [InlineData("Ellipse2 Blank { Center: [0mm,0mm]; AxisLengths: [20mm,30mm] }")]
+ public void PeriodicSeedsAreValuesButCurvedReplacementIsNotAdmitted(string seed)
+ {
+ Assert.NotNull(ProfileAuthoringParser.ResolveNamedProfile(seed + "\nProfile P { From: Blank }", "P", out var errors));
+ Assert.Empty(errors);
+ Assert.Null(ProfileAuthoringParser.ResolveNamedProfile(seed + "\nProfile P { From: Blank; Replace X { On: Blank.Boundary; Through: [[1mm,1mm]] } }", "P", out errors));
+ Assert.Contains(errors, e => e.StartsWith("profile-edit-curve-not-qualified:"));
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
index 2f4a1084..624cdd83 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
@@ -288,6 +288,7 @@ public static class FirmamentBuildAndExport
// parser admission alone is insufficient because the profile/composition
// materializers read source declarations directly.
var staticDiagnostics = new List<string>();
+ sourceText = ProfileModificationTemplateLibrary.ResolveImports(sourceText);
var boundaryExpansion = ClosedBoundary2Authoring.Expand(sourceText, staticDiagnostics);
if (boundaryExpansion is null)
{
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs
index f0581b31..66f9d061 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs
@@ -59,6 +59,23 @@ internal static class ClosedBoundary2Authoring
foreach (var shape in shapes)
{
if (shape.LoweredSource is not null) changes.Add((shape.Start, shape.Length, shape.LoweredSource));
+ // Preserve a closed boundary value for immutable Profile derivation
+ // before the primitive declaration is erased to its ordinary guides.
+ var seedUses = Regex.Matches(source,
+ $@"\bProfile\s+\w+(?:\s+Using\s+\w+)?\s*\{{\s*From\s*:\s*(?:\w+\.)?(?<seed>{Regex.Escape(shape.Declaration.Name)})\b");
+ if (seedUses.Count > 0)
+ {
+ var valueName = "__Boundary2Value_" + shape.Declaration.Name;
+ if (Regex.IsMatch(source, $@"\bProfile\s+{Regex.Escape(valueName)}\b"))
+ diagnostics.Add(Prefix + "reserved-value-name:" + valueName);
+ foreach (Match use in seedUses)
+ {
+ // Include the optional Concept owner qualifier in replacement.
+ var field = Regex.Match(use.Value, @"From\s*:\s*(?<value>\w+(?:\.\w+)?)$");
+ changes.Add((use.Index + field.Groups["value"].Index, field.Groups["value"].Length, valueName));
+ }
+ changes.Add((source.Length, 0, $"\nProfile {valueName} {{ Loop Outer {{ {shape.TraceExpression} }} }}\n"));
+ }
foreach (Match trace in Regex.Matches(source, $@"\b{Regex.Escape(shape.Declaration.Name)}(?:\s+As\s+(?<alias>[A-Za-z_]\w*))?\s*\|>\s*TraceLoop\b", RegexOptions.CultureInvariant))
{
if (Inside(trace.Index, shapes) || InTemplate(trace.Index)) continue;
@@ -71,6 +88,7 @@ internal static class ClosedBoundary2Authoring
foreach (Match reference in Regex.Matches(source, $@"\b{Regex.Escape(shape.Declaration.Name)}\s*\.\s*{Regex.Escape(member.Key)}\b", RegexOptions.CultureInvariant))
if (!Inside(reference.Index, shapes) && !InTemplate(reference.Index)) changes.Add((reference.Index, reference.Length, member.Value));
}
+ if (diagnostics.Any(x => x.StartsWith(Prefix, StringComparison.Ordinal))) return null;
foreach (var change in changes.OrderByDescending(x => x.Start)) source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);
return new(source, shapes.Select(x => x.Declaration).ToArray());
}
@@ -145,7 +163,7 @@ internal static class ClosedBoundary2Authoring
var hasRadius = Length(body, "Radius", out var radius); var hasDiameter = Length(body, "Diameter", out var diameter);
if (hasRadius == hasDiameter || (radius = hasRadius ? radius : diameter / 2) <= 0) return Invalid(name, "invalid-dimensions", diagnostics);
var lowered = inline || hasDiameter ? $"Point2 {name}_Center {{ Position: [{N(c.X)}, {N(c.Y)}] }}\nConcept Circle2 {name}_Curve {{ Center: {name}_Center; Radius: {N(radius)} }}" : null;
- var guide = lowered is null ? name : name + "_Curve"; var map = new Dictionary<string, string>(StringComparer.Ordinal) { ["Center"] = inline || hasDiameter ? name + "_Center" : centerRef! };
+ var guide = lowered is null ? name : name + "_Curve"; var map = new Dictionary<string, string>(StringComparer.Ordinal) { ["Center"] = inline || hasDiameter ? name + "_Center" : centerRef!, ["Boundary"] = guide };
return Make(name, "Circle2", null, c, rotation, new Dictionary<string, double> { ["Radius"] = radius, ["Diameter"] = 2 * radius }, ["Center"], ["Boundary"], "Circle", span, lowered, map, guide + " |> TraceLoop", Math.PI * radius * radius, 2 * Math.PI * radius);
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptProfileDerivation.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptProfileDerivation.cs
index 45c05eec..f90b0ffd 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptProfileDerivation.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptProfileDerivation.cs
@@ -86,7 +86,7 @@ internal static class ConceptProfileDerivation
SourceSpan = $"offset:{profile.Index}", Derivation = FormattableString.Invariant($"ConceptBoundaryPlacement:source={from};translate={translate[0]:R},{translate[1]:R};rotate={rotate:R};scale={scale:R};pivot={pivot[0]:R},{pivot[1]:R}"),
SourceFrame = planeName, TracedFrom = segment.Provenance.StableId }));
}
- result = new(name, planeName, [new("Outer", true, segments)], plane);
+ result = new(name, planeName, [new("Outer", true, segments)], plane, BoundaryEdits: inherited.BoundaryEdits);
var validation = ResolvedProfile2DValidator.Validate(result);
diagnostics.AddRange(validation.Diagnostics);
if (diagnostics.Count != 0) result = null;
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index 71daaab1..a5e078c4 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -307,8 +307,7 @@ public static class FirmamentV2Parser
FirmamentV2ForgeConceptCatalog? 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);
+ sourceText = ProfileModificationTemplateLibrary.ResolveImports(sourceText);
var diagnostics = new List<string> { "firmament-v2-parser-invoked" };
var source = StripLineComments(sourceText);
var polygonExpansion = ClosedBoundary2Authoring.Expand(source, diagnostics);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
index 40d7b462..347200fa 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
@@ -53,10 +53,12 @@ public static class ProfileAuthoringParser
ArgumentException.ThrowIfNullOrWhiteSpace(profileName);
var diagnostics = new List<string>();
if (!visiting.Add(profileName)) { reportedDiagnostics = [$"concept-profile-dependency-cycle:{profileName}"]; return null; }
+ source = ProfileModificationTemplateLibrary.ResolveImports(source);
source = ExpandBuiltInPolygons(source, diagnostics);
var expansion = FirmamentV2TemplateExpansion.Expand(source, diagnostics);
if (expansion is not null) source = expansion.Source;
- if (ConceptProfileDerivation.TryResolve(source, profileName, visiting, diagnostics, out var derived))
+ if (ProfileBoundaryAuthoring.TryResolve(source, profileName, visiting, diagnostics, out var derived)
+ || ConceptProfileDerivation.TryResolve(source, profileName, visiting, diagnostics, out derived))
{
visiting.Remove(profileName);
reportedDiagnostics = diagnostics.Distinct(StringComparer.Ordinal).ToArray();
@@ -175,7 +177,8 @@ public static class ProfileAuthoringParser
if (profile is null)
return (null, 0, ["profile-source-missing-profile"]);
- if (ConceptProfileDerivation.TryResolve(source, profile.Name, new(StringComparer.Ordinal) { profile.Name }, diagnostics, out var conceptProfile))
+ if (ProfileBoundaryAuthoring.TryResolve(source, profile.Name, new(StringComparer.Ordinal) { profile.Name }, diagnostics, out var conceptProfile)
+ || ConceptProfileDerivation.TryResolve(source, profile.Name, new(StringComparer.Ordinal) { profile.Name }, diagnostics, out conceptProfile))
{
var depths = ResolveExtrude(source, profile.Name, diagnostics);
return (conceptProfile is null ? null : conceptProfile with { LocalStartDepth = depths.Start, LocalEndDepth = depths.End }, depths.Height, diagnostics);
@@ -204,8 +207,11 @@ public static class ProfileAuthoringParser
{
// This is the canonical semantic-profile adapter used by Compose and SectionChain.
// Its historical name remains source-compatible; pipeline syntax is erased here too.
+ source = ProfileModificationTemplateLibrary.ResolveImports(source);
source = ExpandBuiltInPolygons(source, diagnostics);
- var authoredProfiles = FindProfiles(source).Where(candidate => candidate.FromPath is not null || candidate.Body?.Contains("|>", StringComparison.Ordinal) == true).ToArray();
+ var templates = FirmamentV2TemplateExpansion.Expand(source, diagnostics);
+ if (templates is not null) source = templates.Source;
+ var authoredProfiles = FindProfiles(source).Where(candidate => candidate.FromPath is not null || candidate.Body?.Contains("|>", StringComparison.Ordinal) == true || ProfileBoundaryAuthoring.IsDerived(candidate.Body)).ToArray();
if (authoredProfiles.Length == 0) return new Dictionary<string, ResolvedProfile2D>();
var points = new Dictionary<string, (double X, double Y)>(StringComparer.Ordinal);
var guides = new Dictionary<string, LineArcProfileCurve2D>(StringComparer.Ordinal);
@@ -214,7 +220,8 @@ public static class ProfileAuthoringParser
var profiles = new Dictionary<string, ResolvedProfile2D>(StringComparer.Ordinal);
foreach (var profile in authoredProfiles)
{
- if (ConceptProfileDerivation.TryResolve(source, profile.Name, new(StringComparer.Ordinal) { profile.Name }, diagnostics, out var derived))
+ if (ProfileBoundaryAuthoring.TryResolve(source, profile.Name, new(StringComparer.Ordinal) { profile.Name }, diagnostics, out var derived)
+ || ConceptProfileDerivation.TryResolve(source, profile.Name, new(StringComparer.Ordinal) { profile.Name }, diagnostics, out derived))
{
if (derived is not null && !profiles.TryAdd(profile.Name, derived)) diagnostics.Add($"profile-duplicate:{profile.Name}");
continue;
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileBoundaryAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileBoundaryAuthoring.cs
new file mode 100644
index 00000000..4d8168a5
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileBoundaryAuthoring.cs
@@ -0,0 +1,351 @@
+using System.Globalization;
+using System.Text.RegularExpressions;
+using Aetheris.Kernel.Firmament.Materializer;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2;
+
+public sealed record ProfileBoundaryEditEvidence(string Name, string SourceMember, double From, double To,
+ string Construction, IReadOnlyList<string> Descendants, string SourceSpan);
+
+// Construction is a typed compile-time value, not an executable delegate. Future
+// equation curves must pass their own purity/admissibility gate before producing
+// this same bounded exact curve representation.
+internal abstract record ProfileCurveConstruction;
+internal sealed record ProfileThroughConstruction(IReadOnlyList<(double X, double Y)> Points,
+ IReadOnlyList<(double X, double Y)>? Derivatives, (double X, double Y)? StartTangent,
+ (double X, double Y)? EndTangent, bool MatchTangent) : ProfileCurveConstruction;
+
+/// <summary>Immutable named edits into the ordinary resolved Profile authority.</summary>
+internal static class ProfileBoundaryAuthoring
+{
+ private const double Tol = 1e-7;
+ private sealed record Block(string Name, string Body, int Start, int Length);
+ private sealed record Edit(string Name, int Segment, double From, double To,
+ IReadOnlyList<(string Name, LineArcProfileCurve2D Curve)> Curves, string Construction, string SourceSpan,
+ bool RequireTangentJoin = false);
+
+ private static string WithoutComments(string text) => Regex.Replace(text, @"/\*.*?\*/|//[^\r\n]*", "", RegexOptions.Singleline);
+ internal static bool IsDerived(string? body) => body is not null && Regex.IsMatch(WithoutComments(body), @"^\s*From\s*:");
+
+ internal static bool TryResolve(string source, string name, HashSet<string> visiting,
+ List<string> diagnostics, out ResolvedProfile2D? result)
+ {
+ result = null;
+ var declaration = Regex.Match(source, $@"\bProfile\s+{Regex.Escape(name)}(?:\s+Using\s+(?<owner>\w+))?\s*\{{");
+ if (!declaration.Success) return false;
+ var body = ReadBody(source, declaration.Index + declaration.Length - 1, out _);
+ if (body is null || !IsDerived(body)) return false;
+ body = WithoutComments(body);
+ var owner = declaration.Groups["owner"].Value;
+ var replacements = Blocks(body, "Replace").ToArray();
+ var remainder = body;
+ foreach (var block in replacements.OrderByDescending(b => b.Start)) remainder = remainder.Remove(block.Start, block.Length);
+ var applies = Regex.Matches(remainder, @"\bApply\s+(?<name>\w+)\s*;?").Select(m => m.Groups["name"].Value).ToArray();
+ remainder = Regex.Replace(remainder, @"\bApply\s+\w+\s*;?", "");
+ var header = Fields(remainder, ["From"], diagnostics, name);
+ if (!header.TryGetValue("From", out var from) || !Regex.IsMatch(from, @"^\w+(?:\.\w+)?$"))
+ { diagnostics.Add($"profile-edit-source-invalid:{name}"); return true; }
+ var deltas = SemanticProfileDeltaParser.Parse(source);
+ if (applies.Length > 0) diagnostics.AddRange(deltas.Diagnostics);
+ // Existing edge authoring attaches ProfileDelta implicitly. A derivation
+ // applies only explicitly selected programs, so resolve an unedited seed.
+ var seedSource = source;
+ ResolvedProfile2D? seed;
+ IReadOnlyList<string> seedErrors;
+ var localFrom = from.Contains('.') && from.StartsWith(owner + ".", StringComparison.Ordinal) ? from[(owner.Length + 1)..] : from;
+ if (Regex.IsMatch(seedSource, $@"\bProfile\s+{Regex.Escape(localFrom)}\b"))
+ seed = ProfileAuthoringParser.ResolveNamedProfileCore(seedSource, localFrom, visiting, out seedErrors);
+ else
+ {
+ foreach (var delta in Blocks(source, "ProfileDelta").OrderByDescending(b => b.Start))
+ seedSource = seedSource.Remove(delta.Start, delta.Length);
+ var synthetic = "__BoundarySeed_" + name;
+ while (Regex.IsMatch(seedSource, $@"\b{Regex.Escape(synthetic)}\b")) synthetic += "_";
+ seed = ProfileAuthoringParser.ResolveNamedProfileCore(seedSource + $"\nProfile {synthetic} {{ Loop Outer {{ {localFrom} |> TraceLoop }} }}",
+ synthetic, visiting, out seedErrors);
+ }
+ diagnostics.AddRange(seedErrors);
+ if (seed is null) return true;
+ if (seed.Loops.Count != 1) { diagnostics.Add($"profile-edit-loop-count-invalid:{name}"); return true; }
+ var segments = seed.Loops[0].Segments;
+ var edits = new List<Edit>();
+ var ids = new HashSet<string>(StringComparer.Ordinal);
+ foreach (var block in replacements)
+ {
+ if (!ids.Add(block.Name)) { diagnostics.Add($"profile-edit-duplicate-name:{name}.{block.Name}"); continue; }
+ var fields = Fields(block.Body, ["On", "Range", "Through", "Derivatives", "Join", "StartTangent", "EndTangent"], diagnostics, name + "." + block.Name);
+ if (!fields.TryGetValue("On", out var on)) { diagnostics.Add($"profile-edit-target-missing:{block.Name}"); continue; }
+ var index = FindMember(segments, on, owner, localFrom);
+ if (index < 0) { diagnostics.Add($"profile-edit-target-missing:{block.Name}:{on}"); continue; }
+ var carrier = segments[index].Geometry;
+ if (carrier is not LineArcLineSegment2D line) { diagnostics.Add($"profile-edit-curve-not-qualified:{block.Name}:straight-carrier-required"); continue; }
+ var length = Distance(line.Start, line.End);
+ var range = fields.TryGetValue("Range", out var rangeText) ? Vector(rangeText, "mm", diagnostics, block.Name) : (0d, length);
+ if (!ValidRange(range, length)) { diagnostics.Add($"profile-edit-range-invalid:{block.Name}"); continue; }
+ if (!fields.TryGetValue("Through", out var through)) { diagnostics.Add($"profile-edit-construction-required:{block.Name}:Through"); continue; }
+ var points = Vectors(through, "mm", diagnostics, block.Name);
+ var derivatives = fields.TryGetValue("Derivatives", out var derivativeText) ? Vectors(derivativeText, "mm", diagnostics, block.Name) : null;
+ var join = fields.GetValueOrDefault("Join", "Position");
+ if (join is not ("Position" or "Tangent")) diagnostics.Add($"profile-edit-join-invalid:{block.Name}:{join}");
+ (double X, double Y)? startTangent = fields.TryGetValue("StartTangent", out var startText) ? Vector(startText, "", diagnostics, block.Name) : null;
+ (double X, double Y)? endTangent = fields.TryGetValue("EndTangent", out var endText) ? Vector(endText, "", diagnostics, block.Name) : null;
+ if (derivatives is not null && (startTangent is not null || endTangent is not null || join == "Tangent"))
+ diagnostics.Add($"profile-edit-construction-conflict:{block.Name}:Derivatives-and-tangents");
+ var construction = new ProfileThroughConstruction(points, derivatives, startTangent, endTangent, join == "Tangent");
+ var curves = Construct(line, range, construction, diagnostics, block.Name);
+ edits.Add(new(block.Name, index, range.Item1 / length, range.Item2 / length,
+ curves.Select((c, i) => ($"{block.Name}_Span{i}", (LineArcProfileCurve2D)c)).ToArray(),
+ derivatives is null ? "ChordHermite" : "ExplicitHermite", $"profile:{name}/Replace:{block.Name}", construction.MatchTangent));
+ }
+ foreach (var apply in applies)
+ {
+ if (!ids.Add(apply)) { diagnostics.Add($"profile-edit-duplicate-name:{name}.{apply}"); continue; }
+ var matches = deltas.Deltas.Where(d => d.Delta.Name == apply).ToArray();
+ if (matches.Length != 1) { diagnostics.Add($"profile-edit-apply-unresolved:{apply}"); continue; }
+ var delta = matches[0];
+ var index = FindMember(segments, delta.OwnerPath, owner, localFrom);
+ if (index < 0 || segments[index].Geometry is not LineArcLineSegment2D line)
+ { diagnostics.Add($"profile-edit-apply-target-invalid:{apply}:{delta.OwnerPath}"); continue; }
+ var resolved = SemanticEdgeProfileResolver.Resolve(new(delta.OwnerPath, delta.OwnerPath,
+ new(line.Start.X, line.Start.Y), new(line.End.X, line.End.Y), [delta.Delta with { Side = -delta.Delta.Side }], seed.PlaneFrame, "Profile Apply"));
+ diagnostics.AddRange(resolved.Diagnostics);
+ var member = resolved.Profile?.OrderedMembers.SingleOrDefault(m => !m.IsGeneratedCarrier);
+ if (member is null) continue;
+ var length = Distance(line.Start, line.End);
+ edits.Add(new(apply, index, member.StartU / length, member.EndU / length,
+ member.CurveDescendants.Select((c, i) => ($"{apply}.{delta.Delta.Members[i].Name}", c.Geometry)).ToArray(),
+ "ProfileDelta", $"profile:{name}/Apply:{apply}"));
+ }
+ foreach (var group in edits.GroupBy(e => e.Segment))
+ {
+ var ordered = group.OrderBy(e => e.From).ToArray();
+ for (var i = 1; i < ordered.Length; i++)
+ if (ordered[i].From < ordered[i - 1].To - Tol) diagnostics.Add($"profile-edit-overlap:{ordered[i - 1].Name}:{ordered[i].Name}");
+ }
+ if (diagnostics.Count != 0) return true;
+ var output = new List<ResolvedProfileSegment2D>();
+ for (var i = 0; i < segments.Count; i++)
+ {
+ var original = segments[i];
+ var ordered = edits.Where(e => e.Segment == i).OrderBy(e => e.From).ToArray();
+ if (ordered.Length == 0) { output.Add(original); continue; }
+ var cursor = 0d; var previous = "Start";
+ foreach (var edit in ordered)
+ {
+ Retain(cursor, edit.From, previous, edit.Name);
+ foreach (var curve in edit.Curves)
+ output.Add(new(curve.Name, curve.Curve, new($"profile:{name}:segment:{curve.Name}",
+ $"profile-edit:{name}.{edit.Name}", edit.SourceSpan, edit.Construction, seed.PlaneFrame, original.Provenance.StableId)));
+ cursor = edit.To; previous = edit.Name;
+ }
+ Retain(cursor, 1, previous, "End");
+ void Retain(double a, double b, string left, string right)
+ {
+ if (b - a <= Tol) return;
+ var id = $"{original.Name}_Between_{left}_{right}";
+ output.Add(new(id, ProfileArrangementBuilder.TrimBounded(original.Geometry, a, b), original.Provenance with {
+ StableId = $"profile:{name}:segment:{id}", TracedFrom = original.Provenance.StableId,
+ Derivation = FormattableString.Invariant($"RetainedBoundary:{a:R}..{b:R}") }));
+ }
+ }
+ result = new(name, seed.PlaneFrame, [new("Outer", true, output)], seed.ConstructionPlane,
+ BoundaryEdits: edits.Select(e => new ProfileBoundaryEditEvidence(e.Name, segments[e.Segment].Name, e.From, e.To,
+ e.Construction, e.Curves.Select(c => c.Name).ToArray(), e.SourceSpan)).ToArray());
+ diagnostics.AddRange(ResolvedProfile2DValidator.Validate(result).Diagnostics);
+ if (edits.Count > 0) ValidateSimple(output, diagnostics, name);
+ foreach (var edit in edits.Where(e => e.RequireTangentJoin))
+ {
+ var first = output.FindIndex(s => s.Name == edit.Curves[0].Name);
+ var last = output.FindIndex(s => s.Name == edit.Curves[^1].Name);
+ if (!SameDirection(Tangent(output[(first + output.Count - 1) % output.Count].Geometry, true), Tangent(output[first].Geometry, false))
+ || !SameDirection(Tangent(output[last].Geometry, true), Tangent(output[(last + 1) % output.Count].Geometry, false)))
+ diagnostics.Add($"profile-edit-join-mismatch:{name}:{edit.Name}:retained-boundary-tangent");
+ }
+ if (diagnostics.Count != 0) result = null;
+ return true;
+ }
+
+ private static int FindMember(IReadOnlyList<ResolvedProfileSegment2D> segments, string reference, string owner, string seed)
+ {
+ if (seed.StartsWith("__Boundary2Value_", StringComparison.Ordinal)) seed = seed[17..];
+ if (owner.Length > 0 && reference.StartsWith(owner + ".", StringComparison.Ordinal)) reference = reference[(owner.Length + 1)..];
+ var leaf = reference.StartsWith(seed + ".", StringComparison.Ordinal) ? reference[(seed.Length + 1)..] : reference;
+ var candidates = segments.Select((s, i) => (s, i)).Where(x => x.s.Name == reference || x.s.Name == leaf
+ || x.s.Name == reference.Replace('.', '_') || x.s.Provenance.TracedFrom == reference
+ || x.s.Provenance.ConceptStableId == reference).ToArray();
+ return candidates.Length == 1 ? candidates[0].i : -1;
+ }
+
+ private static IReadOnlyList<LineArcCubicBezier2D> Construct(LineArcLineSegment2D line, (double, double) range,
+ ProfileThroughConstruction construction, List<string> diagnostics, string name)
+ {
+ var length = Distance(line.Start, line.End);
+ var points = new[] { Lerp(line.Start, line.End, range.Item1 / length) }.Concat(construction.Points)
+ .Append(Lerp(line.Start, line.End, range.Item2 / length)).ToArray();
+ if (points.Length > 1024 || points.Zip(points.Skip(1)).Any(p => Distance(p.First, p.Second) <= Tol))
+ { diagnostics.Add($"profile-edit-knots-invalid:{name}"); return []; }
+ var derivatives = construction.Derivatives?.ToArray();
+ if (derivatives is not null && (derivatives.Length != points.Length || derivatives.Any(d => Distance(d, (0, 0)) <= Tol)))
+ { diagnostics.Add($"profile-edit-derivatives-invalid:{name}"); return []; }
+ var speeds = points.Zip(points.Skip(1)).Select(p => Distance(p.First, p.Second)).ToArray();
+ if (derivatives is null)
+ {
+ derivatives = new (double X, double Y)[points.Length];
+ derivatives[0] = Subtract(points[1], points[0]);
+ derivatives[^1] = Subtract(points[^1], points[^2]);
+ for (var i = 1; i < points.Length - 1; i++)
+ {
+ var before = Scale(Subtract(points[i], points[i - 1]), 1 / speeds[i - 1]);
+ var after = Scale(Subtract(points[i + 1], points[i]), 1 / speeds[i]);
+ derivatives[i] = Scale(Add(Scale(before, speeds[i]), Scale(after, speeds[i - 1])), 1 / (speeds[i - 1] + speeds[i]));
+ }
+ var direction = Subtract(line.End, line.Start);
+ Endpoint(0, construction.StartTangent ?? (construction.MatchTangent ? direction : null));
+ Endpoint(points.Length - 1, construction.EndTangent ?? (construction.MatchTangent ? direction : null));
+ void Endpoint(int i, (double X, double Y)? tangent)
+ {
+ if (tangent is null) { derivatives[i] = Scale(derivatives[i], 1 / speeds[i == 0 ? 0 : ^1]); return; }
+ var magnitude = Distance(tangent.Value, (0, 0));
+ if (magnitude <= Tol) { diagnostics.Add($"profile-edit-tangent-invalid:{name}"); return; }
+ derivatives[i] = Scale(tangent.Value, 1 / magnitude);
+ }
+ if (derivatives.Any(d => Distance(d, (0, 0)) <= Tol)) diagnostics.Add($"profile-edit-cusp:{name}");
+ }
+ return Enumerable.Range(0, points.Length - 1).Select(i => {
+ var factor = construction.Derivatives is null ? speeds[i] / 3 : 1d / 3;
+ return new LineArcCubicBezier2D(points[i], Add(points[i], Scale(derivatives[i], factor)),
+ Subtract(points[i + 1], Scale(derivatives[i + 1], factor)), points[i + 1]);
+ }).ToArray();
+ }
+
+ private static void ValidateSimple(IReadOnlyList<ResolvedProfileSegment2D> segments, List<string> diagnostics, string name)
+ {
+ if (segments.Count > 1024) { diagnostics.Add($"profile-edit-boundary-limit:{name}:maximum=1024"); return; }
+ if (segments.Any(s => s.Geometry is not (LineArcLineSegment2D or LineArcCircularArc2D or LineArcCubicBezier2D)))
+ { diagnostics.Add($"profile-edit-validation-not-qualified:{name}"); return; }
+ foreach (var s in segments)
+ if (s.Geometry is LineArcCubicBezier2D c)
+ {
+ if (CubicCrossesItself(c)) diagnostics.Add($"profile-edit-self-intersection:{name}:{s.Name}");
+ if (!CubicIsRegular(c)) diagnostics.Add($"profile-edit-cusp:{name}:{s.Name}");
+ }
+ for (var i = 0; i < segments.Count; i++) for (var j = i + 1; j < segments.Count; j++)
+ {
+ var hit = ProfileArrangementBuilder.IntersectBounded(segments[i].Geometry, segments[j].Geometry);
+ var adjacent = j == i + 1 || i == 0 && j == segments.Count - 1;
+ if (hit.HasBoundedOverlap || hit.Intersections.Any(p => !adjacent ||
+ !(j == i + 1 && p.FirstParameter >= 1 - Tol && p.SecondParameter <= Tol ||
+ i == 0 && j == segments.Count - 1 && p.FirstParameter <= Tol && p.SecondParameter >= 1 - Tol)))
+ diagnostics.Add($"profile-edit-self-intersection:{name}:{segments[i].Name}:{segments[j].Name}");
+ }
+ }
+
+ private static bool CubicCrossesItself(LineArcCubicBezier2D c)
+ {
+ var a = Add(Subtract(c.End, c.Start), Scale(Subtract(c.Control1, c.Control2), 3));
+ var b = Scale(Add(Subtract(c.Start, Scale(c.Control1, 2)), c.Control2), 3);
+ var d = Scale(Subtract(c.Control1, c.Start), 3);
+ var denominator = Cross(a, b);
+ if (Math.Abs(denominator) < 1e-12) return false;
+ var sum = -Cross(a, d) / denominator;
+ var product = sum * sum + (Math.Abs(a.X) >= Math.Abs(a.Y) ? (b.X * sum + d.X) / a.X : (b.Y * sum + d.Y) / a.Y);
+ var discriminant = sum * sum - 4 * product;
+ if (discriminant <= Tol * Tol) return false;
+ var first = (sum - Math.Sqrt(discriminant)) / 2; var second = (sum + Math.Sqrt(discriminant)) / 2;
+ return first >= -Tol && second <= 1 + Tol && second - first > Tol;
+ }
+
+ private static bool CubicIsRegular(LineArcCubicBezier2D c)
+ {
+ var a = Scale(Add(Subtract(c.End, c.Start), Scale(Subtract(c.Control1, c.Control2), 3)), 3);
+ var b = Scale(Add(Subtract(c.Start, Scale(c.Control1, 2)), c.Control2), 6);
+ var d = Scale(Subtract(c.Control1, c.Start), 3);
+ var useX = Math.Abs(a.X) + Math.Abs(b.X) + Math.Abs(d.X) >= Math.Abs(a.Y) + Math.Abs(b.Y) + Math.Abs(d.Y);
+ var aa = useX ? a.X : a.Y; var bb = useX ? b.X : b.Y; var dd = useX ? d.X : d.Y;
+ var roots = new List<double> { 0, 1 };
+ if (Math.Abs(aa) < 1e-12) { if (Math.Abs(bb) >= 1e-12) roots.Add(-dd / bb); }
+ else
+ {
+ var discriminant = bb * bb - 4 * aa * dd;
+ if (discriminant >= 0) { roots.Add((-bb + Math.Sqrt(discriminant)) / (2 * aa)); roots.Add((-bb - Math.Sqrt(discriminant)) / (2 * aa)); }
+ }
+ return !roots.Any(t => t >= 0 && t <= 1 && Distance(Add(Add(Scale(a, t * t), Scale(b, t)), d), (0, 0)) <= Tol);
+ }
+
+ private static Dictionary<string, string> Fields(string text, string[] allowed, List<string> diagnostics, string name)
+ {
+ var result = new Dictionary<string, string>(StringComparer.Ordinal); var cursor = 0;
+ while (cursor < text.Length)
+ {
+ if (char.IsWhiteSpace(text[cursor]) || text[cursor] == ';') { cursor++; continue; }
+ var match = Regex.Match(text[cursor..], @"^(?<key>\w+)\s*:\s*");
+ if (!match.Success) { diagnostics.Add($"profile-edit-fields-invalid:{name}:{text[cursor..].Trim()}"); break; }
+ var key = match.Groups["key"].Value; cursor += match.Length; var start = cursor;
+ if (cursor < text.Length && text[cursor] == '[')
+ {
+ var depth = 0;
+ do { if (text[cursor] == '[') depth++; else if (text[cursor] == ']') depth--; cursor++; }
+ while (cursor < text.Length && depth > 0);
+ if (depth != 0) diagnostics.Add($"profile-edit-array-invalid:{name}:{key}");
+ }
+ else while (cursor < text.Length && text[cursor] != ';' && text[cursor] != '\r' && text[cursor] != '\n'
+ && !Regex.IsMatch(text[cursor..], @"^\s+\w+\s*:")) cursor++;
+ if (!allowed.Contains(key) || !result.TryAdd(key, text[start..cursor].Trim())) diagnostics.Add($"profile-edit-field-invalid:{name}:{key}");
+ }
+ return result;
+ }
+
+ private static (double X, double Y) Vector(string text, string unit, List<string> diagnostics, string name)
+ {
+ var pieces = text.Trim().Trim('[', ']').Split(',', StringSplitOptions.TrimEntries);
+ if (pieces.Length == 2 && Number(pieces[0], unit, out var x) && Number(pieces[1], unit, out var y)) return (x, y);
+ diagnostics.Add($"profile-edit-vector-invalid:{name}:{text}"); return (0, 0);
+ }
+ private static IReadOnlyList<(double X, double Y)> Vectors(string text, string unit, List<string> diagnostics, string name)
+ {
+ var matches = Regex.Matches(text, @"\[[^\[\]]*\]").ToArray();
+ var residue = text.Trim();
+ if (!residue.StartsWith('[') || !residue.EndsWith(']')) { diagnostics.Add($"profile-edit-array-invalid:{name}"); return []; }
+ residue = Regex.Replace(residue[1..^1], @"\[[^\[\]]*\]", "");
+ if (residue.Any(c => !char.IsWhiteSpace(c) && c != ',')) diagnostics.Add($"profile-edit-array-invalid:{name}");
+ return text.Trim() == "[]" ? [] : matches.Select(m => Vector(m.Value, unit, diagnostics, name)).ToArray();
+ }
+ private static bool Number(string text, string unit, out double value)
+ {
+ value = 0;
+ if (unit.Length > 0 && !text.EndsWith(unit, StringComparison.Ordinal)) return false;
+ return double.TryParse(unit.Length > 0 ? text[..^unit.Length] : text, NumberStyles.Float, CultureInfo.InvariantCulture, out value) && double.IsFinite(value);
+ }
+ private static IEnumerable<Block> Blocks(string source, string kind)
+ {
+ foreach (Match match in Regex.Matches(source, $@"\b{kind}\s+(?<name>\w+)\s*\{{"))
+ {
+ var body = ReadBody(source, match.Index + match.Length - 1, out var end);
+ if (body is not null) yield return new(match.Groups["name"].Value, body, match.Index, end - match.Index + 1);
+ }
+ }
+ private static string? ReadBody(string source, int open, out int end)
+ {
+ var depth = 0; end = open;
+ for (var i = open; i < source.Length; i++)
+ { if (source[i] == '{') depth++; else if (source[i] == '}' && --depth == 0) { end = i; return source[(open + 1)..i]; } }
+ return null;
+ }
+ private static bool ValidRange((double A, double B) range, double length) => range.A >= 0 && range.B <= length && range.B - range.A > Tol;
+ private static (double X, double Y) Tangent(LineArcProfileCurve2D curve, bool end) => curve switch {
+ LineArcLineSegment2D line => Subtract(line.End, line.Start),
+ LineArcCubicBezier2D cubic => end ? Subtract(cubic.End, cubic.Control2) : Subtract(cubic.Control1, cubic.Start),
+ LineArcCircularArc2D arc => (Math.Sign(arc.SweepAngleRadians) * -Math.Sin(arc.StartAngleRadians + (end ? arc.SweepAngleRadians : 0)),
+ Math.Sign(arc.SweepAngleRadians) * Math.Cos(arc.StartAngleRadians + (end ? arc.SweepAngleRadians : 0))),
+ _ => (0, 0)
+ };
+ private static bool SameDirection((double X, double Y) a, (double X, double Y) b) =>
+ Distance(a, (0, 0)) > Tol && Distance(b, (0, 0)) > Tol
+ && Distance(Scale(a, 1 / Distance(a, (0, 0))), Scale(b, 1 / Distance(b, (0, 0)))) <= Tol;
+ private static double Distance((double X, double Y) a, (double X, double Y) b) => Math.Sqrt(Math.Pow(a.X - b.X, 2) + Math.Pow(a.Y - b.Y, 2));
+ private static (double X, double Y) Lerp((double X, double Y) a, (double X, double Y) b, double t) => Add(a, Scale(Subtract(b, a), t));
+ private static (double X, double Y) Add((double X, double Y) a, (double X, double Y) b) => (a.X + b.X, a.Y + b.Y);
+ private static (double X, double Y) Subtract((double X, double Y) a, (double X, double Y) b) => (a.X - b.X, a.Y - b.Y);
+ private static (double X, double Y) Scale((double X, double Y) a, double s) => (a.X * s, a.Y * s);
+ private static double Cross((double X, double Y) a, (double X, double Y) b) => a.X * b.Y - a.Y * b.X;
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileModificationTemplateLibrary.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileModificationTemplateLibrary.cs
index 449ec6b9..fb17c956 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileModificationTemplateLibrary.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileModificationTemplateLibrary.cs
@@ -1,10 +1,13 @@
using System.Reflection;
+using System.Text.RegularExpressions;
namespace Aetheris.Kernel.Firmament.FirmamentV2;
public static class ProfileModificationTemplateLibrary
{
private const string ResourceName="Aetheris.Kernel.Firmament.Resources.ProfileModifications.firmament";
+ public static string ResolveImports(string source) => Regex.IsMatch(source, @"\bUse\s+Profile\.Modifications\s*;")
+ ? Source + Environment.NewLine + Regex.Replace(source, @"\bUse\s+Profile\.Modifications\s*;", "") : source;
public static string Source
{
get
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.cs
index 4f5fc48e..84467ed9 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/SectionChainAuthoringParser.cs
@@ -10,7 +10,11 @@ public sealed record SectionChainAuthoringResult(
SectionChainMaterializationResult? Materialization,
IReadOnlyList<string> Diagnostics,
LoftAuthoredBinding? LoftBinding = null,
- IReadOnlyList<SectionChainProfileDerivation>? ProfileDerivations = null);
+ IReadOnlyList<SectionChainProfileDerivation>? ProfileDerivations = null,
+ IReadOnlyList<SectionChainBoundaryEditInspection>? BoundaryEdits = null);
+
+public sealed record SectionChainBoundaryEditInspection(string Section, string Profile,
+ IReadOnlyList<ProfileBoundaryEditEvidence> Edits);
public sealed record SectionChainProfileDerivation(string Section, string Profile, string ConceptCurve,
string SourceSegment, string Transform, string Plane);
@@ -68,6 +72,7 @@ public static class SectionChainAuthoringParser
var sections = new List<Section>();
var derivations = new List<SectionChainProfileDerivation>();
+ var boundaryEdits = new List<SectionChainBoundaryEditInspection>();
foreach (var authored in Blocks(declaration.Body, "Section"))
{
var frameName = Field(authored.Body, "Frame");
@@ -86,6 +91,7 @@ public static class SectionChainAuthoringParser
if (frameName is not null && plane is null) diagnostics.Add($"section-chain-frame-unresolved:{authored.Name}:{frameName}");
if (plane is null || profile is null) continue;
var outer = profile.Loops.Single(loop => loop.IsOuter);
+ if (profile.BoundaryEdits is { Count: > 0 }) boundaryEdits.Add(new(authored.Name, profile.Name, profile.BoundaryEdits));
if (outer.Segments.FirstOrDefault()?.Provenance is { } provenance
&& provenance.ConceptStableId.StartsWith("concept-curve:", StringComparison.Ordinal))
derivations.Add(new(authored.Name, profile.Name, provenance.ConceptStableId,
@@ -115,11 +121,11 @@ public static class SectionChainAuthoringParser
diagnostics.Add("section-chain-normalization-tolerance-invalid:positive-length-required");
if (diagnostics.Count != 0) return Fail(diagnostics);
var chain = new SectionChain(declaration.Name, sections, correspondence, transition, start, end, continuity, ProfileApproximationTolerance: tolerance);
- if (!materialize) return new(true, chain, null, [], ProfileDerivations: derivations);
+ if (!materialize) return new(true, chain, null, [], ProfileDerivations: derivations, BoundaryEdits: boundaryEdits);
var result = SectionChainMaterializer.Materialize(chain);
if (!result.IsSuccess)
diagnostics.AddRange(result.Diagnostics.Select(item => $"{item.Code}:{item.Message}"));
- return new(result.IsSuccess, chain, result, diagnostics, ProfileDerivations: derivations);
+ return new(result.IsSuccess, chain, result, diagnostics, ProfileDerivations: derivations, BoundaryEdits: boundaryEdits);
SectionChainAuthoringResult Fail(IEnumerable<string> items) => new(false, null, null, items.Distinct(StringComparer.Ordinal).ToArray());
}
diff --git a/Aetheris.Kernel.Firmament/Materializer/ResolvedProfile2D.cs b/Aetheris.Kernel.Firmament/Materializer/ResolvedProfile2D.cs
index 0cdc0b6f..7e133610 100644
--- a/Aetheris.Kernel.Firmament/Materializer/ResolvedProfile2D.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/ResolvedProfile2D.cs
@@ -13,7 +13,8 @@ public sealed record ProfileSegmentProvenance(
string? InvocationSourceRange = null);
public sealed record ResolvedProfileSegment2D(string Name, LineArcProfileCurve2D Geometry, ProfileSegmentProvenance Provenance);
public sealed record ResolvedProfileLoop2D(string Name, bool IsOuter, IReadOnlyList<ResolvedProfileSegment2D> Segments);
-public sealed record ResolvedProfile2D(string Name, string PlaneFrame, IReadOnlyList<ResolvedProfileLoop2D> Loops, ConstructionPlane? ConstructionPlane = null, double? LocalStartDepth = null, double? LocalEndDepth = null)
+public sealed record ResolvedProfile2D(string Name, string PlaneFrame, IReadOnlyList<ResolvedProfileLoop2D> Loops, ConstructionPlane? ConstructionPlane = null, double? LocalStartDepth = null, double? LocalEndDepth = null,
+ IReadOnlyList<FirmamentV2.ProfileBoundaryEditEvidence>? BoundaryEdits = null)
{
public ConstructionPlane EffectiveConstructionPlane => ConstructionPlane ?? Materializer.ConstructionPlane.WorldXY;
}
diff --git a/docs/public/README.md b/docs/public/README.md
index ab91fa14..0e3b70a9 100644
--- a/docs/public/README.md
+++ b/docs/public/README.md
@@ -18,3 +18,6 @@ The Windows ZIP begins with the tested [release-bundle walkthrough](release-bund
All linked example source files are exercised by the public-example qualification tests. Preview 3's reliability rule is simple: a supported requested semantic operation is produced, and an unsupported operation fails with a named diagnostic; successful builds must not silently discard engineering intent.
For source-traceable PDF markup and LLM handoff before CAD reconstruction, see [Reading engineering drawings with Drawing Notes](drawing-notes.md).
+
+For closed-shape authoring with named tabs and smooth replacements, see
+[Immutable Profile boundary edits](firmament/profile-boundary-edits.md).
diff --git a/docs/public/firmament/profile-boundary-edits.md b/docs/public/firmament/profile-boundary-edits.md
new file mode 100644
index 00000000..c505b7e0
--- /dev/null
+++ b/docs/public/firmament/profile-boundary-edits.md
@@ -0,0 +1,209 @@
+# Immutable Profile boundary edits
+
+A Profile can start from a closed boundary or another Profile and apply named,
+compile-time edits. Unedited spans retain their geometry. Replacements inherit
+their endpoints, so ordinary authors do not have to write a spline control cage
+or manually reconnect the loop.
+
+```firmament
+Rect2 Blank { Center: [0mm,0mm]; Size: [120mm,80mm] }
+Profile Panel {
+ From: Blank
+ Replace Grip {
+ On: Blank.Right
+ Range: [20mm,60mm]
+ Through: [[48mm,-10mm], [48mm,10mm]]
+ Join: Tangent
+ }
+}
+```
+
+Use the result through ordinary Extrude, Compose or SectionChain. These edits
+resolve into `ResolvedProfile2D`; they do not introduce another sketch solver,
+geometry engine or runtime editing loop.
+
+## Sources and targets
+
+`From` is the first field, after optional comments, in a derived Profile body.
+The seed is a named closed primitive or Profile. It must have one outer loop and
+no inner loops in this lane. A Profile may derive from another derived Profile;
+cycles fail. Explicit `Loop` authoring and existing Profile pipelines remain
+available, but cannot be mixed into the same derivation block.
+
+Rect2 provides Bottom, Right, Top and Left in counterclockwise traversal order.
+Square2 and linear polygon members also supply straight carriers. Explicit
+polygons retain named Set<Point2> vertices and adjacent-name edge identities.
+`Using Layout` allows references to a boundary under that Concept Struct.
+Circle2/Ellipse2 can be unchanged seeds; editing their periodic boundaries is
+not qualified yet. Curved replacement carriers also remain deferred.
+
+`On` selects a seed member. Range is two Lengths measured from the directed
+member's start, not global coordinates or normalized parameters. It must be a
+positive interval contained in a straight carrier. Omit Range to replace the
+whole member. Through-points use the seed's local 2D coordinates.
+
+One block is an atomic edit set against its immutable seed. Overlapping edits
+are rejected, regardless of declaration order. Further edits to generated
+members require another explicit Profile derivation. Unselected ProfileDelta
+programs do not modify a closed-primitive seed implicitly.
+
+## Reusing engineering edit templates
+
+```firmament
+Use Profile.Modifications;
+Static ServiceTab: ProfileTabSpec {
+ Center: 60mm; Width: 24mm; Extension: 8mm
+}
+ProfileDelta ServiceTabEdit = Tab<P: ServiceTab, Owner: Blank.Top>
+Profile TabbedPanel {
+ From: Blank
+ Apply ServiceTabEdit
+}
+```
+
+Apply reuses the existing semantic ProfileDelta parser/resolver, including its
+anchor, levels, spans and transition validation. Outward means away from the
+counterclockwise region's material interior. Generated members retain names such
+as `TabbedPanel.ServiceTabEdit.Crown`; a subsequent Profile can select that
+straight member. Sheet Metal retains its manufacturing/domain authority and
+formed/flat correspondence. Its existing implicit attachment syntax is preserved.
+CornerProfile authoring remains on its existing route; Apply of a corner program
+is not added by this milestone.
+
+The complete [panel fixture](../../../fixtures/Canonical/Boundary2/edited-panel.firmament)
+combines a templated tab with a smooth grip and builds through Aetheris.CLI.
+
+## Smooth curves and explicit shape control
+
+Through describes a finite open cubic Hermite chain. The inherited endpoints
+are included automatically. For points p0..pn, let hi be the distance between
+pi and p(i+1), and si = (p(i+1)-pi)/hi. Endpoint derivatives default to s0 and
+s(n-1). Interior derivatives are:
+
+```
+di = (hi * s(i-1) + h(i-1) * si) / (h(i-1) + hi)
+```
+
+Each interval uses controls `pi + hi*di/3` and `p(i+1) - hi*d(i+1)/3`.
+Chord parameter intervals make the shared derivative direction continuous;
+this is a fixed interpolation rule, not a shape optimizer. Overshoot is possible
+and resulting intersections are checked.
+
+`StartTangent` and `EndTangent` are finite nonzero dimensionless direction
+vectors; they replace the corresponding endpoint derivative direction.
+`Join: Position` is the default. `Join: Tangent` obtains directions from the
+source carrier and verifies both realized joins against the neighboring result
+curves. A sharp corner cannot silently satisfy a tangent join.
+
+For preserving a designed curve exactly, supply explicit Length-valued
+Derivatives, one for every knot **including both inherited endpoints**:
+
+```firmament
+Replace Grip {
+ On: Blank.Right
+ Range: [20mm,60mm]
+ Through: [[48mm,-10mm], [48mm,10mm]]
+ Derivatives: [[0mm,20mm], [-10mm,15mm], [10mm,15mm], [0mm,20mm]]
+}
+```
+
+These derivatives use a unit parameter interval per cubic, so controls are
+`pi + di/3` and `p(i+1) - d(i+1)/3`. They cannot be combined with tangent fields
+or Join: Tangent. Through: [] admits a single cubic between inherited endpoints.
+Repeated adjacent points, zero derivatives/tangents, cubic cusps and individual
+cubic self-crossings are rejected. There are at most 1,024 knots per replacement
+and 1,024 resulting segments in an edited loop.
+
+## Validation, identities and inspection
+
+Validation checks closure, winding, coincident overlap, inter-span crossings
+and extra contacts, including adjacent spans away from their shared endpoint.
+Pair checks reuse the shared bounded line/arc/cubic intersection kernel at
+1e-7 mm tolerance. Individual cubic loops and stationary tangents have polynomial
+checks. Curved intersection search uses bounded convex-hull subdivision and
+numerical parameter refinement; this is tolerance-based qualification, not a
+certified global algebraic simplicity proof. Unsupported edited curve families
+fail rather than being converted to a display polygon.
+
+New curve names are `Grip_Span0`, `Grip_Span1`, etc. Retained fragment names use
+their bounding named edits rather than a global counter. Editing one member
+does not rename unrelated members. Consumed names remain source provenance;
+they are not redirected to whichever child happens to be nearest.
+
+Resolved Profiles carry BoundaryEdits with source members, normalized selected
+intervals, construction methods, descendants and source identity. SectionChain
+CLI inspection exposes these as `boundaryEdits` per section, alongside Concept
+derivations. Normalized evidence intervals are distinct from Length-valued
+authored Range. Existing SectionChain correspondence still owns span matching.
+
+## Guitar dogfood and reproduction
+
+[body-outline.firmament](../../../fixtures/Canonical/AssemblyInterfaces/GuitarX0/body-outline.firmament)
+now uses six named landmark chords and six edits: LowerTreble, HornRise, Cutaway,
+Shoulder, UpperBass and LowerBass. Its source is 45 lines instead of 93, with no
+separate point/control/Segment declarations. Explicit derivatives preserve the
+previous 18 cubic spans. Carve, back and binding still derive from BodyOutline;
+their seam is now the named `LowerTreble_Span0`.
+
+```powershell
+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll build fixtures/Canonical/Boundary2/edited-panel.firmament --out artifacts/local/profile-loop-implementation/panel.step --json
+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll section-chain inspect fixtures/Canonical/AssemblyInterfaces/GuitarX0/CarvedMaple.firmament --json
+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll asm export-ap242 fixtures/Canonical/AssemblyInterfaces/GuitarX0/guitar.firmasm --out artifacts/local/profile-loop-implementation/guitar.step --json
+```
+
+Fresh before/after carve exports contain 2,324 corresponding Cartesian points
+each. Maximum point displacement is 4.68e-7 mm, attributable to replacing the
+old six-decimal control coordinates with explicit Hermite derivatives. This is
+numerical surface-control parity, not byte-identical STEP: semantic names changed.
+Fresh USD has 53 shared geometry definitions and 91 visible product occurrences.
+Mesh checks found no unmatched edges or nonpositive normal triangles in the
+qualified guitar definitions. Cycles hero/isometric output is regenerated from
+that USD; shading preserves imported product topology.
+
+Release solution build passed. The fast core lane passed 1,004 tests; the final
+full serial lane passed 4,096 tests with 7 existing skips and no failures. The
+19 focused authoring cases cover pure seed preservation, real extrusion,
+templated Apply, overlapping edits, invalid units/targets, tangent mismatches,
+individual cubic loops/cusps and rejected periodic edits. STEP reimport preserves
+53 geometry definitions, 91 bodies and 35 subassembly occurrences.
+
+One host run measured cold compilation at 13.514 seconds, warm uncached at
+6.766 seconds, and populated-session recompilation at 1.599 seconds. Display
+preparation was 0.539 / 0.516 / 0.368 seconds respectively. The incremental run
+reused all 53 definitions and produced byte-identical USD to the same-run uncached
+baseline. Process startup/build are excluded; tests/rendering also ran on this
+host during qualification, so these are not isolated comparative benchmarks.
+Camera interaction was not remeasured by this authoring milestone.
+
+Both inspected Cycles images are 1,800 by 2,200 at 64 samples on an RTX 3070:
+hero rendering took 26.5 seconds, shaded isometric 21.2 seconds. Their topology
+hash checks passed. The refreshed images retain the presentation witness.
+
+Generated evidence, STEP/USD and renders live under ignored
+`artifacts/local/profile-loop-implementation/`: final-build.log, final-fast.log,
+final-full.log, final-carve-inspection.json, carve-parity.json, timings.json,
+mesh-check.json, step-reimport.json, guitar.step, guitar.usda, beauty/hero.png,
+isometric/shaded-isometric.png and their saved Blender scenes/render reports.
+
+## Future equation-driven curves
+
+Curve construction has a typed internal payload seam. A future bounded Equation
+payload can produce the same resolved curves as Through/Hermite without adding
+an executable callback to Profile or a runtime dependency to exported geometry.
+No Equation syntax or C# evaluation is implemented here; such requests fail.
+
+The intended extension is compile-time only: a declared parameter interval,
+Length-valued 2D result, pure arithmetic and approved math intrinsics, bounded
+evaluation/approximation work, and explicit dependencies for cache identity.
+If lowering to C#, validate the restricted program before compilation. No I/O,
+reflection, arbitrary CLR calls, dynamic code loading, mutable static state,
+async work, recursion or unbounded loops. Do not treat running arbitrary C# as
+a purity check.
+
+Recognized polynomial/analytic laws should preserve exact representations.
+Other equations need an explicit approximation tolerance, admitted representation
+and reported error bound before they can be materialized. Exact BRep geometry of
+an approximant must not be reported as an exact representation of the equation.
+After equation binding, the ordinary boundary-edit validity checks still apply.
+See the [larger design proposal](programmable-profile-loops-proposal.md) for
+deferred periodic intervals, Curve2 payloads, inner loops and Profile-valued Features.
diff --git a/docs/public/firmament/programmable-profile-loops-proposal.md b/docs/public/firmament/programmable-profile-loops-proposal.md
new file mode 100644
index 00000000..a104e9da
--- /dev/null
+++ b/docs/public/firmament/programmable-profile-loops-proposal.md
@@ -0,0 +1,350 @@
+# Programmable Profile loops — design proposal
+
+Status: the bounded closed-seed/Apply/straight-member Replace subset is now
+implemented; see [the current authoring guide](profile-boundary-edits.md).
+The examples below record the original design, including deferred syntax.
+Audited on 2026-09-30. This proposal changes authoring, not geometry authority.
+
+## Recommendation
+
+Make a Profile an immutable closed region that can be derived from a closed
+Concept boundary or another Profile by applying named boundary edits.
+
+The author selects an existing directed span and replaces it. The compiler
+preserves everything outside that span and inherits its endpoints. Tabs, recesses,
+corner treatments and smooth replacements are different edit families within
+this model. A closed seed removes endpoint bookkeeping; validation still has to
+establish that the resulting region is admissible.
+
+Use the existing Sheet Metal semantic edge/corner machinery for engineering edits,
+and the existing Profile arrangement routines for bounded curve splitting and
+intersection checks. Keep the resolved Profile as the consumer-facing value for
+Extrude, SectionChain and Concept boundary derivation.
+
+## What the audit found
+
+| Existing owner | Already does | Gap relevant to this proposal |
+| --- | --- | --- |
+| `ClosedBoundary2Authoring` | Rect2, Circle2, Ellipse2, rounded rectangles and polygons; named members; lowering into ordinary guides/Profile routes | No general named boundary-edit program |
+| `ProfileAuthoringParser` | Ordered guide pipelines, explicit loops, bounded guide sub-spans, Profile resolution | Authors still connect low-level curves; no closed-seed-plus-edits contract |
+| `SemanticEdgeProfileResolver` | Anchored tabs/notches/ProfileDelta; retains untouched carrier spans; rejects out-of-bounds and overlapping edits | Carrier is a straight directed edge; descendants are line/circular-arc geometry |
+| `SemanticCornerProfileResolver` | Named corner programs, edge consumption and conflict handling | Not a general editable closed-loop frontend |
+| `Profile.Modifications` | Typed reusable Tab and Recess templates; immutable Record specifications; attachment to Sheet Metal and ordinary rectangular Profile edges | Immutable closed-seed derivation and explicit Apply were missing |
+| `SheetMetalAuthoredLowering` | Combines directed edges and corner descendants into an exact planar contour; preserves formed/flat correspondence | Composition is embedded in flange/domain lowering |
+| `ProfileArrangementBuilder` | Bounded intersection, trimming and splitting for lines/arcs/cubics; region composition for existing material features | General Profile validation does not use its full intersection capability; bounded trim does not admit ellipses |
+| `ResolvedProfile2DValidator` | Closure, endpoint matching, winding, some degeneracy checks, nonadjacent line-line crossings | Does not establish general curved-loop simplicity or complete hole relationships |
+| Concept `Curve2 { From: Profile; ... }` | Explicit boundary derivation and placement without BRep edge selection | Copies/transforms boundaries; does not edit their topology |
+
+The sheet-metal pilot really does implement “start with a region, modify named
+edges.” It is not an arbitrary polygon boolean API. `BlankCompositionPlan` also
+keeps material additions, corner relief and through-cuts under explicit domain
+ownership. Share the boundary machinery; retain that manufacturing authority.
+
+Audited implementation files:
+
+- [Closed boundary authoring](../../../Aetheris.Kernel.Firmament/FirmamentV2/ClosedBoundary2Authoring.cs)
+- [Profile authoring](../../../Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs)
+- [Semantic edge programs](../../../Aetheris.Kernel.Firmament/FirmamentV2/SemanticEdgeProfileIr.cs)
+- [Semantic corner programs](../../../Aetheris.Kernel.Firmament/FirmamentV2/SemanticCornerProfileIr.cs)
+- [Reusable modifications](../../../Aetheris.Kernel.Firmament/Resources/ProfileModifications.firmament)
+- [Sheet Metal lowering](../../../Aetheris.SheetMetal/SheetMetalAuthoredLowering.cs)
+- [Blank composition](../../../Aetheris.SheetMetal/BlankCompositionPlan.cs)
+- [Shared curve/arrangement operations](../../../Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs)
+- [Resolved Profile and validation](../../../Aetheris.Kernel.Firmament/Materializer/ResolvedProfile2D.cs)
+
+## Proposed authoring
+
+### Closed seed, named edits, ordinary Profile result
+
+The panel example's From/Apply/straight-member Replace syntax is implemented.
+Explicit Curve2 replacement payloads, equation curves, periodic intervals and
+Profile-valued Features below remain design sketches, not current compiler syntax.
+
+```firmament
+Use Profile.Modifications;
+
+Concept Struct Layout {
+ Rect2 Blank { Center: [0mm,0mm]; Size: [120mm,80mm] }
+}
+
+Static ServiceTab: ProfileTabSpec {
+ Center: 60mm; Width: 24mm; Extension: 8mm
+}
+
+ProfileDelta ServiceTabEdit = Tab<P: ServiceTab, Owner: Layout.Blank.Top>
+
+Profile Panel Using Layout {
+ From: Blank
+ Apply ServiceTabEdit
+
+ Replace Grip {
+ On: Blank.Right
+ Range: [20mm,60mm]
+ Through: [[48mm,-10mm], [48mm,10mm]]
+ Join: Tangent
+ }
+}
+```
+
+`From` initializes the region. It accepts a closed boundary or a Profile value.
+It excludes an additional explicit `Loop Outer` in the same declaration.
+`Apply` uses the existing ProfileDelta template/specification language; it does
+not redefine what Tab/Recess mean.
+
+`Replace` is a named pure edit. `On` selects a directed base member; `Range` is
+distance from that member's start and is initially admitted only on straight
+members. Omitting Range selects the whole member. Grip inherits both endpoints;
+the through-points are in the Profile's local Concept frame. In this example,
+Blank.Right goes from bottom-right to top-right, so the range endpoints are
+`[60mm,-20mm]` and `[60mm,20mm]`.
+
+`Join: Tangent` derives endpoint tangent directions from the retained source
+boundary. Default `Join: Position` requires only shared endpoints. Explicit
+`StartTangent` and `EndTangent` direction vectors override the corresponding
+source direction, with finite nonzero vectors required. At a source corner,
+Tangent is rejected unless the relevant one-sided tangent is unambiguous or
+explicitly supplied. These are construction rules followed by verification,
+not constraints sent to a solver.
+
+Through is shorthand for a finite open cubic interpolating chain. It must have a
+documented, fixed interpolation rule, not a best-fit optimizer: chord-length
+parameterization, interior derivatives from the adjacent secants weighted by
+their parameter intervals, and endpoint derivatives from the selected directions
+with adjacent chord-speed magnitudes. Publish the exact formula and regression
+fixtures before qualification. Reject repeated points, zero tangents and cusps.
+The resulting cubic control points are compiler output, inspectable but usually
+not authored.
+
+A replacement must choose exactly one construction payload: Through, an explicit
+bounded open `Curve2` chain, or a named line/arc construction. Explicit cubics
+remain an escape hatch when the interpolation rule does not express the design.
+This does not promise that interpolation cannot overshoot.
+
+### Identity, ordering and functional composition
+
+One derivation block is an atomic edit set against its immutable seed. Named
+edits on disjoint intervals are composed in boundary traversal order. Source order
+is retained for diagnostics; it does not make overlapping edits legal.
+
+To edit the result of a previous edit, derive another Profile explicitly:
+
+```firmament
+Profile FinishedPanel {
+ From: Panel
+ Replace Crown {
+ On: Panel.ServiceTabEdit.Crown
+ Through: [[0mm,52mm]]
+ Join: Position
+ }
+}
+```
+
+The result remains a Profile value. A future `Feature ... -> Profile` should
+package exactly this pure recipe using existing typed Feature call mechanics.
+Profile returns are an extension to the currently qualified Feature subset,
+not something this syntax assumes is already supported. No mutable sketch or
+separate execution language is needed.
+
+Names address engineering intent: `Panel.Grip`, `Panel.ServiceTabEdit.Crown`. A member can
+have several exact descendants. Untouched spans retain their source identity
+and interval; split fragment identities derive from their bounding named edits,
+not enumeration order. Consumed seed members remain provenance references, not
+aliases silently redirected to a different curve. Inspection must distinguish
+source members from selectable result members.
+
+### Circles and ovals
+
+A full circle/ellipse has no natural start/end and must not silently acquire a
+nearest-edge selector. Rectangles already provide named edges; periodic curves
+need explicit named landmarks and a directed interval between them.
+
+Proposed later form:
+
+```firmament
+Concept Struct Layout {
+ Ellipse2 Blank { Center: [0mm,0mm]; AxisLengths: [340mm,440mm] }
+ Point2 Shoulder { On: Blank.Boundary; Parameter: 0.12 }
+ Point2 Heel { On: Blank.Boundary; Parameter: 0.30 }
+}
+Profile Body Using Layout {
+ From: Blank
+ Replace Cutaway {
+ On: Blank.Boundary
+ From: Shoulder; To: Heel; Direction: CounterClockwise
+ Through: [[55mm,125mm]]
+ Join: Tangent
+ }
+}
+```
+
+Parameter is normalized canonical curve parameter, not arc-length fraction;
+zero/seam and axis conventions must be specified independently of rendering.
+Direction disambiguates the two periodic paths. Full periodic replacement needs
+a separate explicit whole-member form, not equal endpoints interpreted magically.
+Circle arcs can use existing analytic geometry. Ellipse interval trimming and
+intersection qualification are additional work: do not pretend the current
+bounded line/arc/cubic helper already supplies them. Rectangles/straight-member
+edits and the guitar polygon scaffold can ship before ellipse edits.
+
+## Guitar dogfood
+
+The current [body outline](../../../fixtures/Canonical/AssemblyInterfaces/GuitarX0/body-outline.firmament)
+has 54 point declarations, 18 cubic declarations and 18 Segment entries. It
+already describes one shared boundary, but its source exposes compilation detail
+instead of lower bout, waist, horn and cutaway intent.
+
+A rectangle is a useful seed for brackets. For this guitar, use a closed polygon
+through a handful of named landmarks, then replace its chords. The polygon is
+Concept scaffolding and is never an intermediate solid. Reuse the existing named
+Set<Point2> and its adjacent-name edge identities, rather than inventing another
+polygon literal or exposing generated edge indices.
+
+```firmament
+Static Landmarks: Set<Point2> {
+ Tail => Point2(0mm,-220mm)
+ TrebleWaist => Point2(105mm,28mm)
+ Horn => Point2(113mm,160mm)
+ NeckSeat => Point2(28mm,204mm)
+ BassShoulder => Point2(-111mm,174mm)
+ BassWaist => Point2(-95mm,40mm)
+}
+Concept Struct BodyLayout {
+ Polygon2<Explicit> Scaffold { Vertices: Landmarks }
+}
+
+Profile BodyOutline Using BodyLayout {
+ From: Scaffold
+ Replace LowerTreble {
+ On: Scaffold.Tail_TrebleWaist
+ Through: [[115mm,-195mm], [168mm,-115mm], [148mm,-35mm]]
+ StartTangent: [1,0]; EndTangent: [-15,65]
+ }
+ Replace HornRise {
+ On: Scaffold.TrebleWaist_Horn
+ Through: [[118mm,95mm], [124mm,140mm]]
+ StartTangent: [-15,65]; EndTangent: [-16.5,1]
+ }
+ Replace Cutaway {
+ On: Scaffold.Horn_NeckSeat
+ Through: [[91mm,142mm], [48mm,137mm]]
+ StartTangent: [-16.5,1]; EndTangent: [-45,34]
+ }
+ Replace Shoulder {
+ On: Scaffold.NeckSeat_BassShoulder
+ Through: [[-42mm,205mm]]
+ StartTangent: [-45,34]; EndTangent: [-38.5,-45]
+ }
+ Replace UpperBass {
+ On: Scaffold.BassShoulder_BassWaist
+ Through: [[-119mm,115mm]]
+ StartTangent: [-38.5,-45]; EndTangent: [-9,-73.5]
+ }
+ Replace LowerBass {
+ On: Scaffold.BassWaist_Tail
+ Through: [[-137mm,-32mm], [-168mm,-115mm], [-115mm,-195mm]]
+ StartTangent: [-9,-73.5]; EndTangent: [1,0]
+ }
+}
+```
+
+This is a proposed readable redesign, not a verified curve-equivalent migration.
+Coordinates reuse existing landmarks, and shared endpoint directions express G1
+intent; generated derivative magnitudes can change the silhouette. During
+implementation, compare bounds, area, silhouette and neck-side/back views before
+replacing the witness. If exact preservation is needed, allow inline Hermite
+knots with Length-valued derivatives; those map directly to the current cubic
+control points without guessing a fit.
+
+Keep `BodyOutline` as the same public Profile export. CarvedMaple, MahoganyBack
+and IvoryBinding continue using their existing Concept Curve2 derivations.
+SectionChain consumes stable member/descendant correspondence. Knot insertion
+may change descendant count; surface correspondence must reject mismatches
+between independently edited sections rather than pair spans by position.
+
+## Compiler integration and validity contract
+
+1. Bind closed seed and edit references through the existing semantic namespace.
+ Resolve values before erasing Concept scaffolding; reject cyclic Profile
+ derivations. No references to incidental BRep edges.
+2. Introduce a small typed closed-boundary edit plan: seed reference, frame, named
+ member/interval, edit family/payload, stable identity and source range.
+ Generalize the straight-edge resolver only where its contract remains true.
+ Curved replacement is a new sibling payload; do not coerce every curve into
+ a straight carrier or a distance/offset ProfileDelta.
+3. Resolve Apply through existing ProfileDelta and CornerProfile machinery. Share
+ boundary composition below ordinary Profile and Sheet Metal authoring.
+ Sheet Metal still owns bend boundaries, attachability, thickness and flat
+ correspondence; ordinary Profile edits cannot grant those capabilities.
+4. Split only selected spans, inherit endpoints exactly and retain untouched
+ geometry. Use existing TrimBounded/SplitBounded for admitted families. Build
+ one `ResolvedProfile2D` with source/edit/descendant provenance.
+5. Validate the complete resulting region before materialization. Reject span
+ overlap, stale targets, duplicate names, zero-length pieces, endpoint gaps,
+ reversed winding, crossings, positive coincident overlap and extra contacts.
+ Adjacent curves may share their declared endpoint only; do not skip all
+ adjacent-pair intersection checks. Check cubic self-intersection within an
+ individual span as well as intersections between spans.
+6. Reuse `ProfileArrangementBuilder.IntersectBounded` for qualified pair checks.
+ Audit same-cubic loops, tangencies and numerical exhaustion explicitly. Its
+ cubic candidate search currently has a depth limit and numerical refinement;
+ exact cubic representation is not an exact global simplicity proof. Report
+ tolerance/method, and reject unsupported/indeterminate cases rather than
+ declaring them proven. Do not substitute a sampled display polygon as truth.
+7. Retain existing material consumers and their validity checks. One outer loop
+ is required. An interior cut is a named inner-loop operation, not a boundary
+ splice; containment, winding and inter-loop intersections need qualification
+ before that operation ships. Splitting a region into multiple islands is
+ rejected in this lane.
+8. Use existing compilation-session cache keys with expanded included source.
+ An edited exported Profile invalidates dependent parts; unrelated definitions
+ remain reusable. This needs no new incremental dependency engine.
+
+Suggested diagnostics: `profile-edit-overlap`, `profile-edit-target-consumed`,
+`profile-edit-range-invalid`, `profile-edit-join-ambiguous`,
+`profile-edit-self-intersection`, `profile-edit-validation-indeterminate`, and
+`profile-edit-curve-not-qualified`. Include the two conflicting member identities
+and source spans, not just “invalid profile.”
+
+Inspection should show seed, operations, selected source intervals, preserved
+members, generated curves, join residuals, validation method and downstream
+dependency. This makes the compact source explainable without exposing control
+points in every authored document.
+
+## Bounded delivery order
+
+1. **Closed seed + engineering edits:** From, Apply of existing straight-carrier
+ ProfileDelta, named members and ordinary Profile result. Prove identical
+ Sheet Metal formed/flat output while ordinary extrusion gains the same recipe.
+2. **Smooth replacement + guitar:** whole named straight-member replacements,
+ straight-member ranges, compact through-points/explicit cubic escape hatch,
+ explicit tangent directions,
+ complete admitted curved validation, inspection and SectionChain correspondence.
+ Dogfood the shared guitar outline here; compare hero and side views.
+3. **Curved/periodic carriers:** bounded arc/cubic intervals, circle landmarks
+ and directed periodic spans; ellipse intervals only after their exact trim and
+ validation path is qualified. Add interior-loop edits separately.
+
+Acceptance includes valid and rejected corpus fixtures, deterministic identities,
+source provenance, unchanged input Profile values, real CLI inspection/STEP
+roundtrip, and full Release test gates for implementation. No generic solver,
+runtime editing engine, public arbitrary booleans or fallback mesh path.
+
+## Audit evidence
+
+Current CLI checks passed:
+
+```powershell
+dotnet run --project Aetheris.CLI -c Release --no-build -- sheetmetal paths fixtures/Canonical/SheetMetal/profile-delta-tab-family.firmament --json
+dotnet run --project Aetheris.CLI -c Release --no-build -- section-chain inspect fixtures/Canonical/AssemblyInterfaces/GuitarX0/CarvedMaple.firmament --json
+```
+
+The Sheet Metal fixture exposes 41 semantic paths, including 12 ServiceTab paths
+across formed and flat views. CarvedMaple inspection succeeds with no diagnostics
+through its SectionChain path. Generic `inspect` does not dispatch this SectionChain
+document correctly; it reports `firmament-v2-phase3-edge-finish-syntax-invalid`.
+Use the schema-specific command above for this audit. That CLI dispatch friction
+is separate from Profile editing and was not patched here.
+
+Original audit JSON is under ignored `artifacts/local/profile-loop-audit/`.
+Implementation evidence is separate under `artifacts/local/profile-loop-implementation/`;
+the current guide distinguishes the admitted subset from this broader proposal.
diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/CarvedMaple.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/CarvedMaple.firmament
index e2ebf7fe..bfcfe53a 100644
--- a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/CarvedMaple.firmament
+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/CarvedMaple.firmament
@@ -28,19 +28,19 @@ Model CarvedMaple {
SectionChain CarvedMaple { Continuity: G1
Section S0 { Frame: F0
Profile: P0
- Seam: Edge0 }
+ Seam: LowerTreble_Span0 }
Section S1 { Frame: F1
Profile: P1
- Seam: Edge0 }
+ Seam: LowerTreble_Span0 }
Section S2 { Frame: F2
Profile: P2
- Seam: Edge0 }
+ Seam: LowerTreble_Span0 }
Section S3 { Frame: F3
Profile: P3
- Seam: Edge0 }
+ Seam: LowerTreble_Span0 }
Section S4 { Frame: F4
Profile: P4
- Seam: Edge0 }
+ Seam: LowerTreble_Span0 }
Start: Cap
End: Cap
}
diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/IvoryBinding.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/IvoryBinding.firmament
index c0128f13..0cee403b 100644
--- a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/IvoryBinding.firmament
+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/IvoryBinding.firmament
@@ -16,10 +16,10 @@ Model IvoryBinding {
SectionChain IvoryBinding { Continuity: G0
Section S0 { Frame: F0
Profile: P0
- Seam: Edge0 }
+ Seam: LowerTreble_Span0 }
Section S1 { Frame: F1
Profile: P1
- Seam: Edge0 }
+ Seam: LowerTreble_Span0 }
Start: Cap
End: Cap
}
diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/MahoganyBack.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/MahoganyBack.firmament
index d8bef561..915ece1b 100644
--- a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/MahoganyBack.firmament
+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/MahoganyBack.firmament
@@ -16,10 +16,10 @@ Model MahoganyBack {
SectionChain MahoganyBack { Continuity: G0
Section S0 { Frame: F0
Profile: P0
- Seam: Edge0 }
+ Seam: LowerTreble_Span0 }
Section S1 { Frame: F1
Profile: P1
- Seam: Edge0 }
+ Seam: LowerTreble_Span0 }
Start: Cap
End: Cap
}
diff --git a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/body-outline.firmament b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/body-outline.firmament
index 9251d12d..178a358d 100644
--- a/fixtures/Canonical/AssemblyInterfaces/GuitarX0/body-outline.firmament
+++ b/fixtures/Canonical/AssemblyInterfaces/GuitarX0/body-outline.firmament
@@ -1,93 +1,45 @@
-// Shared authored single-cut boundary; Concept placements derive each section.
- Point2 BodyOutlineP0 { Position: [0mm,-220mm] }
- Point2 BodyOutlineA0 { Position: [38.333333mm,-220mm] }
- Point2 BodyOutlineB0 { Position: [-38.333333mm,-220mm] }
- Point2 BodyOutlineP1 { Position: [115mm,-195mm] }
- Point2 BodyOutlineA1 { Position: [143mm,-177.5mm] }
- Point2 BodyOutlineB1 { Position: [87mm,-212.5mm] }
- Point2 BodyOutlineP2 { Position: [168mm,-115mm] }
- Point2 BodyOutlineA2 { Position: [173.5mm,-88.333333mm] }
- Point2 BodyOutlineB2 { Position: [162.5mm,-141.666667mm] }
- Point2 BodyOutlineP3 { Position: [148mm,-35mm] }
- Point2 BodyOutlineA3 { Position: [137.5mm,-11.166667mm] }
- Point2 BodyOutlineB3 { Position: [158.5mm,-58.833333mm] }
- Point2 BodyOutlineP4 { Position: [105mm,28mm] }
- Point2 BodyOutlineA4 { Position: [100mm,49.666667mm] }
- Point2 BodyOutlineB4 { Position: [110mm,6.333333mm] }
- Point2 BodyOutlineP5 { Position: [118mm,95mm] }
- Point2 BodyOutlineA5 { Position: [121.166667mm,113.666667mm] }
- Point2 BodyOutlineB5 { Position: [114.833333mm,76.333333mm] }
- Point2 BodyOutlineP6 { Position: [124mm,140mm] }
- Point2 BodyOutlineA6 { Position: [123.166667mm,150.833333mm] }
- Point2 BodyOutlineB6 { Position: [124.833333mm,129.166667mm] }
- Point2 BodyOutlineP7 { Position: [113mm,160mm] }
- Point2 BodyOutlineA7 { Position: [107.5mm,160.333333mm] }
- Point2 BodyOutlineB7 { Position: [118.5mm,159.666667mm] }
- Point2 BodyOutlineP8 { Position: [91mm,142mm] }
- Point2 BodyOutlineA8 { Position: [80.166667mm,138.166667mm] }
- Point2 BodyOutlineB8 { Position: [101.833333mm,145.833333mm] }
- Point2 BodyOutlineP9 { Position: [48mm,137mm] }
- Point2 BodyOutlineA9 { Position: [37.5mm,147.333333mm] }
- Point2 BodyOutlineB9 { Position: [58.5mm,126.666667mm] }
- Point2 BodyOutlineP10 { Position: [28mm,204mm] }
- Point2 BodyOutlineA10 { Position: [13mm,215.333333mm] }
- Point2 BodyOutlineB10 { Position: [43mm,192.666667mm] }
- Point2 BodyOutlineP11 { Position: [-42mm,205mm] }
- Point2 BodyOutlineA11 { Position: [-65.166667mm,200mm] }
- Point2 BodyOutlineB11 { Position: [-18.833333mm,210mm] }
- Point2 BodyOutlineP12 { Position: [-111mm,174mm] }
- Point2 BodyOutlineA12 { Position: [-123.833333mm,159mm] }
- Point2 BodyOutlineB12 { Position: [-98.166667mm,189mm] }
- Point2 BodyOutlineP13 { Position: [-119mm,115mm] }
- Point2 BodyOutlineA13 { Position: [-116.333333mm,92.666667mm] }
- Point2 BodyOutlineB13 { Position: [-121.666667mm,137.333333mm] }
- Point2 BodyOutlineP14 { Position: [-95mm,40mm] }
- Point2 BodyOutlineA14 { Position: [-98mm,15.5mm] }
- Point2 BodyOutlineB14 { Position: [-92mm,64.5mm] }
- Point2 BodyOutlineP15 { Position: [-137mm,-32mm] }
- Point2 BodyOutlineA15 { Position: [-149.166667mm,-57.833333mm] }
- Point2 BodyOutlineB15 { Position: [-124.833333mm,-6.166667mm] }
- Point2 BodyOutlineP16 { Position: [-168mm,-115mm] }
- Point2 BodyOutlineA16 { Position: [-164.333333mm,-142.166667mm] }
- Point2 BodyOutlineB16 { Position: [-171.666667mm,-87.833333mm] }
- Point2 BodyOutlineP17 { Position: [-115mm,-195mm] }
- Point2 BodyOutlineA17 { Position: [-87mm,-212.5mm] }
- Point2 BodyOutlineB17 { Position: [-143mm,-177.5mm] }
- CubicBezier2 BodyOutlineC0 { From: BodyOutlineP0; Control1: BodyOutlineA0; Control2: BodyOutlineB1; To: BodyOutlineP1 }
- CubicBezier2 BodyOutlineC1 { From: BodyOutlineP1; Control1: BodyOutlineA1; Control2: BodyOutlineB2; To: BodyOutlineP2 }
- CubicBezier2 BodyOutlineC2 { From: BodyOutlineP2; Control1: BodyOutlineA2; Control2: BodyOutlineB3; To: BodyOutlineP3 }
- CubicBezier2 BodyOutlineC3 { From: BodyOutlineP3; Control1: BodyOutlineA3; Control2: BodyOutlineB4; To: BodyOutlineP4 }
- CubicBezier2 BodyOutlineC4 { From: BodyOutlineP4; Control1: BodyOutlineA4; Control2: BodyOutlineB5; To: BodyOutlineP5 }
- CubicBezier2 BodyOutlineC5 { From: BodyOutlineP5; Control1: BodyOutlineA5; Control2: BodyOutlineB6; To: BodyOutlineP6 }
- CubicBezier2 BodyOutlineC6 { From: BodyOutlineP6; Control1: BodyOutlineA6; Control2: BodyOutlineB7; To: BodyOutlineP7 }
- CubicBezier2 BodyOutlineC7 { From: BodyOutlineP7; Control1: BodyOutlineA7; Control2: BodyOutlineB8; To: BodyOutlineP8 }
- CubicBezier2 BodyOutlineC8 { From: BodyOutlineP8; Control1: BodyOutlineA8; Control2: BodyOutlineB9; To: BodyOutlineP9 }
- CubicBezier2 BodyOutlineC9 { From: BodyOutlineP9; Control1: BodyOutlineA9; Control2: BodyOutlineB10; To: BodyOutlineP10 }
- CubicBezier2 BodyOutlineC10 { From: BodyOutlineP10; Control1: BodyOutlineA10; Control2: BodyOutlineB11; To: BodyOutlineP11 }
- CubicBezier2 BodyOutlineC11 { From: BodyOutlineP11; Control1: BodyOutlineA11; Control2: BodyOutlineB12; To: BodyOutlineP12 }
- CubicBezier2 BodyOutlineC12 { From: BodyOutlineP12; Control1: BodyOutlineA12; Control2: BodyOutlineB13; To: BodyOutlineP13 }
- CubicBezier2 BodyOutlineC13 { From: BodyOutlineP13; Control1: BodyOutlineA13; Control2: BodyOutlineB14; To: BodyOutlineP14 }
- CubicBezier2 BodyOutlineC14 { From: BodyOutlineP14; Control1: BodyOutlineA14; Control2: BodyOutlineB15; To: BodyOutlineP15 }
- CubicBezier2 BodyOutlineC15 { From: BodyOutlineP15; Control1: BodyOutlineA15; Control2: BodyOutlineB16; To: BodyOutlineP16 }
- CubicBezier2 BodyOutlineC16 { From: BodyOutlineP16; Control1: BodyOutlineA16; Control2: BodyOutlineB17; To: BodyOutlineP17 }
- CubicBezier2 BodyOutlineC17 { From: BodyOutlineP17; Control1: BodyOutlineA17; Control2: BodyOutlineB0; To: BodyOutlineP0 }
- Profile BodyOutline { Loop Outer {
- Segment Edge0 { Trace: BodyOutlineC0; From: BodyOutlineP0; To: BodyOutlineP1 }
- Segment Edge1 { Trace: BodyOutlineC1; From: BodyOutlineP1; To: BodyOutlineP2 }
- Segment Edge2 { Trace: BodyOutlineC2; From: BodyOutlineP2; To: BodyOutlineP3 }
- Segment Edge3 { Trace: BodyOutlineC3; From: BodyOutlineP3; To: BodyOutlineP4 }
- Segment Edge4 { Trace: BodyOutlineC4; From: BodyOutlineP4; To: BodyOutlineP5 }
- Segment Edge5 { Trace: BodyOutlineC5; From: BodyOutlineP5; To: BodyOutlineP6 }
- Segment Edge6 { Trace: BodyOutlineC6; From: BodyOutlineP6; To: BodyOutlineP7 }
- Segment Edge7 { Trace: BodyOutlineC7; From: BodyOutlineP7; To: BodyOutlineP8 }
- Segment Edge8 { Trace: BodyOutlineC8; From: BodyOutlineP8; To: BodyOutlineP9 }
- Segment Edge9 { Trace: BodyOutlineC9; From: BodyOutlineP9; To: BodyOutlineP10 }
- Segment Edge10 { Trace: BodyOutlineC10; From: BodyOutlineP10; To: BodyOutlineP11 }
- Segment Edge11 { Trace: BodyOutlineC11; From: BodyOutlineP11; To: BodyOutlineP12 }
- Segment Edge12 { Trace: BodyOutlineC12; From: BodyOutlineP12; To: BodyOutlineP13 }
- Segment Edge13 { Trace: BodyOutlineC13; From: BodyOutlineP13; To: BodyOutlineP14 }
- Segment Edge14 { Trace: BodyOutlineC14; From: BodyOutlineP14; To: BodyOutlineP15 }
- Segment Edge15 { Trace: BodyOutlineC15; From: BodyOutlineP15; To: BodyOutlineP16 }
- Segment Edge16 { Trace: BodyOutlineC16; From: BodyOutlineP16; To: BodyOutlineP17 }
- Segment Edge17 { Trace: BodyOutlineC17; From: BodyOutlineP17; To: BodyOutlineP0 }
- } }
+// Shared named body boundary; no authored spline control cage.
+Static Landmarks: Set<Point2> {
+ Tail => Point2(0mm,-220mm)
+ TrebleWaist => Point2(105mm,28mm)
+ Horn => Point2(113mm,160mm)
+ NeckSeat => Point2(28mm,204mm)
+ BassShoulder => Point2(-111mm,174mm)
+ BassWaist => Point2(-95mm,40mm)
+}
+Concept Struct BodyLayout {
+ Polygon2<Explicit> Scaffold { Vertices: Landmarks }
+}
+Profile BodyOutline Using BodyLayout {
+ From: Scaffold
+ Replace LowerTreble {
+ On: Scaffold.Tail_TrebleWaist
+ Through: [[115mm,-195mm], [168mm,-115mm], [148mm,-35mm]]
+ Derivatives: [[115mm,0mm], [84mm,52.5mm], [16.5mm,80mm], [-31.5mm,71.5mm], [-15mm,65mm]]
+ }
+ Replace HornRise {
+ On: Scaffold.TrebleWaist_Horn
+ Through: [[118mm,95mm], [124mm,140mm]]
+ Derivatives: [[-15mm,65mm], [9.5mm,56mm], [-2.5mm,32.5mm], [-16.5mm,1mm]]
+ }
+ Replace Cutaway {
+ On: Scaffold.Horn_NeckSeat
+ Through: [[91mm,142mm], [48mm,137mm]]
+ Derivatives: [[-16.5mm,1mm], [-32.5mm,-11.5mm], [-31.5mm,31mm], [-45mm,34mm]]
+ }
+ Replace Shoulder {
+ On: Scaffold.NeckSeat_BassShoulder
+ Through: [[-42mm,205mm]]
+ Derivatives: [[-45mm,34mm], [-69.5mm,-15mm], [-38.5mm,-45mm]]
+ }
+ Replace UpperBass {
+ On: Scaffold.BassShoulder_BassWaist
+ Through: [[-119mm,115mm]]
+ Derivatives: [[-38.5mm,-45mm], [8mm,-67mm], [-9mm,-73.5mm]]
+ }
+ Replace LowerBass {
+ On: Scaffold.BassWaist_Tail
+ Through: [[-137mm,-32mm], [-168mm,-115mm], [-115mm,-195mm]]
+ Derivatives: [[-9mm,-73.5mm], [-36.5mm,-77.5mm], [11mm,-81.5mm], [84mm,-52.5mm], [115mm,0mm]]
+ }
+}
diff --git a/fixtures/Canonical/Boundary2/edited-panel.firmament b/fixtures/Canonical/Boundary2/edited-panel.firmament
new file mode 100644
index 00000000..b1e94ac6
--- /dev/null
+++ b/fixtures/Canonical/Boundary2/edited-panel.firmament
@@ -0,0 +1,20 @@
+Use Profile.Modifications;
+Model EditedPanel {
+ Units: mm
+ Concept Struct Layout {
+ Rect2 Blank { Center: [0mm,0mm]; Size: [120mm,80mm] }
+ }
+ Static ServiceTab: ProfileTabSpec { Center: 60mm; Width: 24mm; Extension: 8mm }
+ ProfileDelta ServiceTabEdit = Tab<P: ServiceTab, Owner: Layout.Blank.Top>
+ Profile Panel Using Layout {
+ From: Blank
+ Apply ServiceTabEdit
+ Replace Grip {
+ On: Blank.Right
+ Range: [20mm,60mm]
+ Through: [[48mm,-10mm], [48mm,10mm]]
+ Join: Tangent
+ }
+ }
+ Extrude Body { Profile: Panel From: 0mm To: 3mm }
+}
diff --git a/fixtures/Invalid/Boundary2/edit-crossing.firmament b/fixtures/Invalid/Boundary2/edit-crossing.firmament
new file mode 100644
index 00000000..49edcc9e
--- /dev/null
+++ b/fixtures/Invalid/Boundary2/edit-crossing.firmament
@@ -0,0 +1,9 @@
+Model CrossingEdit {
+ Units: mm
+ Rect2 Blank { Center: [0mm,0mm]; Size: [120mm,80mm] }
+ Profile Panel {
+ From: Blank
+ Replace Grip { On: Blank.Right; Range: [20mm,60mm]; Through: [[-100mm,0mm]] }
+ }
+ Extrude Body { Profile: Panel From: 0mm To: 3mm }
+}
diff --git a/fixtures/Invalid/Boundary2/edit-overlap.firmament b/fixtures/Invalid/Boundary2/edit-overlap.firmament
new file mode 100644
index 00000000..e9d546b1
--- /dev/null
+++ b/fixtures/Invalid/Boundary2/edit-overlap.firmament
@@ -0,0 +1,10 @@
+Model OverlappingEdits {
+ Units: mm
+ Rect2 Blank { Center: [0mm,0mm]; Size: [120mm,80mm] }
+ Profile Panel {
+ From: Blank
+ Replace First { On: Blank.Right; Range: [20mm,60mm]; Through: [[48mm,0mm]] }
+ Replace Second { On: Blank.Right; Range: [30mm,70mm]; Through: [[50mm,0mm]] }
+ }
+ Extrude Body { Profile: Panel From: 0mm To: 3mm }
+}
diff --git a/scripts/create-guitar-x0.py b/scripts/create-guitar-x0.py
index c0de6630..9ed7e539 100644
--- a/scripts/create-guitar-x0.py
+++ b/scripts/create-guitar-x0.py
@@ -53,14 +53,44 @@ def body_chain(name, stations, continuity):
rows.append(f' Profile P{i} Using SectionLayout {{ Loop Outer {{ Outline{i} |> TraceLoop }} }}')
rows.append(f' SectionChain {name} {{ Continuity: {continuity}')
for i in range(len(stations)):
- rows.append(f' Section S{i} {{ Frame: F{i}\n Profile: P{i}\n Seam: Edge0 }}')
+ rows.append(f' Section S{i} {{ Frame: F{i}\n Profile: P{i}\n Seam: LowerTreble_Span0 }}')
rows.extend([' Start: Cap', ' End: Cap', ' }'])
if name == 'CarvedMaple':
rows.append(' Expose { Semantic TopSeat { DatumFrame Frame = CarvedMaple.Section.S4.Frame; } }')
rows.append('}')
(ROOT/f'{name}.firmament').write_text('\n'.join(rows)+'\n')
-(ROOT/'body-outline.firmament').write_text('// Shared authored single-cut boundary; Concept placements derive each section.\n'+profile('BodyOutline',OUTLINE)+'\n')
+def body_outline():
+ # Named Concept chords are the closed seed. Pure Profile edits inherit their
+ # endpoints; explicit Hermite derivatives preserve the existing silhouette.
+ groups = [('Tail', 'LowerTreble', 0), ('TrebleWaist', 'HornRise', 4),
+ ('Horn', 'Cutaway', 7), ('NeckSeat', 'Shoulder', 10),
+ ('BassShoulder', 'UpperBass', 12), ('BassWaist', 'LowerBass', 14)]
+ vector = lambda p: '[' + ','.join(number(v)+'mm' for v in p) + ']'
+ rows = ['// Shared named body boundary; no authored spline control cage.',
+ 'Static Landmarks: Set<Point2> {']
+ for landmark, _, index in groups:
+ x,y = OUTLINE[index]
+ rows.append(f' {landmark} => Point2({number(x)}mm,{number(y)}mm)')
+ rows.extend(['}', 'Concept Struct BodyLayout {',
+ ' Polygon2<Explicit> Scaffold { Vertices: Landmarks }', '}',
+ 'Profile BodyOutline Using BodyLayout {', ' From: Scaffold'])
+ for k,(landmark,edit,start) in enumerate(groups):
+ next_landmark,_,end = groups[(k+1)%len(groups)]
+ if end <= start: end += len(OUTLINE)
+ knots = list(range(start,end+1))
+ through = ', '.join(vector(OUTLINE[i%len(OUTLINE)]) for i in knots[1:-1])
+ derivatives = []
+ for i in knots:
+ before,after = OUTLINE[(i-1)%len(OUTLINE)],OUTLINE[(i+1)%len(OUTLINE)]
+ derivatives.append(((after[0]-before[0])/2,(after[1]-before[1])/2))
+ rows.extend([f' Replace {edit} {{', f' On: Scaffold.{landmark}_{next_landmark}',
+ f' Through: [{through}]',
+ ' Derivatives: ['+', '.join(vector(d) for d in derivatives)+']', ' }'])
+ rows.append('}')
+ return '\n'.join(rows)+'\n'
+
+(ROOT/'body-outline.firmament').write_text(body_outline())
body_chain('MahoganyBack',[(0,1),(38,1)],'G0')
body_chain('IvoryBinding',[(38,1),(40,1)],'G0')
body_chain('CarvedMaple',[(40,.992),(43,.955),(48,.84),(52,.76),(53,.72)],'G1')