Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add deterministic straight-edge fillet support
Yuechen Li5b8174cb7652
diff --git a/Aetheris.CLI.Tests/ProfileStraightEdgeFilletInspectionTests.cs b/Aetheris.CLI.Tests/ProfileStraightEdgeFilletInspectionTests.csnew file mode 100644index 00000000..45ae05eb--- /dev/null+++ b/Aetheris.CLI.Tests/ProfileStraightEdgeFilletInspectionTests.cs@@ -0,0 +1,32 @@+using System.Text.Json;++namespace Aetheris.CLI.Tests;++public sealed class ProfileStraightEdgeFilletInspectionTests+{+ [Fact]+ public void InspectProfile_ReportsDeterministicStraightFilletPlan()+ {+ var source = Path.Combine(FindRepoRoot(), "fixtures", "FirmamentV2", "Canonical", "valid", "profile-straight-edge-fillet-top.firmament");+ var stdout = new StringWriter(); var stderr = new StringWriter();+ var exit = Aetheris.CLI.CliRunner.Run(["inspect-profile", source, "--json"], stdout, stderr);++ Assert.Equal(0, exit); Assert.True(string.IsNullOrWhiteSpace(stderr.ToString()), stderr.ToString());+ using var json = JsonDocument.Parse(stdout.ToString());+ var fillet = json.RootElement.GetProperty("profile").GetProperty("straightEdgeFillet");+ Assert.True(fillet.GetProperty("succeeded").GetBoolean());+ Assert.Equal("edgefinish:SouthTopRound", fillet.GetProperty("edgeFinishId").GetString());+ Assert.Equal("FilletSpanInset", fillet.GetProperty("endpointPolicy").GetString());+ Assert.Equal(new[] { 1d, 0d, 0d }, fillet.GetProperty("cylinderAxis").EnumerateArray().Select(x => x.GetDouble()).ToArray());+ Assert.Equal(new[] { 3d, 2d, 6d }, fillet.GetProperty("cylinderCenterlineStart").EnumerateArray().Select(x => x.GetDouble()).ToArray());+ Assert.Equal("DisjointNoCavitiesInBareProfileM1", fillet.GetProperty("corridorClassification").GetString());+ Assert.Contains(fillet.GetProperty("generatedDescendants").EnumerateArray().Select(x => x.GetString()), x => x!.EndsWith(":FilletSurface", StringComparison.Ordinal));+ }++ private static string FindRepoRoot()+ {+ var directory = new DirectoryInfo(AppContext.BaseDirectory);+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;+ return directory?.FullName ?? throw new DirectoryNotFoundException("Repository root was not found.");+ }+}diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 26a0fb2b..04dbb55c 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -4,6 +4,7 @@ using System.Text.Json;using System.Text.Json.Serialization;using Aetheris.Forge.Abstractions.FirmamentInterop;using Aetheris.Kernel.Core.Brep.Verification;+using Aetheris.Kernel.Core.Math;using Aetheris.Kernel.Core.Step242;using Aetheris.Kernel.Firmament;using Aetheris.Kernel.Firmament.Assembly;@@ -458,6 +459,7 @@ public static class CliRunner}),validation.IsValid, validation.SignedArea, validation.Diagnostics,junctions = DescribeProfileJunctions(parsed.Profile, source, parsed.Profile.Name),+ straightEdgeFillet = DescribeProfileStraightEdgeFillet(parsed.Profile, source, parsed.Profile.Name),extrusionHeight = parsed.Height,brepPlan = plan.Plan is null ? null : new{@@ -3224,6 +3226,29 @@ public static class CliRunnerstring VertexId, double SignedTurnDegrees, double MaterialInteriorAngleDegrees,string Classification, bool SelectedByEdgeFinish, IReadOnlyList<string> GeneratedDescendants);+ private sealed record ProfileStraightEdgeFilletInspection(+ bool Succeeded, string? Diagnostic, string? EdgeFinishId, string? ProfileId, string? LoopId, string? SegmentId,+ string? Side, double? Radius, double? EndClearance, string? EndpointPolicy,+ double[]? CylinderAxis, double[]? CylinderCenterlineStart, double[]? CylinderCenterlineEnd,+ double[]? CapContactStart, double[]? CapContactEnd, double[]? SideContactStart, double[]? SideContactEnd,+ string CorridorClassification, IReadOnlyList<string> GeneratedDescendants, IReadOnlyList<string> Provenance);++ private static ProfileStraightEdgeFilletInspection? DescribeProfileStraightEdgeFillet(ResolvedProfile2D profile, string source, string hostBodyId)+ {+ if (!ProfileBoundaryChamferSourceBinder.HasProfileBoundaryFillet(source)) return null;+ if (!ProfileBoundaryChamferSourceBinder.TryBindFillet(source, profile, hostBodyId, out var target, out var radius, out var clearance, out var diagnostic))+ return new(false, diagnostic, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, "RejectedBeforePlan", [], []);+ var result = ProfileStraightEdgeFilletPlanner.TryPlan(profile, target!, radius, clearance);+ if (!result.Succeeded || result.Plan is null)+ return new(false, result.Diagnostics.FirstOrDefault(), target!.StableId, target.ProfileId, target.LoopId, target.SegmentIds.Single(), target.Side.ToString(), radius, clearance, null, null, null, null, null, null, null, null, "RejectedBeforeTopology", [], []);+ var plan = result.Plan;+ static double[] V(Direction3D value) => [value.ToVector().X, value.ToVector().Y, value.ToVector().Z];+ static double[] P(Point3D value) => [value.X, value.Y, value.Z];+ return new(true, null, target!.StableId, target.ProfileId, target.LoopId, target.SegmentIds.Single(), target.Side.ToString(), radius, clearance, plan.EndpointPolicy,+ V(plan.Tangent), P(plan.CylinderCenterlineStart), P(plan.CylinderCenterlineEnd), P(plan.CapContactStart), P(plan.CapContactEnd), P(plan.SideContactStart), P(plan.SideContactEnd),+ "DisjointNoCavitiesInBareProfileM1", result.Correspondence?.Descendants.Select(x => x.StableId).OrderBy(x => x, StringComparer.Ordinal).ToArray() ?? [], result.Correspondence?.ProvenanceChain ?? []);+ }+private static IReadOnlyList<ProfileJunctionInspection> DescribeProfileJunctions(ResolvedProfile2D profile, string source, string hostBodyId){ProfileBoundaryChamferTarget? target = null;diff --git a/Aetheris.Kernel.Firmament.Tests/Integration/ProfileBoundaryChamferFixtureTests.cs b/Aetheris.Kernel.Firmament.Tests/Integration/ProfileBoundaryChamferFixtureTests.csindex 0cb5acbf..e5143ee3 100644--- a/Aetheris.Kernel.Firmament.Tests/Integration/ProfileBoundaryChamferFixtureTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/Integration/ProfileBoundaryChamferFixtureTests.cs@@ -63,11 +63,39 @@ public sealed class ProfileBoundaryChamferFixtureTests}}+ [Theory]+ [InlineData("profile-straight-edge-fillet-top.firmament")]+ [InlineData("profile-straight-edge-fillet-bottom.firmament")]+ public void StraightFilletFixture_ExportsDeterministicExactCylinderAndEndpointArcs(string fixtureName)+ {+ var source = FirmamentCorpusHarness.ResolveFixtureFullPath($"fixtures/FirmamentV2/Canonical/valid/{fixtureName}");+ var firstOutput = Path.Combine(Path.GetTempPath(), $"aetheris-{Guid.NewGuid():N}.step");+ var secondOutput = Path.Combine(Path.GetTempPath(), $"aetheris-{Guid.NewGuid():N}.step");+ try+ {+ var first = FirmamentBuildAndExport.Run(source, firstOutput); var second = FirmamentBuildAndExport.Run(source, secondOutput);+ Assert.True(first.IsSuccess, string.Join(Environment.NewLine, first.Diagnostics.Select(x => x.Message)));+ Assert.True(second.IsSuccess, string.Join(Environment.NewLine, second.Diagnostics.Select(x => x.Message)));+ Assert.Equal(first.Value.Export.StepText, second.Value.Export.StepText);+ var imported = Step242Importer.ImportBody(first.Value.Export.StepText);+ Assert.True(imported.IsSuccess, string.Join(Environment.NewLine, imported.Diagnostics.Select(x => x.Message)));+ Assert.Equal(1, imported.Value!.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Cylinder));+ Assert.Equal(2, imported.Value.Geometry.Curves.Count(c => c.Value.Kind == CurveGeometryKind.Circle3));+ Assert.True(BrepMassProperties.Evaluate(imported.Value).IsEnclosed);+ }+ finally+ {+ if (File.Exists(firstOutput)) File.Delete(firstOutput);+ if (File.Exists(secondOutput)) File.Delete(secondOutput);+ }+ }+[Theory][InlineData("profile-compose-reflex-chamfer-shaft-collision.firmament", "ProfileBoundaryChamferIntersectsShaft")][InlineData("profile-compose-reflex-chamfer-counterbore-collision.firmament", "ProfileBoundaryChamferIntersectsCounterbore")][InlineData("profile-chamfer-reflex-inset-collapse.firmament", "ProfileBoundaryChamferInsetCollapse")][InlineData("profile-fillet-reflex-junction-not-materialized.firmament", "ProfileBoundaryFilletNotMaterialized")]+ [InlineData("profile-straight-edge-fillet-shaft-collision.firmament", "ProfileBoundaryFilletIntersectsShaft")]public void InvalidFixture_ProducesTypedProfileBoundaryDiagnostic(string fixtureName, string diagnostic){var source = FirmamentCorpusHarness.ResolveFixtureFullPath($"fixtures/FirmamentV2/Canonical/invalid/{fixtureName}");diff --git a/Aetheris.Kernel.Firmament.Tests/Integration/ProfileBoundaryChamferTests.cs b/Aetheris.Kernel.Firmament.Tests/Integration/ProfileBoundaryChamferTests.csindex 69799ade..29aee911 100644--- a/Aetheris.Kernel.Firmament.Tests/Integration/ProfileBoundaryChamferTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/Integration/ProfileBoundaryChamferTests.cs@@ -82,6 +82,54 @@ public sealed class ProfileBoundaryChamferTestsAssert.Equal("ProfileBoundaryFilletNotMaterialized", diagnostic);}+ [Theory]+ [InlineData("Top")]+ [InlineData("Bottom")]+ public void PlansFiniteStraightProfileFilletWithExactCylindricalFace(string side)+ {+ var source = $"Modify Body {{ EdgeFinish Round {{ Target: Bracket.Outer.South On: {side} Kind: Fillet Radius: 2mm EndClearance: 3mm }} }}";+ Assert.True(ProfileBoundaryChamferSourceBinder.TryBindFillet(source, Profile(), "Bracket", out var target, out var radius, out var clearance, out var diagnostic), diagnostic);+ var result = ProfileStraightEdgeFilletPlanner.TryPlan(Profile(), target!, radius, clearance);+ Assert.True(result.Succeeded, string.Join("; ", result.Diagnostics));+ var counts = result.Body!.Topology.Faces.SelectMany(face => face.LoopIds).SelectMany(id => result.Body.Topology.Loops.Single(loop => loop.Id == id).CoedgeIds).Select(id => result.Body.Topology.Coedges.Single(coedge => coedge.Id == id).EdgeId).GroupBy(id => id).ToDictionary(x => x.Key, x => x.Count());+ Assert.Equal(result.Body.Topology.Edges.Count(), counts.Count);+ Assert.All(counts, item => Assert.True(item.Value == 2, $"edge {item.Key.Value}: {item.Value}"));+ Assert.Contains(result.Correspondence!.Descendants, x => x.Role == SemanticTopologyRole.FilletSurface);+ }++ [Fact]+ public void FilletPlanUsesDocumentedInsetCenterlineAndTypedRejections()+ {+ const string source = "Modify Body { EdgeFinish Round { Target: Bracket.Outer.South On: Top Kind: Fillet Radius: 2mm EndClearance: 3mm } }";+ Assert.True(ProfileBoundaryChamferSourceBinder.TryBindFillet(source, Profile(), "Bracket", out var target, out var radius, out var clearance, out var diagnostic), diagnostic);+ var result = ProfileStraightEdgeFilletPlanner.TryPlan(Profile(), target!, radius, clearance);+ Assert.True(result.Succeeded);+ Assert.Equal(3d, result.Plan!.SpanStart.X, 8);+ Assert.Equal(17d, result.Plan.SpanEnd.X, 8);+ Assert.Equal(2d, result.Plan.CylinderCenterlineStart.Y, 8);+ Assert.Equal(6d, result.Plan.CylinderCenterlineStart.Z, 8);++ Assert.False(ProfileBoundaryChamferSourceBinder.TryBindFillet("Modify Body { EdgeFinish Bad { Target: Bracket.Outer.South On: Top Kind: Fillet Radius: 0mm } }", Profile(), "Bracket", out _, out _, out _, out diagnostic));+ Assert.Equal("ProfileBoundaryFilletRadiusMustBePositive", diagnostic);+ Assert.False(ProfileBoundaryChamferSourceBinder.TryBindFillet("Modify Body { EdgeFinish Bad { Target: Bracket.Outer On: Top Kind: Fillet Radius: 2mm } }", Profile(), "Bracket", out _, out _, out _, out diagnostic));+ Assert.Equal("ProfileBoundaryFilletWholeLoopUnsupported", diagnostic);+ var tooShort = ProfileStraightEdgeFilletPlanner.TryPlan(Profile(), target!, 2d, 10d);+ Assert.False(tooShort.Succeeded);+ Assert.Contains("ProfileBoundaryFilletSegmentTooShort", tooShort.Diagnostics);+ var tooLarge = ProfileStraightEdgeFilletPlanner.TryPlan(Profile(), target!, 8d, 3d);+ Assert.False(tooLarge.Succeeded);+ Assert.Contains("ProfileBoundaryFilletRadiusExceedsHost", tooLarge.Diagnostics);+ }++ [Fact]+ public void FilletComposeCorridorRejectsShaftBeforeComposeMaterialization()+ {+ var source = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/FirmamentV2/Canonical/invalid/profile-straight-edge-fillet-shaft-collision.firmament");+ var build = FirmamentBuildAndExport.Run(source, Path.Combine(Path.GetTempPath(), $"aetheris-{Guid.NewGuid():N}.step"));+ Assert.False(build.IsSuccess);+ Assert.Contains(build.Diagnostics, x => x.Message.StartsWith("ProfileBoundaryFilletIntersectsShaft", StringComparison.Ordinal));+ }+private static ResolvedProfile2D Profile(){var points = new[] { (0d, 0d), (20d, 0d), (20d, 10d), (0d, 10d) };diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex e25ac414..3be472c4 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -260,6 +260,16 @@ public static class FirmamentBuildAndExportnew Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, code, "FirmamentV2.ComposeSemanticSelection")]);if (ProfileBoundaryChamferSourceBinder.HasSemanticProfileBoundaryFinish(source)){+ if (ProfileBoundaryChamferSourceBinder.HasProfileBoundaryFillet(source))+ {+ ProfileBoundaryChamferTarget? filletTarget = null; ResolvedProfile2D? filletProfile = null; double radius = 0d; double clearance = 0d; string? filletDiagnostic = null;+ foreach (var candidate in parsed.Profiles.Values.OrderBy(x => x.Name, StringComparer.Ordinal))+ if (ProfileBoundaryChamferSourceBinder.TryBindFillet(source, candidate, stack.Feature.Name, out filletTarget, out radius, out clearance, out filletDiagnostic)) { filletProfile = candidate; break; }+ if (filletProfile is null || filletTarget is null) return Fail(filletDiagnostic ?? "ProfileBoundaryFilletProfileUnknown");+ var filletAdmission = ProfileStraightEdgeFilletAdmissionChecker.Check(stack, filletProfile, filletTarget, radius, clearance);+ if (!filletAdmission.Disjoint) return Fail(filletAdmission.Diagnostics.FirstOrDefault() ?? "ProfileBoundaryFilletCavityInteractionUnsupported");+ return Fail("ProfileBoundaryFilletComposeUnsupported");+ }ProfileBoundaryChamferTarget? target = null; double distance = 0d; string? bindingDiagnostic = null; ResolvedProfile2D? profile = null;foreach (var candidate in parsed.Profiles.Values.OrderBy(x => x.Name, StringComparer.Ordinal)){@@ -325,6 +335,26 @@ public static class FirmamentBuildAndExportnew Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, code, "FirmamentV2.SemanticSelection")]);if (ProfileBoundaryChamferSourceBinder.HasSemanticProfileBoundaryFinish(source)){+ if (ProfileBoundaryChamferSourceBinder.HasProfileBoundaryFillet(source))+ {+ if (!ProfileBoundaryChamferSourceBinder.TryBindFillet(source, profile, profile.Name, out var filletTarget, out var radius, out var clearance, out var filletDiagnostic))+ return Fail(filletDiagnostic ?? "ProfileBoundaryFilletBindingFailed");+ var fillet = ProfileStraightEdgeFilletPlanner.TryPlan(profile, filletTarget!, radius, clearance);+ if (!fillet.Succeeded || fillet.Body is null || fillet.Correspondence is null)+ return Fail(fillet.Diagnostics.FirstOrDefault() ?? "ProfileBoundaryFilletPlanningFailed");+ if (!FirmamentManifoldChecker.IsManifold(fillet.Body)) return Fail("ProfileBoundaryFilletNonManifold");+ var filletStep = Step242Exporter.ExportBody(fillet.Body, new Step242ExportOptions+ {+ ProductName = filletTarget!.StableId,+ ApplicationName = "Aetheris.Firmament.ProfileStraightEdgeFillet.M1",+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce,+ BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute+ });+ if (!filletStep.IsSuccess || filletStep.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(filletStep.Diagnostics);+ var filletReimport = Step242Importer.ImportBody(filletStep.Value);+ if (!filletReimport.IsSuccess || filletReimport.Value is null || !FirmamentManifoldChecker.IsManifold(filletReimport.Value)) return Fail("ProfileBoundaryFilletStepReimportFailed");+ return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(filletStep.Value, filletTarget.StableId, fillet.Correspondence.Descendants.Count, "profile-straight-edge-fillet", "source-grounded-profile-straight-edge-fillet"));+ }if (!ProfileBoundaryChamferSourceBinder.TryBind(source, profile, profile.Name, out var target, out var distance, out var bindingDiagnostic))return Fail(bindingDiagnostic ?? "ProfileBoundaryChamferBindingFailed");var planned = ProfileBoundaryChamferPlanner.TryPlan(profile, target!, distance);diff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileBoundaryChamfer.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileBoundaryChamfer.csindex 9d57cb32..b2fbe916 100644--- a/Aetheris.Kernel.Firmament/Materializer/ProfileBoundaryChamfer.cs+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileBoundaryChamfer.cs@@ -23,6 +23,21 @@ public sealed record ProfileBoundaryChamferPlanResult(bool Succeeded, BrepBody? Body, SemanticTopologyCorrespondence? Correspondence,ProfileBoundaryChamferTarget? Target, IReadOnlyList<string> Diagnostics);+/// <summary>+/// M1's source-selected round. It is deliberately a separate, non-generic plan: it+/// owns one Line2 descendant and never searches a materialized B-rep for an edge.+/// </summary>+public sealed record ProfileStraightEdgeFilletPlan(+ ProfileBoundaryChamferTarget Target, double Radius, double EndClearance,+ Point3D SourceStart, Point3D SourceEnd, Point3D SpanStart, Point3D SpanEnd,+ Direction3D Tangent, Direction3D InwardNormal, Direction3D ExtrusionAxis,+ Point3D CylinderCenterlineStart, Point3D CylinderCenterlineEnd,+ Point3D CapContactStart, Point3D CapContactEnd, Point3D SideContactStart, Point3D SideContactEnd,+ string EndpointPolicy = "FilletSpanInset");+public sealed record ProfileStraightEdgeFilletPlanResult(+ bool Succeeded, BrepBody? Body, SemanticTopologyCorrespondence? Correspondence,+ ProfileStraightEdgeFilletPlan? Plan, IReadOnlyList<string> Diagnostics);+public static class ProfileBoundaryChamferSourceBinder{private static readonly Regex EdgeFinishHeader = new(@"\bEdgeFinish\s+(?<name>\w+)\s*\{", RegexOptions.CultureInvariant);@@ -31,6 +46,7 @@ public static class ProfileBoundaryChamferSourceBinderprivate static readonly Regex Kind = new(@"\bKind\s*:\s*(?<value>\w+)\b", RegexOptions.CultureInvariant);private static readonly Regex Distance = new(@"\bDistance\s*:\s*(?<value>[-+.\deE]+)mm\b", RegexOptions.CultureInvariant);private static readonly Regex Radius = new(@"\bRadius\s*:\s*(?<value>[-+.\deE]+)mm\b", RegexOptions.CultureInvariant);+ private static readonly Regex EndClearance = new(@"\bEndClearance\s*:\s*(?<value>[-+.\deE]+)mm\b", RegexOptions.CultureInvariant);private static readonly Regex SelectionHeader = new(@"\bSelection\s+(?<name>\w+)\s*\{", RegexOptions.CultureInvariant);private static readonly Regex CanonicalSelection = new(@"\bSource\s*:\s*(?<profile>\w+)\.(?<loop>\w+)\.\[\s*(?<segments>[\w\s,]+)\s*\]", RegexOptions.CultureInvariant);private static readonly Regex HistoricalSelection = new(@"\bSource\s*:\s*(?<profile>\w+)\.ProfileSegments\s*\(\s*\[(?<segments>[\w\s,]+)\]\s*\)", RegexOptions.CultureInvariant);@@ -43,6 +59,42 @@ public static class ProfileBoundaryChamferSourceBinderreturn body is not null && On.IsMatch(body);});+ public static bool HasProfileBoundaryFillet(string source) => EdgeFinishHeader.Matches(source).Cast<Match>().Any(header =>+ {+ var body = Block(source, header.Index + header.Length - 1);+ return body is not null && On.IsMatch(body) && string.Equals(Kind.Match(body).Groups["value"].Value, "Fillet", StringComparison.Ordinal);+ });++ /// <summary>Parses M1's explicit source form. EndClearance defaults to Radius;+ /// the default is visible in inspection and therefore never silently changes span.</summary>+ public static bool TryBindFillet(string source, ResolvedProfile2D profile, string hostBodyId, out ProfileBoundaryChamferTarget? target, out double radius, out double endClearance, out string? diagnostic)+ {+ target = null; radius = 0d; endClearance = 0d; diagnostic = null;+ var finish = EdgeFinishHeader.Matches(source).Cast<Match>().Select(match => (Match: match, Body: Block(source, match.Index + match.Length - 1))).FirstOrDefault(x => x.Body is not null && On.IsMatch(x.Body) && string.Equals(Kind.Match(x.Body).Groups["value"].Value, "Fillet", StringComparison.Ordinal));+ if (finish.Body is null) { diagnostic = "ProfileBoundaryFilletBoundaryRequired"; return false; }+ var radiusMatch = Radius.Match(finish.Body); var clearanceMatch = EndClearance.Match(finish.Body);+ if (!radiusMatch.Success || !double.TryParse(radiusMatch.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out radius) || !double.IsFinite(radius) || radius <= 0d) { diagnostic = "ProfileBoundaryFilletRadiusMustBePositive"; return false; }+ endClearance = clearanceMatch.Success && double.TryParse(clearanceMatch.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var explicitClearance) ? explicitClearance : radius;+ if (!double.IsFinite(endClearance) || endClearance <= 0d) { diagnostic = "ProfileBoundaryFilletEndClearanceMustBePositive"; return false; }++ var targetMatch = Target.Match(finish.Body); var on = On.Match(finish.Body);+ if (!targetMatch.Success || !on.Success) { diagnostic = "ProfileBoundaryFilletDeclarationInvalid"; return false; }+ var rawTarget = targetMatch.Groups["value"].Value; var parts = rawTarget.Split('.');+ // A named Selection can denote a connected chain. M1 intentionally keeps+ // that historical materialization boundary rather than pretending it is a+ // single segment; direct Profile.Loop remains a precise whole-loop error.+ if (parts.Length != 3) { diagnostic = parts.Length == 2 ? "ProfileBoundaryFilletWholeLoopUnsupported" : "ProfileBoundaryFilletNotMaterialized"; return false; }+ if (!string.Equals(parts[0], profile.Name, StringComparison.Ordinal)) { diagnostic = "ProfileBoundaryFilletProfileUnknown"; return false; }+ var loop = profile.Loops.SingleOrDefault(x => string.Equals(x.Name, parts[1], StringComparison.Ordinal));+ if (loop is null) { diagnostic = "ProfileBoundaryFilletLoopUnknown"; return false; }+ if (!loop.IsOuter) { diagnostic = "ProfileBoundaryFilletInnerLoopUnsupported"; return false; }+ var segment = loop.Segments.SingleOrDefault(x => string.Equals(x.Name, parts[2], StringComparison.Ordinal));+ if (segment is null) { diagnostic = "ProfileBoundaryFilletSegmentUnknown"; return false; }+ if (segment.Geometry is not LineArcLineSegment2D) { diagnostic = "ProfileBoundaryFilletSegmentKindUnsupported"; return false; }+ target = new($"edgefinish:{finish.Match.Groups["name"].Value}", hostBodyId, profile.Name, loop.Name, [segment.Name], Enum.Parse<ProfileBoundaryChamferSide>(on.Groups["value"].Value), ProfileBoundaryChamferChainKind.SingleSegment, $"offset:{finish.Match.Index}", "DirectProfileBoundaryTarget");+ return true;+ }+public static bool TryBind(string source, ResolvedProfile2D profile, string hostBodyId, out ProfileBoundaryChamferTarget? target, out double distance, out string? diagnostic){target = null; distance = 0d; diagnostic = null;@@ -373,3 +425,208 @@ public static class ProfileBoundaryChamferPlannerprivate static double Distance((double X, double Y) a, (double X, double Y) b) => Math.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y));private static int IndexOf(ResolvedProfileLoop2D loop, string segmentId) => loop.Segments.Select((segment, index) => (segment, index)).Single(x => x.segment.Name == segmentId).index;}++/// <summary>+/// Authoritative M1 materializer for a finite straight Profile-boundary round. The+/// end faces are quarter-discs in planes normal to the selected segment; this keeps+/// the adjacent Profile junctions sharp and outside the solved topology.+/// </summary>+public static class ProfileStraightEdgeFilletPlanner+{+ private const double Tol = 1e-8;++ public static ProfileStraightEdgeFilletPlanResult TryPlan(ResolvedProfile2D profile, ProfileBoundaryChamferTarget target, double radius, double clearance)+ {+ ProfileStraightEdgeFilletPlanResult Fail(string code) => new(false, null, null, null, [code]);+ var loop = profile.Loops.SingleOrDefault(x => x.Name == target.LoopId);+ if (loop is null) return Fail("ProfileBoundaryFilletLoopUnknown");+ if (!loop.IsOuter || profile.Loops.Count != 1) return Fail("ProfileBoundaryFilletInnerLoopUnsupported");+ if (target.ChainKind != ProfileBoundaryChamferChainKind.SingleSegment || target.SegmentIds.Count != 1) return Fail("ProfileBoundaryFilletConnectedChainUnsupported");+ if (loop.Segments.Any(x => x.Geometry is not LineArcLineSegment2D)) return Fail("ProfileBoundaryFilletEndpointTerminationUnsupported");+ var index = loop.Segments.Select((x, i) => (x, i)).Where(x => x.x.Name == target.SegmentIds[0]).Select(x => x.i).DefaultIfEmpty(-1).Single();+ if (index < 0) return Fail("ProfileBoundaryFilletSegmentUnknown");+ var line = (LineArcLineSegment2D)loop.Segments[index].Geometry;+ var dx = line.End.X - line.Start.X; var dy = line.End.Y - line.Start.Y; var length = Math.Sqrt(dx * dx + dy * dy);+ if (length <= 2d * clearance + Tol) return Fail("ProfileBoundaryFilletSegmentTooShort");+ var start = profile.LocalStartDepth ?? -1d; var end = profile.LocalEndDepth ?? 1d; var thickness = end - start;+ if (radius >= thickness - Tol) return Fail("ProfileBoundaryFilletRadiusExceedsHost");+ var signedArea = loop.Segments.Cast<ResolvedProfileSegment2D>().Select(x => (LineArcLineSegment2D)x.Geometry).Select((x, i) => x.Start.X * ((LineArcLineSegment2D)loop.Segments[(i + 1) % loop.Segments.Count].Geometry).Start.Y - ((LineArcLineSegment2D)loop.Segments[(i + 1) % loop.Segments.Count].Geometry).Start.X * x.Start.Y).Sum() * .5d;+ if (Math.Abs(signedArea) <= Tol) return Fail("ProfileBoundaryFilletEndpointTerminationUnsupported");+ var frame = profile.EffectiveConstructionPlane;+ var tangent = Direction3D.Create(frame.ToWorldDirection(new Vector3D(dx / length, dy / length, 0d)));+ var inward2 = signedArea > 0d ? (-dy / length, dx / length) : (dy / length, -dx / length);+ var inward = Direction3D.Create(frame.ToWorldDirection(new Vector3D(inward2.Item1, inward2.Item2, 0d)));+ var axis = frame.AxisZ;+ var station = target.Side == ProfileBoundaryChamferSide.Top ? end : start;+ var axialIntoBody = target.Side == ProfileBoundaryChamferSide.Top ? -axis.ToVector() : axis.ToVector();+ var sourceStart = frame.ToWorld(line.Start, station); var sourceEnd = frame.ToWorld(line.End, station);+ var spanStart = sourceStart + tangent.ToVector() * clearance; var spanEnd = sourceEnd - tangent.ToVector() * clearance;+ var centerStart = spanStart + inward.ToVector() * radius + axialIntoBody * radius;+ var centerEnd = spanEnd + inward.ToVector() * radius + axialIntoBody * radius;+ var capStart = spanStart + inward.ToVector() * radius; var capEnd = spanEnd + inward.ToVector() * radius;+ var sideStart = spanStart + axialIntoBody * radius; var sideEnd = spanEnd + axialIntoBody * radius;+ var plan = new ProfileStraightEdgeFilletPlan(target, radius, clearance, sourceStart, sourceEnd, spanStart, spanEnd, tangent, inward, axis, centerStart, centerEnd, capStart, capEnd, sideStart, sideEnd);+ return BuildBody(profile, loop, index, plan, start, end);+ }++ private static ProfileStraightEdgeFilletPlanResult BuildBody(ResolvedProfile2D profile, ResolvedProfileLoop2D loop, int selected, ProfileStraightEdgeFilletPlan plan, double start, double end)+ {+ ProfileStraightEdgeFilletPlanResult Fail(string code) => new(false, null, null, plan, [code]);+ var builder = new TopologyBuilder(); var geometry = new BrepGeometryStore(); var bindings = new BrepBindingModel(); var points = new Dictionary<VertexId, Point3D>();+ var vertices = new Dictionary<string, VertexId>(StringComparer.Ordinal); var edges = new Dictionary<(VertexId, VertexId), EdgeId>(); var descendants = new List<SemanticTopologyDescendant>();+ VertexId Vertex(string key, Point3D point) { if (vertices.TryGetValue(key, out var id)) return id; id = builder.AddVertex(); vertices[key] = id; points[id] = point; return id; }+ var curveId = 1; var surfaceId = 1;+ EdgeId LineEdge(VertexId a, VertexId b)+ {+ var key = a.Value < b.Value ? (a, b) : (b, a); if (edges.TryGetValue(key, out var id)) return id;+ id = builder.AddEdge(a, b); edges[key] = id; var from = points[a]; var to = points[b];+ var curve = new CurveGeometryId(curveId++); geometry.AddCurve(curve, CurveGeometry.FromLine(new Line3Curve(from, Direction3D.Create(to - from))));+ bindings.AddEdgeBinding(new EdgeGeometryBinding(id, curve, new ParameterInterval(0d, (to - from).Length), true)); return id;+ }+ EdgeId ArcEdge(VertexId a, VertexId b, Point3D center)+ {+ var key = a.Value < b.Value ? (a, b) : (b, a); if (edges.TryGetValue(key, out var id)) return id;+ id = builder.AddEdge(a, b); edges[key] = id;+ // X is from centre to the cap contact. With tangent x cap-normal, +pi/2 reaches the side contact.+ var capNormal = plan.Target.Side == ProfileBoundaryChamferSide.Top ? plan.ExtrusionAxis : Direction3D.Create(-plan.ExtrusionAxis.ToVector());+ var curve = new CurveGeometryId(curveId++); geometry.AddCurve(curve, CurveGeometry.FromCircle(new Circle3Curve(center, plan.Tangent, plan.Radius, capNormal)));+ var capPoint = center + capNormal.ToVector() * plan.Radius;+ var capIsStart = (points[a] - capPoint).Length <= Tol;+ var top = plan.Target.Side == ProfileBoundaryChamferSide.Top;+ var trim = top ? new ParameterInterval(0d, Math.PI / 2d) : new ParameterInterval(-Math.PI / 2d, 0d);+ // The binding trim is monotone; coedge orientation carries the opposite endpoint order.+ bindings.AddEdgeBinding(new EdgeGeometryBinding(id, curve, trim, top ? capIsStart : !capIsStart)); return id;+ }+ FaceId Face(string stable, IReadOnlyList<(VertexId Vertex, bool Arc, Point3D? Center)> boundary, SurfaceGeometry surface, SemanticTopologyRole role, string source, string? parent = null)+ {+ var loopId = builder.AllocateLoopId(); var coedges = Enumerable.Range(0, boundary.Count).Select(_ => new CoedgeId(builder.Model.Coedges.Count() + 1 + _)).ToArray();+ for (var i = 0; i < boundary.Count; i++)+ {+ var current = boundary[i]; var next = boundary[(i + 1) % boundary.Count];+ var edge = current.Arc ? ArcEdge(current.Vertex, next.Vertex, current.Center!.Value) : LineEdge(current.Vertex, next.Vertex);+ var modelEdge = builder.Model.Edges.Single(x => x.Id == edge);+ builder.AddCoedge(new Coedge(coedges[i], edge, loopId, coedges[(i + 1) % boundary.Count], coedges[(i + boundary.Count - 1) % boundary.Count], modelEdge.StartVertexId != current.Vertex));+ }+ builder.AddLoop(new Loop(loopId, coedges)); var face = builder.AddFace([loopId]); var sid = new SurfaceGeometryId(surfaceId++); geometry.AddSurface(sid, surface); bindings.AddFaceBinding(new FaceGeometryBinding(face, sid, true));+ descendants.Add(new(stable, "Face", role, source, Face: face, ParentStableId: parent)); return face;+ }+ static (VertexId Vertex, bool Arc, Point3D? Center) L(VertexId v) => (v, false, null);+ static (VertexId Vertex, bool Arc, Point3D? Center) A(VertexId v, Point3D c) => (v, true, c);++ var frame = profile.EffectiveConstructionPlane; var n = loop.Segments.Count; var lower = new VertexId[n]; var upper = new VertexId[n];+ for (var i = 0; i < n; i++)+ {+ var line = (LineArcLineSegment2D)loop.Segments[i].Geometry;+ lower[i] = Vertex($"lower:{i}", frame.ToWorld(line.Start, start)); upper[i] = Vertex($"upper:{i}", frame.ToWorld(line.Start, end));+ }+ var sharpStart = Vertex("sharp-start", plan.SpanStart); var sharpEnd = Vertex("sharp-end", plan.SpanEnd);+ var capStart = Vertex("cap-start", plan.CapContactStart); var capEnd = Vertex("cap-end", plan.CapContactEnd);+ var sideStart = Vertex("side-start", plan.SideContactStart); var sideEnd = Vertex("side-end", plan.SideContactEnd);+ var isTop = plan.Target.Side == ProfileBoundaryChamferSide.Top;+ var sourceStart = isTop ? upper[selected] : lower[selected]; var sourceEnd = isTop ? upper[(selected + 1) % n] : lower[(selected + 1) % n];+ var capPlane = SurfaceGeometry.FromPlane(new PlaneSurface(isTop ? plan.SourceStart : frame.ToWorld((0d, 0d), start), isTop ? plan.ExtrusionAxis : Direction3D.Create(-plan.ExtrusionAxis.ToVector()), plan.Tangent));+ var otherCapPlane = SurfaceGeometry.FromPlane(new PlaneSurface(isTop ? frame.ToWorld((0d, 0d), start) : frame.ToWorld((0d, 0d), end), isTop ? Direction3D.Create(-plan.ExtrusionAxis.ToVector()) : plan.ExtrusionAxis, plan.Tangent));+ var capBoundary = new List<(VertexId Vertex, bool Arc, Point3D? Center)>();+ for (var i = 0; i < n; i++)+ {+ capBoundary.Add(L(isTop ? upper[i] : lower[i]));+ if (i == selected) capBoundary.AddRange([L(sharpStart), L(capStart), L(capEnd), L(sharpEnd)]);+ }+ Face(isTop ? $"{plan.Target.StableId}:top-cap" : $"{plan.Target.StableId}:bottom-cap", (isTop ? capBoundary : capBoundary.AsEnumerable().Reverse()).ToArray(), capPlane, isTop ? SemanticTopologyRole.TopFaceBoundaryLoop : SemanticTopologyRole.BottomFaceBoundaryLoop, $"profile:{profile.Name}.{loop.Name}", plan.Target.StableId);+ Face(isTop ? $"{plan.Target.StableId}:bottom-cap" : $"{plan.Target.StableId}:top-cap", (isTop ? lower.Reverse() : upper).Select(L).ToArray(), otherCapPlane, isTop ? SemanticTopologyRole.BottomFaceBoundaryLoop : SemanticTopologyRole.TopFaceBoundaryLoop, $"profile:{profile.Name}.{loop.Name}", plan.Target.StableId);++ for (var i = 0; i < n; i++)+ {+ var next = (i + 1) % n; var line = (LineArcLineSegment2D)loop.Segments[i].Geometry;+ var localDx = line.End.X - line.Start.X; var localDy = line.End.Y - line.Start.Y; var localLength = Math.Sqrt(localDx * localDx + localDy * localDy);+ var outNormal = Direction3D.Create(frame.ToWorldDirection(new Vector3D(localDy / localLength, -localDx / localLength, 0d)));+ var localTangent = Direction3D.Create(frame.ToWorldDirection(new Vector3D(localDx / localLength, localDy / localLength, 0d)));+ var surface = SurfaceGeometry.FromPlane(new PlaneSurface(frame.ToWorld(line.Start, start), outNormal, localTangent));+ if (i != selected)+ Face($"profile:{profile.Name}.{loop.Name}.{loop.Segments[i].Name}:side", [L(lower[i]), L(lower[next]), L(upper[next]), L(upper[i])], surface, SemanticTopologyRole.ExtrusionSideFace, $"profile:{profile.Name}.{loop.Name}.{loop.Segments[i].Name}");+ else+ {+ var a = isTop ? new[] { L(lower[i]), L(lower[next]), L(upper[next]), L(sharpEnd), L(sideEnd), L(sideStart), L(sharpStart), L(upper[i]) }+ : new[] { L(lower[i]), L(sharpStart), L(sideStart), L(sideEnd), L(sharpEnd), L(lower[next]), L(upper[next]), L(upper[i]) };+ Face($"profile:{profile.Name}.{loop.Name}.{loop.Segments[i].Name}:trimmed-side", a, surface, SemanticTopologyRole.ExtrusionSideFace, $"profile:{profile.Name}.{loop.Name}.{loop.Segments[i].Name}", plan.Target.StableId);+ }+ }+ var cylinder = SurfaceGeometry.FromCylinder(new CylinderSurface(plan.CylinderCenterlineStart, plan.Tangent, plan.Radius, isTop ? plan.ExtrusionAxis : Direction3D.Create(-plan.ExtrusionAxis.ToVector())));+ Face($"{plan.Target.StableId}:FilletSurface", [L(capStart), A(capEnd, plan.CylinderCenterlineEnd), L(sideEnd), A(sideStart, plan.CylinderCenterlineStart)], cylinder, SemanticTopologyRole.FilletSurface, plan.Target.StableId, plan.Target.StableId);+ var startTerm = SurfaceGeometry.FromPlane(new PlaneSurface(plan.SpanStart, Direction3D.Create(-plan.Tangent.ToVector()), isTop ? plan.ExtrusionAxis : Direction3D.Create(-plan.ExtrusionAxis.ToVector())));+ var endTerm = SurfaceGeometry.FromPlane(new PlaneSurface(plan.SpanEnd, plan.Tangent, isTop ? plan.ExtrusionAxis : Direction3D.Create(-plan.ExtrusionAxis.ToVector())));+ Face($"{plan.Target.StableId}:StartTerminationFace", [L(sharpStart), A(capStart, plan.CylinderCenterlineStart), L(sideStart)], startTerm, SemanticTopologyRole.StartTerminationFace, plan.Target.StableId, plan.Target.StableId);+ Face($"{plan.Target.StableId}:EndTerminationFace", [L(sharpEnd), A(sideEnd, plan.CylinderCenterlineEnd), L(capEnd)], endTerm, SemanticTopologyRole.EndTerminationFace, plan.Target.StableId, plan.Target.StableId);++ var shell = builder.AddShell(builder.Model.Faces.Select(x => x.Id).ToArray()); builder.AddBody([shell]);+ var body = new BrepBody(builder.Model, geometry, bindings, points);+ var validation = BrepBindingValidator.Validate(body, requireAllEdgeAndFaceBindings: true);+ if (!validation.IsSuccess) return Fail("ProfileBoundaryFilletTopologyPlanInvalid");+ AddEdgeDescendant("CapContactEdge", LineEdge(capStart, capEnd), SemanticTopologyRole.CapContactEdge);+ AddEdgeDescendant("SideContactEdge", LineEdge(sideStart, sideEnd), SemanticTopologyRole.SideContactEdge);+ AddEdgeDescendant("StartEndpointArc", ArcEdge(capStart, sideStart, plan.CylinderCenterlineStart), SemanticTopologyRole.StartEndpointArc);+ AddEdgeDescendant("EndEndpointArc", ArcEdge(capEnd, sideEnd, plan.CylinderCenterlineEnd), SemanticTopologyRole.EndEndpointArc);+ AddEdgeDescendant("RetainedStartSharpEdge", LineEdge(sourceStart, sharpStart), SemanticTopologyRole.RetainedStartSharpEdge);+ AddEdgeDescendant("RetainedEndSharpEdge", LineEdge(sharpEnd, sourceEnd), SemanticTopologyRole.RetainedEndSharpEdge);+ var correspondence = new SemanticTopologyCorrespondence(plan.Target.HostBodyId, descendants, ["ResolvedProfile2D", "ProfileStraightEdgeFilletPlan", "FilletSpanInset", "AuthoritativeBRepPlan"]);+ return new(true, body, correspondence, plan, ["ProfileStraightEdgeFilletPlan", "ProfileBoundaryFilletExactQuarterCylinder", "ProfileBoundaryFilletEndpointTerminationFaces"]);++ void AddEdgeDescendant(string name, EdgeId edge, SemanticTopologyRole role) => descendants.Add(new($"{plan.Target.StableId}:{name}", "Edge", role, plan.Target.StableId, Edge: edge, ParentStableId: plan.Target.StableId));+ }+}++/// <summary>+/// Conservative source-space corridor check used before a composed host can ever+/// attempt a future M2 materialization. M1 still rejects composed hosts after a+/// disjoint proof; a collision receives the more useful feature-specific code.+/// </summary>+public sealed record ProfileStraightEdgeFilletCorridor(+ string EdgeFinishId, string ProfileId, string LoopId, string SegmentId,+ double Radius, double EndClearance, double From, double To,+ (double X, double Y) SpanStart, (double X, double Y) SpanEnd);+public sealed record ProfileStraightEdgeFilletAdmission(+ bool Disjoint, ProfileStraightEdgeFilletCorridor? Corridor, IReadOnlyList<string> Diagnostics);++public static class ProfileStraightEdgeFilletAdmissionChecker+{+ private const double Tol = 1e-8;++ public static ProfileStraightEdgeFilletAdmission Check(PrismaticSectionStackConstruction stack, ResolvedProfile2D profile, ProfileBoundaryChamferTarget target, double radius, double clearance)+ {+ var loop = profile.Loops.SingleOrDefault(x => x.Name == target.LoopId);+ if (loop is null || target.SegmentIds.Count != 1 || loop.Segments.SingleOrDefault(x => x.Name == target.SegmentIds[0])?.Geometry is not LineArcLineSegment2D line)+ return new(false, null, ["ProfileBoundaryFilletEndpointTerminationUnsupported"]);+ var length = Math.Sqrt(Math.Pow(line.End.X - line.Start.X, 2d) + Math.Pow(line.End.Y - line.Start.Y, 2d));+ if (length <= 2d * clearance + Tol) return new(false, null, ["ProfileBoundaryFilletSegmentTooShort"]);+ var dx = (line.End.X - line.Start.X) / length; var dy = (line.End.Y - line.Start.Y) / length;+ var station = target.Side == ProfileBoundaryChamferSide.Top ? stack.Feature.CriticalLevels.Max() : stack.Feature.CriticalLevels.Min();+ var from = target.Side == ProfileBoundaryChamferSide.Top ? station - radius : station;+ var to = target.Side == ProfileBoundaryChamferSide.Top ? station : station + radius;+ var corridor = new ProfileStraightEdgeFilletCorridor(target.StableId, profile.Name, loop.Name, target.SegmentIds[0], radius, clearance, from, to,+ (line.Start.X + dx * clearance, line.Start.Y + dy * clearance), (line.End.X - dx * clearance, line.End.Y - dy * clearance));+ var diagnostics = new List<string>();+ foreach (var hole in stack.Feature.ShaftHoles ?? []) AddIfCollision(hole.StableId, "Shaft", hole.CenterX, hole.CenterY, hole.Diameter / 2d, hole.From, hole.To, "ProfileBoundaryFilletIntersectsShaft");+ foreach (var hole in stack.Feature.CounterboreHoles ?? [])+ {+ AddIfCollision(hole.StableId, "Counterbore", hole.CenterX, hole.CenterY, hole.CounterboreDiameter / 2d, Math.Max(hole.From, hole.To - hole.CounterboreDepth), hole.To, "ProfileBoundaryFilletIntersectsCounterbore");+ AddIfCollision(hole.StableId, "CounterboreShaft", hole.CenterX, hole.CenterY, hole.Diameter / 2d, hole.From, Math.Max(hole.From, hole.To - hole.CounterboreDepth), "ProfileBoundaryFilletIntersectsCounterbore");+ }+ return new(diagnostics.Count == 0, corridor, diagnostics.Distinct(StringComparer.Ordinal).ToArray());++ void AddIfCollision(string feature, string kind, double x, double y, double cavityRadius, double cavityFrom, double cavityTo, string code)+ {+ // Touching is rejected too. The radial test is the Minkowski sum of the+ // finite span and the radius-r fillet strip; it is conservative by design.+ var overlapsAxially = cavityFrom <= corridor.To + Tol && cavityTo >= corridor.From - Tol;+ if (!overlapsAxially || PointSegmentDistance((x, y), corridor.SpanStart, corridor.SpanEnd) > cavityRadius + radius + Tol) return;+ diagnostics.Add($"{code}:edgeFinish={corridor.EdgeFinishId}:cavity={feature}:kind={kind}:profile={corridor.ProfileId}.{corridor.LoopId}.{corridor.SegmentId}:span=({corridor.SpanStart.X:R},{corridor.SpanStart.Y:R})->({corridor.SpanEnd.X:R},{corridor.SpanEnd.Y:R}):radius={radius:R}");+ }+ }++ private static double PointSegmentDistance((double X, double Y) p, (double X, double Y) a, (double X, double Y) b)+ {+ var dx = b.X - a.X; var dy = b.Y - a.Y; var lengthSquared = dx * dx + dy * dy;+ var t = Math.Clamp(((p.X - a.X) * dx + (p.Y - a.Y) * dy) / lengthSquared, 0d, 1d);+ var ox = p.X - (a.X + t * dx); var oy = p.Y - (a.Y + t * dy); return Math.Sqrt(ox * ox + oy * oy);+ }+}diff --git a/Aetheris.Kernel.Firmament/Materializer/SemanticTopologySelections.cs b/Aetheris.Kernel.Firmament/Materializer/SemanticTopologySelections.csindex c2ecbf4a..8d4978ba 100644--- a/Aetheris.Kernel.Firmament/Materializer/SemanticTopologySelections.cs+++ b/Aetheris.Kernel.Firmament/Materializer/SemanticTopologySelections.cs@@ -5,7 +5,7 @@ using System.Text.RegularExpressions;namespace Aetheris.Kernel.Firmament.Materializer;/// <summary>Stable roles assigned while an authoritative plan is materialized. These are not geometric queries.</summary>-public enum SemanticTopologyRole { Unknown, ProfileVertex, VerticalExtrusionEdge, LocalStartBoundary, LocalEndBoundary, LocalStartCapLoop, LocalEndCapLoop, TopBoundary, BottomBoundary, ExtrusionSideFace, TopFaceBoundaryLoop, BottomFaceBoundaryLoop, HoleEntryLoop, HoleExitLoop, HoleWallFace, HoleShaftToDrillPointLoop, HoleShaftToDrillPointEdge, HoleDrillPointFace, HoleTipVertex, HoleCounterboreMouthLoop, HoleCounterboreWallFace, HoleCounterboreShoulderLoop, HoleCounterboreShaftWallFace, SlotEntryLoop, SlotExitLoop, SlotWallFace, SlotStraightWallFace, SlotEndWallFace, ComposeTransition, EdgeFinishReplacementFace }+public enum SemanticTopologyRole { Unknown, ProfileVertex, VerticalExtrusionEdge, LocalStartBoundary, LocalEndBoundary, LocalStartCapLoop, LocalEndCapLoop, TopBoundary, BottomBoundary, ExtrusionSideFace, TopFaceBoundaryLoop, BottomFaceBoundaryLoop, HoleEntryLoop, HoleExitLoop, HoleWallFace, HoleShaftToDrillPointLoop, HoleShaftToDrillPointEdge, HoleDrillPointFace, HoleTipVertex, HoleCounterboreMouthLoop, HoleCounterboreWallFace, HoleCounterboreShoulderLoop, HoleCounterboreShaftWallFace, SlotEntryLoop, SlotExitLoop, SlotWallFace, SlotStraightWallFace, SlotEndWallFace, ComposeTransition, EdgeFinishReplacementFace, FilletSurface, CapContactEdge, SideContactEdge, StartTerminationFace, EndTerminationFace, StartEndpointArc, EndEndpointArc, RetainedStartSharpEdge, RetainedEndSharpEdge }public enum SemanticSelectionRequirement { ExactlyOne, OneOrMore, ConnectedChain, ClosedLoop, NonEmptyFaceSet }public enum SemanticSelectionFailure { None, SemanticSourceNotFound, NoMaterializedDescendants, AmbiguousBodyContext, SelectionCardinalityMismatch, DescendantsNotConnected, DescendantsBranch, DescendantsDoNotClose, MixedBoundaryRoles, UnsupportedTopologyChange, SelectionConsumerMismatch }diff --git a/docs/firmament/profile-edgefinish-convex-concave-audit-x1.md b/docs/firmament/profile-edgefinish-convex-concave-audit-x1.mdindex facd3812..3b13bf89 100644--- a/docs/firmament/profile-edgefinish-convex-concave-audit-x1.md+++ b/docs/firmament/profile-edgefinish-convex-concave-audit-x1.md@@ -3,11 +3,10 @@## ResultProfile-boundary chamfers are explicit source-bound constructions for both-`ConvexProfileJunction` and `ReflexProfileJunction`. Profile-boundary fillets-do **not** currently exist: canonical `EdgeFinish ... Kind: Fillet Radius: ...`-is parsed, reaches the resolved-Profile finish binder, and stops at the typed-`ProfileBoundaryFilletNotMaterialized` boundary. No 2D Profile arc is counted-as a 3D fillet.+`ConvexProfileJunction` and `ReflexProfileJunction`. The isolated M1+Profile-boundary fillet now exists for one named straight outer segment on Top+or Bottom. It remains deliberately unavailable for chains, loops, and convex or+reflex junctions; no 2D Profile arc is counted as a 3D fillet.## Junction model@@ -83,22 +82,21 @@ larger entry radius is checked and reports| Frustum routes | bounded primitive rim routes | analytic primitive support | supported where admitted || Profile chamfer | source Profile outer line loop/chain, Top/Bottom | planar section transition | supported || Compose Profile chamfer | Top whole outer line loop, disjoint cavities | planar variable-outer transition | supported |-| Profile fillet segment / convex junction / reflex junction | source Profile boundary | no rolling-surface plan | unsupported: `ProfileBoundaryFilletNotMaterialized` |+| Profile fillet, one straight outer segment | authored `Profile.Outer.Segment`, Top/Bottom | quarter cylinder + planar end faces | supported (M1) |+| Profile fillet chain / loop / convex junction / reflex junction | source Profile boundary | no junction rolling-surface plan | unsupported: `ProfileBoundaryFilletNotMaterialized` |Primitive internal/reflex fillet support is not evidence of a Profile fillet:-the former is a bounded primitive/cell planner and emits cylinders. The missing-Profile primitive is the first authoritative constant-radius straight-Profile-boundary rolling-surface plan, including cap/side contact curves and-semantic descendants. Until that exists, convex/reflex junction patches,-trim/intersection topology, cavity corridors, and whole-loop fillets must not-be claimed.--Recommended bounded follow-up: **PROFILE-STRAIGHT-EDGE-FILLET-M1** — one+the former is a bounded primitive/cell planner. M1 instead has an authoritative+constant-radius straight Profile-boundary rolling-surface plan, including+cap/side contact curves and semantic descendants. Convex/reflex junction+patches, trim/intersection topology, cavity corridors, and whole-loop fillets+remain outside that plan.++Implemented bounded follow-up: **PROFILE-STRAIGHT-EDGE-FILLET-M1** — onesource-selected straight outer Profile segment on Top, with a constant-radiuscylinder, explicit endpoint termination policy, `FilletSurface`,-`TopContactEdge`, and `SideContactEdge` descendants. Only after that evidence-should a convex two-line junction be considered; reflex junctions are a later,-separate milestone.+`CapContactEdge`, and `SideContactEdge` descendants. The next bounded work can+therefore be a convex two-line junction; reflex junctions remain later work.## Authoring and performance notesdiff --git a/docs/firmament/profile-straight-edge-fillet-m1.md b/docs/firmament/profile-straight-edge-fillet-m1.mdnew file mode 100644index 00000000..81ee9457--- /dev/null+++ b/docs/firmament/profile-straight-edge-fillet-m1.md@@ -0,0 +1,57 @@+# Profile straight-edge fillet M1++M1 materializes one authored `Line2` segment on the outer loop of a prismatic+Profile extrusion. It is a source-bound operation: `Target` names+`Profile.Loop.Segment`; no B-rep edge lookup is performed.++```firmament+Modify Body {+ EdgeFinish SouthTopRound {+ Target: Bracket.Outer.South+ On: Top+ Kind: Fillet+ Radius: 2mm+ EndClearance: 3mm+ }+}+```++`On` is `Top` or `Bottom`. `EndClearance` is the distance retained at both+source-segment ends. If omitted it is exactly `Radius`; the emitted plan records+that `FilletSpanInset` policy. The span is `[EndClearance, Length-EndClearance]`+and must be non-empty.++For a directed outer-line segment `P0 -> P1`, M1 derives tangent `t` and the+inward profile normal `n` from loop winding. For Top, the cylindrical axis is+parallel to `t` and its centreline is `r*n-r*z` from the sharp edge. For Bottom+it is `r*n+r*z`. The cap contact is inset by `r*n`; the side contact is offset+by `r*z` into the body. The surface is an exact quarter cylinder; its end+boundaries are exact quarter-circle arcs in planes normal to `t`.++Each end is closed by a planar quarter-disc termination face. The source edge+therefore retains two sharp stubs, and adjacent Profile junctions remain wholly+untouched. Typed descendants include `FilletSurface`, both contact edges, both+endpoint arcs, both termination faces, and both retained sharp edges.++The implementation rejects non-positive radii/clearances, a radius at or above+host thickness, non-Line2 sources, inner loops, loop/chain targets, and spans+that cannot retain both endpoint clearances. For a Compose source, M1 first+tests an exact finite-span/axial corridor conservatively against Shaft and+Counterbore circles. Touching or overlap reports+`ProfileBoundaryFilletIntersectsShaft` or+`ProfileBoundaryFilletIntersectsCounterbore` before topology generation.+Disjoint composed hosts still report `ProfileBoundaryFilletComposeUnsupported`:+the M1 topology route is intentionally bare-Profile only.++`aetheris inspect-profile file.firmament --json` reports the selected target,+radius, clearances/span policy, cylinder axis and centreline, both contact+lines, corridor classification, typed descendants, and provenance chain.++For span `S` and radius `r`, the exact removed volume is+`S * r^2 * (1 - pi/4)`. The end termination faces merely partition the boundary+at the span ends; they add no further removed volume. The cylindrical area is+`S * pi * r / 2`.++Current limitations: no adjacent-junction continuation, convex/reflex patch,+whole-loop or chain finish, inner loop, curve source, variable radius, imported+edge, cavity interaction, or composed Profile host is supported.diff --git a/docs/firmament/v2-canonical-authoring.md b/docs/firmament/v2-canonical-authoring.mdindex 0f36a408..66073c2b 100644--- a/docs/firmament/v2-canonical-authoring.md+++ b/docs/firmament/v2-canonical-authoring.md@@ -198,10 +198,21 @@ material-side interior angle); this is not a 2D arc or a BRep-edge guess.chain and `profile-chamfer-mixed-convex-reflex-loop-top.firmament` applies thesame exact planar section transition around the whole outer loop.-`Kind: Fillet` is parsed as an EdgeFinish declaration, but no Profile-boundary-rolling-surface planner exists. A source-bound Profile fillet is deliberately-rejected as `ProfileBoundaryFilletNotMaterialized`; a Concept Path `Arc` only-changes the 2D outline and is not a substitute for that 3D fillet.+One finite source-bound Profile fillet is available on a straight outer segment:++```firmament+Modify Body { EdgeFinish SouthTopRound {+ Target: Bracket.Outer.South On: Top Kind: Fillet Radius: 2mm EndClearance: 3mm+} }+Modify Body { EdgeFinish SouthBottomRound {+ Target: Bracket.Outer.South On: Bottom Kind: Fillet Radius: 2mm EndClearance: 3mm+} }+```++It emits one exact quarter-cylinder with planar endpoint termination faces.+`EndClearance` defaults to `Radius`. Multi-segment convex/reflex junction+fillets, chains, and whole loops remain unsupported; a Concept Path `Arc` only+changes a 2D outline and is not a substitute for this 3D edge finish.## Canonical examples@@ -214,6 +225,8 @@ changes the 2D outline and is not a substitute for that 3D fillet.- `fixtures/FirmamentV2/Canonical/valid/profile-line-extrusion.firmament`- `fixtures/FirmamentV2/Canonical/valid/profile-compose-base.firmament`- `fixtures/FirmamentV2/Canonical/valid/profile-compose-l-bracket.firmament`+- `fixtures/FirmamentV2/Canonical/valid/profile-straight-edge-fillet-top.firmament`+- `fixtures/FirmamentV2/Canonical/valid/profile-straight-edge-fillet-bottom.firmament`- `fixtures/FirmamentV2/Canonical/valid/box-hole-pmi.firmament`- `fixtures/FirmamentV2/Canonical/valid/semantic-slot-capsule.firmament`- `fixtures/FirmamentV2/Canonical/valid/semantic-slot-rounded-rectangle.firmament`diff --git a/fixtures/FirmamentV2/Canonical/invalid/profile-straight-edge-fillet-shaft-collision.firmament b/fixtures/FirmamentV2/Canonical/invalid/profile-straight-edge-fillet-shaft-collision.firmamentnew file mode 100644index 00000000..6d9ad84e--- /dev/null+++ b/fixtures/FirmamentV2/Canonical/invalid/profile-straight-edge-fillet-shaft-collision.firmament@@ -0,0 +1,17 @@+Model ProfileStraightEdgeFilletShaftCollision {+ Units: mm+ Concept Struct Layout On XY {+ Rect2 Stock { Center: [0mm, 0mm]; Size: [20mm, 10mm] }+ }+ Profile Plate Using Layout { Loop Outer {+ Segment South { Trace: Stock.Bottom; From: Stock.BottomLeft; To: Stock.BottomRight }+ Segment East { Trace: Stock.Right; From: Stock.BottomRight; To: Stock.TopRight }+ Segment North { Trace: Stock.Top; From: Stock.TopRight; To: Stock.TopLeft }+ Segment West { Trace: Stock.Left; From: Stock.TopLeft; To: Stock.BottomLeft }+ } }+ Struct PlateBody { Compose Body {+ Base Stock { Profile: Plate; From: 0mm; To: 8mm; Role: Stock }+ Hole<Shaft> NearSouth { On: +Z; Center: Point2(0mm, -3mm); Diameter: 2mm; End: ThroughAll }+ } }+ Modify PlateBody { EdgeFinish SouthTopRound { Target: Plate.Outer.South On: Top Kind: Fillet Radius: 2mm EndClearance: 3mm } }+}diff --git a/fixtures/FirmamentV2/Canonical/valid/profile-straight-edge-fillet-bottom.firmament b/fixtures/FirmamentV2/Canonical/valid/profile-straight-edge-fillet-bottom.firmamentnew file mode 100644index 00000000..bc32db7d--- /dev/null+++ b/fixtures/FirmamentV2/Canonical/valid/profile-straight-edge-fillet-bottom.firmament@@ -0,0 +1,12 @@+Concept Struct RectangleLayout On XY {+ Point2 A { Position: [0mm, 0mm] } Point2 B { Position: [20mm, 0mm] }+ Point2 C { Position: [20mm, 10mm] } Point2 D { Position: [0mm, 10mm] }+ Line2 South { From: A; To: B } Line2 East { From: B; To: C }+ Line2 North { From: C; To: D } Line2 West { From: D; To: A }+}+Profile Bracket Using RectangleLayout { Loop Outer {+ Segment South { Trace: South; From: A; To: B } Segment East { Trace: East; From: B; To: C }+ Segment North { Trace: North; From: C; To: D } Segment West { Trace: West; From: D; To: A }+} }+Struct Body { Extrude Bracket { Profile: Bracket; From: 0mm; To: 8mm } }+Modify Body { EdgeFinish SouthBottomRound { Target: Bracket.Outer.South On: Bottom Kind: Fillet Radius: 2mm EndClearance: 3mm } }diff --git a/fixtures/FirmamentV2/Canonical/valid/profile-straight-edge-fillet-top.firmament b/fixtures/FirmamentV2/Canonical/valid/profile-straight-edge-fillet-top.firmamentnew file mode 100644index 00000000..2e76e01a--- /dev/null+++ b/fixtures/FirmamentV2/Canonical/valid/profile-straight-edge-fillet-top.firmament@@ -0,0 +1,12 @@+Concept Struct RectangleLayout On XY {+ Point2 A { Position: [0mm, 0mm] } Point2 B { Position: [20mm, 0mm] }+ Point2 C { Position: [20mm, 10mm] } Point2 D { Position: [0mm, 10mm] }+ Line2 South { From: A; To: B } Line2 East { From: B; To: C }+ Line2 North { From: C; To: D } Line2 West { From: D; To: A }+}+Profile Bracket Using RectangleLayout { Loop Outer {+ Segment South { Trace: South; From: A; To: B } Segment East { Trace: East; From: B; To: C }+ Segment North { Trace: North; From: C; To: D } Segment West { Trace: West; From: D; To: A }+} }+Struct Body { Extrude Bracket { Profile: Bracket; From: 0mm; To: 8mm } }+Modify Body { EdgeFinish SouthTopRound { Target: Bracket.Outer.South On: Top Kind: Fillet Radius: 2mm EndClearance: 3mm } }