Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add rib planning and support unfinished through-hole stock
Yuechen Licb22a47ad4eb
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 7bc152ce..97e8ce5a 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -611,6 +611,7 @@ public static class CliRunnerengineeringFeatures = build.Value.Export.EngineeringFeatures,materializedFeatures = build.Value.Export.MaterializedFeatures,edgeFinishPlanning = build.Value.Export.EdgeFinishPlanning,+ ribPlanning = build.Value.Export.RibPlanning,patterns = build.Value.Export.Patterns,perforation = build.Value.Export.Perforation,structural = build.Value.Export.Structural,diff --git a/Aetheris.Kernel.Core/Brep/Features/BrepPlanarAdditiveAttachment.cs b/Aetheris.Kernel.Core/Brep/Features/BrepPlanarAdditiveAttachment.csnew file mode 100644index 00000000..cd12e955--- /dev/null+++ b/Aetheris.Kernel.Core/Brep/Features/BrepPlanarAdditiveAttachment.cs@@ -0,0 +1,188 @@+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Curves;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Results;+using Aetheris.Kernel.Core.Topology;++namespace Aetheris.Kernel.Core.Brep.Features;++public sealed record PlanarAttachmentResult(BrepBody Body, IReadOnlyDictionary<FaceId, FaceId> AddedFaceMap);++/// <summary>Joins a construction-owned, Z-monotone additive section boundary to+/// a proved planar support. Auxiliary section-stack base material at/below the+/// contact plane is discarded. Only actual upper boundary and its exact contact+/// cycles survive. This is a shared planar interface, not a general solid Boolean.</summary>+public static class BrepPlanarAdditiveAttachment+{+ public static KernelResult<PlanarAttachmentResult> Attach(BrepBody host, BrepBody addition, double contactZ, FaceId supportFace)+ {+ const double tol = 1e-7;+ KernelResult<PlanarAttachmentResult> Fail(string message) => KernelResult<PlanarAttachmentResult>.Failure([+ new(Diagnostics.KernelDiagnosticCode.ValidationFailed, Diagnostics.KernelDiagnosticSeverity.Error,+ "rib-attachment-invalid: " + message, "Brep.PlanarAttachment")]);+ var hostPoints = Points(host); var addedPoints = Points(addition);+ if (!host.Topology.TryGetFace(supportFace, out var support) || support is null+ || host.Geometry.GetSurface(host.Bindings.GetFaceBinding(supportFace).SurfaceGeometryId).Plane is not { } plane+ || plane.Normal.Z < .999 || double.Abs(plane.Origin.Z - contactZ) > tol)+ return Fail("The selected support must be an outward +Z plane at the contact station.");+ var kept = addition.Topology.Faces.Where(f => f.LoopIds.SelectMany(l => addition.Topology.GetLoop(l).CoedgeIds)+ .SelectMany(c => { var e = addition.Topology.GetEdge(addition.Topology.GetCoedge(c).EdgeId); return new[] { e.StartVertexId, e.EndVertexId }; })+ .Any(v => addedPoints[v].Z > contactZ + tol)).ToArray();+ if (kept.Length == 0) return Fail("No positive-height additive boundary was constructed.");+ var coedges = kept.SelectMany(f => f.LoopIds).SelectMany(l => addition.Topology.GetLoop(l).CoedgeIds)+ .Select(addition.Topology.GetCoedge).ToArray();+ var uses = coedges.GroupBy(c => c.EdgeId).ToDictionary(g => g.Key, g => g.ToArray());+ if (uses.Any(g => g.Value.Length > 2)) return Fail("Additive boundary is non-manifold.");+ var contacts = uses.Where(g => g.Value.Length == 1).Select(g => g.Value[0] with { IsReversed = !g.Value[0].IsReversed }).ToArray();+ if (contacts.Length == 0) return Fail("No finite planar contact boundary was proved.");+ foreach (var c in contacts)+ {+ var e = addition.Topology.GetEdge(c.EdgeId);+ if (double.Abs(addedPoints[e.StartVertexId].Z - contactZ) > tol || double.Abs(addedPoints[e.EndVertexId].Z - contactZ) > tol)+ return Fail("An unclosed additive edge lies away from the attachment plane.");+ }+ var outgoing = contacts.GroupBy(c => DirectedEdgeUse.Resolve(addition.Topology.GetEdge(c.EdgeId), c).StartVertexId).ToArray();+ if (outgoing.Any(g => g.Count() != 1)) return Fail("Contact cycles branch or touch at a point; positive-area junctions are required.");+ var byStart = outgoing.ToDictionary(g => g.Key, g => g.Single()); var consumed = new HashSet<EdgeId>();+ var cycles = new List<Coedge[]>();+ foreach (var first in contacts.OrderBy(c => c.EdgeId.Value))+ {+ if (consumed.Contains(first.EdgeId)) continue;+ var cycle = new List<Coedge>(); var next = first;+ while (consumed.Add(next.EdgeId))+ {+ cycle.Add(next);+ if (!byStart.TryGetValue(DirectedEdgeUse.Resolve(addition.Topology.GetEdge(next.EdgeId), next).EndVertexId, out next!))+ return Fail("Contact boundary is open.");+ }+ if (next.EdgeId != first.EdgeId) return Fail("Contact boundary merges ambiguously.");+ cycles.Add(cycle.ToArray());+ }+ var model = host.Topology.Clone(); var geometry = host.Geometry.Clone();+ // Rebuild only the host's face container later; immutable source entities remain unchanged.+ var bindings = new BrepBindingModel();+ foreach (var e in host.Bindings.EdgeBindings) bindings.AddEdgeBinding(e);+ foreach (var f in host.Bindings.FaceBindings) bindings.AddFaceBinding(f);+ foreach (var r in host.Bindings.FaceBoundaryRoleBindings) bindings.AddFaceBoundaryRoleBinding(r);+ // Adding an inner boundary makes role evidence explicit for this face.+ // Complete the original authored-order evidence before extending it.+ for (var i = 0; i < support.LoopIds.Count; i++)+ if (!bindings.TryGetFaceBoundaryRoleBinding(support.LoopIds[i], out _))+ bindings.AddFaceBoundaryRoleBinding(new(supportFace, support.LoopIds[i],+ i == 0 ? FaceBoundaryRole.Outer : FaceBoundaryRole.Inner));+ var vOffset = host.Topology.Vertices.Max(v => v.Id.Value); var eOffset = host.Topology.Edges.Max(e => e.Id.Value);+ var cOffset = host.Topology.Coedges.Max(c => c.Id.Value); var lOffset = host.Topology.Loops.Max(l => l.Id.Value);+ var fOffset = host.Topology.Faces.Max(f => f.Id.Value);+ var curveOffset = host.Geometry.Curves.Max(c => c.Key.Value); var surfaceOffset = host.Geometry.Surfaces.Max(s => s.Key.Value);+ VertexId V(VertexId id) => new(id.Value + vOffset); EdgeId E(EdgeId id) => new(id.Value + eOffset);+ CoedgeId C(CoedgeId id) => new(id.Value + cOffset); LoopId L(LoopId id) => new(id.Value + lOffset); FaceId F(FaceId id) => new(id.Value + fOffset);+ var usedVertices = uses.Keys.Select(addition.Topology.GetEdge).SelectMany(e => new[] { e.StartVertexId, e.EndVertexId }).Distinct().ToArray();+ foreach (var v in usedVertices) { model.AddVertex(new(V(v))); hostPoints[V(v)] = addedPoints[v]; }+ foreach (var id in uses.Keys.OrderBy(e => e.Value))+ {+ var e = addition.Topology.GetEdge(id); model.AddEdge(new(E(id), V(e.StartVertexId), V(e.EndVertexId)));+ var b = addition.Bindings.GetEdgeBinding(id); var cid = new CurveGeometryId(b.CurveGeometryId.Value + curveOffset);+ if (!geometry.TryGetCurve(cid, out _)) geometry.AddCurve(cid, addition.Geometry.GetCurve(b.CurveGeometryId));+ bindings.AddEdgeBinding(b with { EdgeId = E(id), CurveGeometryId = cid });+ }+ foreach (var c in coedges) model.AddCoedge(new(C(c.Id), E(c.EdgeId), L(c.LoopId), C(c.NextCoedgeId), C(c.PrevCoedgeId), c.IsReversed));+ foreach (var id in kept.SelectMany(f => f.LoopIds).Distinct())+ model.AddLoop(new(L(id), addition.Topology.GetLoop(id).CoedgeIds.Select(C).ToArray()));+ var addedFaces = new List<Face>(); var faceMap = new Dictionary<FaceId, FaceId>();+ foreach (var f in kept)+ {+ var mapped = new Face(F(f.Id), f.LoopIds.Select(L).ToArray()); addedFaces.Add(mapped); faceMap[f.Id] = mapped.Id;+ var b = addition.Bindings.GetFaceBinding(f.Id); var sid = new SurfaceGeometryId(b.SurfaceGeometryId.Value + surfaceOffset);+ if (!geometry.TryGetSurface(sid, out _)) geometry.AddSurface(sid, addition.Geometry.GetSurface(b.SurfaceGeometryId));+ bindings.AddFaceBinding(new(mapped.Id, sid, b.Orientation));+ for (var i = 0; i < f.LoopIds.Count; i++)+ {+ var role = addition.Bindings.TryGetFaceBoundaryRoleBinding(f.LoopIds[i], out var r) ? r.Role : i == 0 ? FaceBoundaryRole.Outer : FaceBoundaryRole.Inner;+ bindings.AddFaceBoundaryRoleBinding(new(mapped.Id, L(f.LoopIds[i]), role));+ }+ }+ var nextLoop = System.Math.Max(lOffset, model.Loops.Max(l => l.Id.Value));+ var nextCoedge = System.Math.Max(cOffset, model.Coedges.Max(c => c.Id.Value));+ var nextFace = System.Math.Max(fOffset, addedFaces.Select(f => f.Id.Value).DefaultIfEmpty(fOffset).Max());+ var supportLoops = support.LoopIds.ToList();+ foreach (var cycle in cycles)+ {+ var area = cycle.Sum(c => Area(addition, c, addedPoints));+ if (double.Abs(area) < 1e-9) return Fail("Contact has zero signed area.");+ // Section construction stores hole source loops CCW and material+ // orientation separately. Recover the interface's explicit cap role;+ // a cycle's traversal alone is not evidence of material ownership.+ var boundaryEdges = cycle.Select(c => c.EdgeId).ToHashSet();+ var capRoles = addition.Topology.Faces.Except(kept).SelectMany(f =>+ {+ var binding = addition.Bindings.GetFaceBinding(f.Id);+ var cap = addition.Geometry.GetSurface(binding.SurfaceGeometryId).Plane;+ if (cap is not { } p || double.Abs(p.Origin.Z - contactZ) > tol || double.Abs(p.Normal.Z) < .999)+ return Array.Empty<FaceBoundaryRole>();+ return f.LoopIds.Select((id, i) => (id, i)).Where(l => addition.Topology.GetLoop(l.id).CoedgeIds+ .Select(id => addition.Topology.GetCoedge(id).EdgeId).ToHashSet().SetEquals(boundaryEdges))+ .Select(l =>+ {+ var role = addition.Bindings.TryGetFaceBoundaryRoleBinding(l.id, out var r) ? r.Role+ : l.i == 0 ? FaceBoundaryRole.Outer : FaceBoundaryRole.Inner;+ return p.Normal.Z * (binding.Orientation.IsAlignedWithSurface ? 1 : -1) > 0 ? role+ : role == FaceBoundaryRole.Outer ? FaceBoundaryRole.Inner : FaceBoundaryRole.Outer;+ }).ToArray();+ }).Distinct().ToArray();+ if (capRoles.Length != 1) return Fail("No unique construction-owned cap role was proved for a contact cycle.");+ var lid = new LoopId(++nextLoop); var ids = cycle.Select(_ => new CoedgeId(++nextCoedge)).ToArray();+ for (var i = 0; i < ids.Length; i++) model.AddCoedge(new(ids[i], E(cycle[i].EdgeId), lid, ids[(i + 1) % ids.Length], ids[(i + ids.Length - 1) % ids.Length], cycle[i].IsReversed));+ model.AddLoop(new(lid, ids));+ if (capRoles[0] == FaceBoundaryRole.Inner)+ { supportLoops.Add(lid); bindings.AddFaceBoundaryRoleBinding(new(supportFace, lid, FaceBoundaryRole.Inner)); }+ else+ {+ var island = new Face(new(++nextFace), [lid]); addedFaces.Add(island);+ bindings.AddFaceBinding(new(island.Id, host.Bindings.GetFaceBinding(supportFace).SurfaceGeometryId));+ bindings.AddFaceBoundaryRoleBinding(new(island.Id, lid, FaceBoundaryRole.Outer));+ }+ }+ var completed = new TopologyModel();+ foreach (var v in model.Vertices) completed.AddVertex(v);+ foreach (var e in model.Edges) completed.AddEdge(e);+ foreach (var c in model.Coedges) completed.AddCoedge(c);+ foreach (var l in model.Loops) completed.AddLoop(l);+ foreach (var f in model.Faces) completed.AddFace(f.Id == supportFace ? f with { LoopIds = supportLoops } : f);+ foreach (var f in addedFaces) completed.AddFace(f);+ foreach (var s in model.Shells) completed.AddShell(s with { FaceIds = s.FaceIds.Concat(addedFaces.Select(f => f.Id)).ToArray() });+ foreach (var b in model.Bodies) completed.AddBody(b);+ var body = new BrepBody(completed, geometry, bindings, hostPoints);+ var validation = BrepBindingValidator.Validate(body, true);+ if (!validation.IsSuccess) return KernelResult<PlanarAttachmentResult>.Failure(validation.Diagnostics);+ if (completed.Edges.Any(e => completed.Coedges.Count(c => c.EdgeId == e.Id) != 2)) return Fail("Final boundary has an open or overused edge.");+ body.PcurveRecoveryReport = BrepPcurveRecovery.Populate(completed, geometry, bindings);+ var preflight = BrepExportPreflight.Validate(body);+ if (!preflight.IsValid) return Fail(string.Join("; ", preflight.Diagnostics.Where(d => d.Severity == BrepExportPreflightSeverity.Error).Select(d => d.Message)));+ return KernelResult<PlanarAttachmentResult>.Success(new(body, faceMap));+ }++ private static Dictionary<VertexId, Point3D> Points(BrepBody body)+ {+ var result = body.Topology.Vertices.Where(v => body.TryGetVertexPoint(v.Id, out _)).ToDictionary(v => v.Id, v => { body.TryGetVertexPoint(v.Id, out var p); return p; });+ foreach (var e in body.Topology.Edges)+ {+ var b = body.Bindings.GetEdgeBinding(e.Id); var c = body.Geometry.GetCurve(b.CurveGeometryId); var t = b.TrimInterval!.Value;+ result.TryAdd(e.StartVertexId, BrepPcurveValidator.Evaluate(c, b.OrientedEdgeSense ? t.Start : t.End)!.Value);+ result.TryAdd(e.EndVertexId, BrepPcurveValidator.Evaluate(c, b.OrientedEdgeSense ? t.End : t.Start)!.Value);+ }+ return result;+ }+ private static double Area(BrepBody body, Coedge use, IReadOnlyDictionary<VertexId, Point3D> points)+ {+ var edge = body.Topology.GetEdge(use.EdgeId); var direction = DirectedEdgeUse.Resolve(edge, use);+ var a = points[direction.StartVertexId]; var b = points[direction.EndVertexId];+ var binding = body.Bindings.GetEdgeBinding(edge.Id); var curve = body.Geometry.GetCurve(binding.CurveGeometryId);+ if (curve.Circle3 is not { } circle) return (a.X * b.Y - b.X * a.Y) / 2;+ var interval = binding.TrimInterval!.Value; var forward = binding.OrientedEdgeSense != use.IsReversed;+ var from = forward ? interval.Start : interval.End; var to = forward ? interval.End : interval.Start;+ var orientation = circle.XAxis.X * circle.YAxis.Y - circle.XAxis.Y * circle.YAxis.X;+ return (circle.Center.X * (b.Y - a.Y) - circle.Center.Y * (b.X - a.X)+ + circle.Radius * circle.Radius * orientation * (to - from)) / 2;+ }+}diff --git a/Aetheris.Kernel.Core/Brep/Features/BrepPlanarPathFeature.cs b/Aetheris.Kernel.Core/Brep/Features/BrepPlanarPathFeature.csindex 32ce6863..d0ee23f6 100644--- a/Aetheris.Kernel.Core/Brep/Features/BrepPlanarPathFeature.cs+++ b/Aetheris.Kernel.Core/Brep/Features/BrepPlanarPathFeature.cs@@ -16,43 +16,76 @@ public sealed record PlanarPathFeature(string Name, bool Add, PathSectionKind Sedouble Width, double Extent, double DraftDegrees = 0, bool RoundEnds = false);public sealed record PathFeatureBody(BrepBody Body, IReadOnlyDictionary<string, IReadOnlyList<FaceId>> Faces,double MaterialVolumeDelta);+public sealed record PlanarBandSpan(ProfilePoint2D Start, ProfilePoint2D End, ProfilePoint2D Center,+ double Radius, double StartAngle, double Sweep);/// <summary>Analytic local bands on a Box top. Footprints are integrated into the/// support face, not emitted as intersecting tool solids. Disjoint bounds are a/// conservative admission proof; crossing or adjoining features require a junction plan.</summary>public static class BrepPlanarPathFeature{+ /// <summary>The same exact section used by isolated materialization, exposed+ /// to the section-arrangement owner without duplicating offset semantics.</summary>+ public static IReadOnlyList<IReadOnlyList<PlanarBandSpan>> Footprint(PlanarPathFeature feature, double height = 0)+ {+ var half = feature.Width / 2 - height * double.Tan(feature.DraftDegrees * double.Pi / 180);+ if (!double.IsFinite(half) || half <= 0) throw new ArgumentOutOfRangeException(nameof(height));+ return (Outline(feature.Guide, half, feature.RoundEnds) ?? throw new ArgumentException("Invalid guide."))+ .Select(loop => (IReadOnlyList<PlanarBandSpan>)loop.Select(e =>+ new PlanarBandSpan(e.Start, e.End, new(e.Cx,e.Cy), e.Radius, e.Angle, e.Sweep)).ToArray()).ToArray();+ }++ public static KernelResult<bool> ValidateFeature(PlanarPathFeature f, double z)+ {+ if (!double.IsFinite(f.Width + f.Extent + f.DraftDegrees) || f.Width <= 0 || f.Extent <= 0 || f.DraftDegrees < 0 || f.DraftDegrees >= 89)+ return Invalid("dimensions", $"{f.Name}: width/height/depth must be positive; draft must be in [0deg,89deg).");+ if (!Enum.IsDefined(f.Guide.Kind) || !Enum.IsDefined(f.Section)+ || !double.IsFinite(f.Guide.Start.X + f.Guide.Start.Y + f.Guide.End.X + f.Guide.End.Y + f.Guide.Center.X + f.Guide.Center.Y))+ return Invalid("guide", $"{f.Name}: guide kind and coordinates must be finite and admitted.");+ if (f.Section == PathSectionKind.Semicircular && (f.Add || double.Abs(f.Extent - f.Width / 2) > 1e-9 || f.DraftDegrees != 0))+ return Invalid("section", $"{f.Name}: semicircular removal requires depth = radius = width/2 and no draft.");+ if (!f.Add && (f.Extent >= z - 1e-8 || f.DraftDegrees != 0)) return Invalid("floor", $"{f.Name}: groove must leave a positive floor; groove draft is unsupported.");+ if (f.Guide.Kind != PlanarGuideKind.Line && (f.Guide.Radius <= f.Width / 2 + 1e-8+ || !double.IsFinite(f.Guide.Radius + f.Guide.StartAngle + f.Guide.Sweep)))+ return Invalid("offset-collapse", $"{f.Name}: guide radius must exceed half the section width.");+ if (f.Guide.Kind == PlanarGuideKind.Arc && (f.RoundEnds || f.Guide.Sweep <= 0 || f.Guide.Sweep > double.Pi))+ return Invalid("arc", $"{f.Name}: open arcs currently require Flat ends and a positive sweep no greater than 180deg.");+ if (f.Guide.Kind == PlanarGuideKind.Circle && f.RoundEnds) return Invalid("ends", $"{f.Name}: closed guides have no end caps.");+ var widthTop = f.Width - 2 * f.Extent * double.Tan(f.DraftDegrees * double.Pi / 180);+ if (widthTop <= 1e-8) return Invalid("draft-collapse", $"{f.Name}: draft collapses the rib top; reduce draft/height or increase thickness.");+ return KernelResult<bool>.Success(true);++ static KernelResult<bool> Invalid(string code, string message) =>+ KernelResult<bool>.Failure(Failure(code, message).Diagnostics);+ }+public static KernelResult<PathFeatureBody> BuildBox(double x, double y, double z, IReadOnlyList<PlanarPathFeature> features){if (!double.IsFinite(x + y + z) || x <= 0 || y <= 0 || z <= 0) return Failure("dimensions", "Box dimensions must be finite and positive.");var source = BrepPrimitives.CreateBox(x, y, z);if (!source.IsSuccess) return KernelResult<PathFeatureBody>.Failure(source.Diagnostics);- var p = new AnalyticPatchBuilder(source.Value);- var support = source.Value.Topology.Faces.Single(f => source.Value.Geometry.GetSurface(source.Value.Bindings.GetFaceBinding(f.Id).SurfaceGeometryId).Plane is { } plane- && plane.Normal.Z > .9);+ return BuildOnBox(source.Value, x, y, z, features);+ }++ /// <summary>Host is in the centered Box frame. The caller proves that the+ /// footprints clear existing cavities and the retained outer support boundary.</summary>+ public static KernelResult<PathFeatureBody> BuildOnBox(BrepBody source, double x, double y, double z, IReadOnlyList<PlanarPathFeature> features)+ {+ var p = new AnalyticPatchBuilder(source);+ var support = source.Topology.Faces.Where(f => source.Geometry.GetSurface(source.Bindings.GetFaceBinding(f.Id).SurfaceGeometryId).Plane is { } plane+ && plane.Normal.Z > .9 && double.Abs(plane.Origin.Z - z / 2) < 1e-8)+ .OrderByDescending(f => f.LoopIds.SelectMany(l => source.Topology.GetLoop(l).CoedgeIds).Count()).FirstOrDefault();+ if (support is null) return Failure("support", "No retained planar Box top is available.");var supportLoops = support.LoopIds.ToList();var footprints = new List<(double MinX, double MinY, double MaxX, double MaxY)>();var faces = new Dictionary<string, IReadOnlyList<FaceId>>(StringComparer.Ordinal);double volume = 0;foreach (var f in features){- if (!double.IsFinite(f.Width + f.Extent + f.DraftDegrees) || f.Width <= 0 || f.Extent <= 0 || f.DraftDegrees < 0 || f.DraftDegrees >= 89)- return Failure("dimensions", $"{f.Name}: width/height/depth must be positive; draft must be in [0deg,89deg).");- if (!Enum.IsDefined(f.Guide.Kind) || !Enum.IsDefined(f.Section)- || !double.IsFinite(f.Guide.Start.X + f.Guide.Start.Y + f.Guide.End.X + f.Guide.End.Y + f.Guide.Center.X + f.Guide.Center.Y))- return Failure("guide", $"{f.Name}: guide kind and coordinates must be finite and admitted.");+ var admitted = ValidateFeature(f, z);+ if (!admitted.IsSuccess) return KernelResult<PathFeatureBody>.Failure(admitted.Diagnostics);if (faces.ContainsKey(f.Name)) return Failure("duplicate", $"Duplicate path feature '{f.Name}'.");- if (f.Section == PathSectionKind.Semicircular && (f.Add || double.Abs(f.Extent - f.Width / 2) > 1e-9 || f.DraftDegrees != 0))- return Failure("section", $"{f.Name}: semicircular removal requires depth = radius = width/2 and no draft.");- if (!f.Add && (f.Extent >= z - 1e-8 || f.DraftDegrees != 0)) return Failure("floor", $"{f.Name}: groove must leave a positive floor; groove draft is unsupported.");- if (f.Guide.Kind != PlanarGuideKind.Line && (f.Guide.Radius <= f.Width / 2 + 1e-8- || !double.IsFinite(f.Guide.Radius + f.Guide.StartAngle + f.Guide.Sweep)))- return Failure("offset-collapse", $"{f.Name}: guide radius must exceed half the section width.");- if (f.Guide.Kind == PlanarGuideKind.Arc && (f.RoundEnds || f.Guide.Sweep <= 0 || f.Guide.Sweep > double.Pi))- return Failure("arc", $"{f.Name}: open arcs currently require Flat ends and a positive sweep no greater than 180deg.");- if (f.Guide.Kind == PlanarGuideKind.Circle && f.RoundEnds) return Failure("ends", $"{f.Name}: closed guides have no end caps.");var widthTop = f.Width - 2 * f.Extent * double.Tan(f.DraftDegrees * double.Pi / 180);- if (widthTop <= 1e-8) return Failure("draft-collapse", $"{f.Name}: draft collapses the rib top; reduce draft/height or increase thickness.");var baseOutline = Outline(f.Guide, f.Width / 2, f.RoundEnds);if (baseOutline is null) return Failure("guide", $"{f.Name}: line guide must have nonzero finite length.");var bounds = Bounds(baseOutline);diff --git a/Aetheris.Kernel.Core/Brep/Features/BrepRuledRibNetwork.cs b/Aetheris.Kernel.Core/Brep/Features/BrepRuledRibNetwork.csnew file mode 100644index 00000000..54d163c9--- /dev/null+++ b/Aetheris.Kernel.Core/Brep/Features/BrepRuledRibNetwork.cs@@ -0,0 +1,80 @@+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Curves;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Results;+using Aetheris.Kernel.Core.Topology;++namespace Aetheris.Kernel.Core.Brep.Features;++/// <summary>Corresponding polygon vertices certified by the arrangement planner.+/// Each side retains the authored rib which supplies its supporting plane.</summary>+public sealed record RibLoftLoop(IReadOnlyList<ProfilePoint2D> Lower, IReadOnlyList<ProfilePoint2D> Upper,+ IReadOnlyList<string> SideOwners);+public sealed record RibLoftRegion(IReadOnlyList<RibLoftLoop> Loops);+public sealed record RibLoftBody(BrepBody Body, IReadOnlyDictionary<FaceId, string> SideOwners);++public static class BrepRuledRibNetwork+{+ public static KernelResult<RibLoftBody> Build(IReadOnlyList<RibLoftRegion> regions, double height)+ {+ KernelResult<RibLoftBody> Fail(string message) => KernelResult<RibLoftBody>.Failure([+ new(Diagnostics.KernelDiagnosticCode.ValidationFailed,Diagnostics.KernelDiagnosticSeverity.Error,"rib-loft-invalid: "+message,"Brep.RibNetwork")]);+ if (!double.IsFinite(height) || height <= 0 || regions.Count == 0) return Fail("Positive height and nonempty regions are required.");+ var b = new TopologyBuilder(); var g = new BrepGeometryStore(); var bindings = new BrepBindingModel();+ var points = new Dictionary<VertexId, Point3D>(); var faces = new List<FaceId>(); var owners = new Dictionary<FaceId, string>();+ var curve = 0; var surface = 0;+ VertexId Vertex(ProfilePoint2D p, double z)+ {+ var point = new Point3D(p.X, p.Y, z);+ if (!double.IsFinite(p.X + p.Y)) throw new ArgumentException("Non-finite loft point.");+ var id = b.AddVertex(); points[id] = point; return id;+ }+ EdgeId Line(VertexId a, VertexId c)+ {+ var delta = points[c] - points[a]; var edge = b.AddEdge(a, c); var id = new CurveGeometryId(++curve);+ g.AddCurve(id, CurveGeometry.FromLine(new(points[a], Direction3D.Create(delta))));+ bindings.AddEdgeBinding(new(edge, id, new(0, delta.Length))); return edge;+ }+ LoopId Loop(IReadOnlyList<(EdgeId Edge, bool Reverse)> uses)+ {+ var id = b.AllocateLoopId(); var coedges = uses.Select(_ => b.AllocateCoedgeId()).ToArray();+ for (var i = 0; i < coedges.Length; i++) b.AddCoedge(new(coedges[i], uses[i].Edge, id, coedges[(i + 1) % coedges.Length], coedges[(i + coedges.Length - 1) % coedges.Length], uses[i].Reverse));+ b.AddLoop(new Loop(id, coedges)); return id;+ }+ FaceId Face(IReadOnlyList<LoopId> loops, PlaneSurface plane)+ {+ var f = b.AddFace(loops); faces.Add(f); var id = new SurfaceGeometryId(++surface); g.AddSurface(id, SurfaceGeometry.FromPlane(plane)); bindings.AddFaceBinding(new(f, id));+ for (var i = 0; i < loops.Count; i++) bindings.AddFaceBoundaryRoleBinding(new(f, loops[i], i == 0 ? FaceBoundaryRole.Outer : FaceBoundaryRole.Inner));+ return f;+ }+ foreach (var region in regions)+ {+ var lowerCaps = new List<LoopId>(); var upperCaps = new List<LoopId>();+ foreach (var loop in region.Loops)+ {+ var n = loop.Lower.Count;+ if (n < 3 || loop.Upper.Count != n || loop.SideOwners.Count != n) return Fail("Section correspondence is incomplete.");+ var lo = loop.Lower.Select(p => Vertex(p, 0)).ToArray(); var hi = loop.Upper.Select(p => Vertex(p, height)).ToArray();+ var lower = Enumerable.Range(0, n).Select(i => Line(lo[i], lo[(i + 1) % n])).ToArray();+ var upper = Enumerable.Range(0, n).Select(i => Line(hi[i], hi[(i + 1) % n])).ToArray();+ var links = Enumerable.Range(0, n).Select(i => Line(lo[i], hi[i])).ToArray();+ lowerCaps.Add(Loop(lower.Select(e => (e, true)).Reverse().ToArray())); upperCaps.Add(Loop(upper.Select(e => (e, false)).ToArray()));+ for (var i = 0; i < n; i++)+ {+ var j = (i + 1) % n; var origin = points[lo[i]]; var u = points[lo[j]] - origin;+ var normal = Direction3D.Create(u.Cross(points[hi[i]] - origin));+ if (double.Abs((points[hi[j]] - origin).Dot(normal.ToVector())) > 1e-7) return Fail("A ruled side is not planar.");+ var f = Face([Loop([(lower[i], false), (links[j], false), (upper[i], true), (links[i], true)])], new(origin, normal, Direction3D.Create(u)));+ owners[f] = loop.SideOwners[i];+ }+ }+ Face(lowerCaps, new(new(0, 0, 0), Direction3D.Create(new(0, 0, -1)), BrepPlanarPathFeature.X));+ Face(upperCaps, new(new(0, 0, height), BrepPlanarPathFeature.Z, BrepPlanarPathFeature.X));+ }+ b.AddBody([b.AddShell(faces)]);+ var body = new BrepBody(b.Model, g, bindings, points);+ var valid = BrepBindingValidator.Validate(body, true); if (!valid.IsSuccess) return KernelResult<RibLoftBody>.Failure(valid.Diagnostics);+ return KernelResult<RibLoftBody>.Success(new(body, owners));+ }+}diff --git a/Aetheris.Kernel.Core/Brep/Features/CombinedTopBoundaryEdgeFinishThroughHoleBuilder.cs b/Aetheris.Kernel.Core/Brep/Features/CombinedTopBoundaryEdgeFinishThroughHoleBuilder.csindex 21650262..fd339a1a 100644--- a/Aetheris.Kernel.Core/Brep/Features/CombinedTopBoundaryEdgeFinishThroughHoleBuilder.cs+++ b/Aetheris.Kernel.Core/Brep/Features/CombinedTopBoundaryEdgeFinishThroughHoleBuilder.cs@@ -33,7 +33,7 @@ public sealed record CombinedTopBoundaryEdgeFinishThroughHole(+ (IsCountersink ? System.Math.PI / 3d * (EntryRadius - Radius) * (EntryRadius + 2d * Radius) * ReliefDepth!.Value : 0d);}-public enum TopBoundaryEdgeFinishKind { Chamfer, Fillet }+public enum TopBoundaryEdgeFinishKind { Chamfer, Fillet, None }public sealed record CombinedTopBoundaryEdgeFinishThroughHolePlan(string PlanId,@@ -107,12 +107,13 @@ public static class CombinedTopBoundaryEdgeFinishThroughHoleBuilderPoint3D[] top){var b = new TopologyBuilder();- var vertices = Enumerable.Range(0, 12).Select(_ => b.AddVertex()).ToArray();+ var unfinished = plan.FinishKind == TopBoundaryEdgeFinishKind.None;+ var vertices = Enumerable.Range(0, unfinished ? 8 : 12).Select(_ => b.AddVertex()).ToArray();var bottomEdges = Ring(b, vertices, 0);var shoulderEdges = Ring(b, vertices, 4);- var topEdges = Ring(b, vertices, 8);+ var topEdges = unfinished ? shoulderEdges : Ring(b, vertices, 8);var lowerEdges = Enumerable.Range(0, 4).Select(i => b.AddEdge(vertices[i], vertices[4 + i])).ToArray();- var finishEdges = Enumerable.Range(0, 4).Select(i => b.AddEdge(vertices[4 + i], vertices[8 + i])).ToArray();+ var finishEdges = Enumerable.Range(0, unfinished ? 0 : 4).Select(i => b.AddEdge(vertices[4 + i], vertices[8 + i])).ToArray();var holes = plan.Holes.Select(h =>{// The periodic circle and its longitudinal seam share endpoint identities.@@ -147,12 +148,12 @@ public static class CombinedTopBoundaryEdgeFinishThroughHoleBuildervar bottomFace = b.AddFace(bottomLoops);var topFace = b.AddFace(topLoops);var lowerFaces = new FaceId[4];- var finishFaces = new FaceId[4];+ var finishFaces = new FaceId[unfinished ? 0 : 4];for (var i = 0; i < 4; i++){var next = (i + 1) % 4;lowerFaces[i] = b.AddFace([AddLoop(b, [Forward(bottomEdges[i]), Forward(lowerEdges[next]), Reversed(shoulderEdges[i]), Reversed(lowerEdges[i])])]);- finishFaces[i] = b.AddFace([AddLoop(b, [Forward(shoulderEdges[i]), Forward(finishEdges[next]), Reversed(topEdges[i]), Reversed(finishEdges[i])])]);+ if (!unfinished) finishFaces[i] = b.AddFace([AddLoop(b, [Forward(shoulderEdges[i]), Forward(finishEdges[next]), Reversed(topEdges[i]), Reversed(finishEdges[i])])]);}var holeFaces = new List<(HoleTopology Hole, FaceId Face, double Radius, double ZMin, double ZMax, bool Cone)>();var shoulderFaces = new List<(HoleTopology Hole, FaceId Face)>();@@ -186,10 +187,10 @@ public static class CombinedTopBoundaryEdgeFinishThroughHoleBuildervar geometry = new BrepGeometryStore();var bindings = new BrepBindingModel();- var points = bottom.Concat(shoulder).Concat(top).ToArray();+ var points = (unfinished ? bottom.Concat(shoulder) : bottom.Concat(shoulder).Concat(top)).ToArray();var vertexPoints = vertices.Select((id, index) => new KeyValuePair<VertexId, Point3D>(id, points[index])).ToDictionary(x => x.Key, x => x.Value);var edgeCurve = 1;- foreach (var edge in bottomEdges.Concat(shoulderEdges).Concat(topEdges).Concat(lowerEdges).Concat(finishEdges))+ foreach (var edge in bottomEdges.Concat(shoulderEdges).Concat(topEdges).Concat(lowerEdges).Concat(finishEdges).Distinct()){var start = vertexPoints[b.Model.Edges.Single(e => e.Id == edge).StartVertexId];var end = vertexPoints[b.Model.Edges.Single(e => e.Id == edge).EndVertexId];@@ -224,6 +225,7 @@ public static class CombinedTopBoundaryEdgeFinishThroughHoleBuilder{var next = (i + 1) % 4;BindPlane(lowerFaces[i], bottom[i], bottom[next] - bottom[i], shoulder[i] - bottom[i]);+ if (unfinished) continue;if (plan.FinishKind == TopBoundaryEdgeFinishKind.Chamfer)BindPlane(finishFaces[i], shoulder[i], shoulder[next] - shoulder[i], top[i] - shoulder[i]);else@@ -304,7 +306,7 @@ public static class CombinedTopBoundaryEdgeFinishThroughHoleBuilder{if (!Enum.IsDefined(plan.FinishKind)) return Failure("CombinedFeaturePlanChainInvalid: unknown top-boundary finish kind.");if (!double.IsFinite(plan.Width) || !double.IsFinite(plan.Depth) || !double.IsFinite(plan.ZMin) || !double.IsFinite(plan.ZMax) || !double.IsFinite(plan.FinishSize)- || plan.Width <= Tol || plan.Depth <= Tol || plan.ZMax - plan.ZMin <= Tol || plan.FinishSize <= Tol+ || plan.Width <= Tol || plan.Depth <= Tol || plan.ZMax - plan.ZMin <= Tol || (plan.FinishKind == TopBoundaryEdgeFinishKind.None ? plan.FinishSize != 0 : plan.FinishSize <= Tol)|| 2d * plan.FinishSize >= plan.Width - Tol || 2d * plan.FinishSize >= plan.Depth - Tol || plan.FinishSize >= plan.ZMax - plan.ZMin - Tol)return Failure("CombinedFeaturePlanChainInvalid: bounded top-boundary finish size must be positive, smaller than the stock height and smaller than half its width and depth.");foreach (var hole in plan.Holes)diff --git a/Aetheris.Kernel.Core/Step242/Step242Importer.cs b/Aetheris.Kernel.Core/Step242/Step242Importer.csindex 34094e95..5d918498 100644--- a/Aetheris.Kernel.Core/Step242/Step242Importer.cs+++ b/Aetheris.Kernel.Core/Step242/Step242Importer.cs@@ -2250,7 +2250,7 @@ public static class Step242Importer{if (LoopsOverlap(innerLoops[i], innerLoops[j], containmentTolerance)){- return LoopRoleFailure<IReadOnlyList<LoopBuildData>>("Inner loops overlap or are nested.", "Importer.LoopRole.InnerOverlap");+ return LoopRoleFailure<IReadOnlyList<LoopBuildData>>($"Inner loops {innerLoops[i].Loop.LoopId.Value} and {innerLoops[j].Loop.LoopId.Value} overlap or are nested.", "Importer.LoopRole.InnerOverlap");}}}diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentPathFeatureTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentPathFeatureTests.csindex 766c93e2..4b4eac0c 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentPathFeatureTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentPathFeatureTests.cs@@ -3,6 +3,7 @@ using Aetheris.Kernel.Core.Brep.Verification;using Aetheris.Kernel.Core.Geometry;using Aetheris.Kernel.Core.Step242;using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.Materializer;namespace Aetheris.Kernel.Firmament.Tests;@@ -42,7 +43,9 @@ public sealed class FirmamentPathFeatureTestsAssert.Equal(name, Assert.Single(built.Value.MaterializedFeatures).Name);Assert.NotEmpty(built.Value.RuntimeCorrespondence!.Descendants);Assert.Equal(declared.GuideReference, Assert.Single(built.Value.EngineeringFeatures!).Profile);- Assert.All(built.Value.RuntimeCorrespondence.Descendants, d => Assert.Contains(name, d.StableId));+ var featureFaces = built.Value.RuntimeCorrespondence.Descendants.Where(d => d.Role == SemanticTopologyRole.PathFeatureFace).ToArray();+ Assert.NotEmpty(featureFaces);+ Assert.All(featureFaces, d => Assert.Contains(name, d.StableId));var body = built.Value.RuntimeBody!;var points = body.Topology.Vertices.Select(v => { Assert.True(body.TryGetVertexPoint(v.Id, out var p)); return p; }).ToArray();Assert.Equal(0, points.Min(p => p.Z), 8); Assert.Equal(maximumZ, points.Max(p => p.Z), 8);@@ -139,7 +142,7 @@ public sealed class FirmamentPathFeatureTestsBrepMassProperties.Evaluate(second.Value.RuntimeBody!).SignedVolume, 6);var crossing = prefix.Replace("Point2(-15mm,8mm)", "Point2(-15mm,-8mm)", StringComparison.Ordinal) + a + b + "}}";var rejected = FirmamentBuildAndExport.CompileSource(crossing);- Assert.False(rejected.IsSuccess); Assert.Contains("junction-unqualified", Messages(rejected));+ Assert.False(rejected.IsSuccess); Assert.Contains("redundant or completely buried", Messages(rejected));}[Fact]diff --git a/Aetheris.Kernel.Firmament.Tests/RibNetworkTests.cs b/Aetheris.Kernel.Firmament.Tests/RibNetworkTests.csnew file mode 100644index 00000000..86269a02--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/RibNetworkTests.cs@@ -0,0 +1,182 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Verification;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class RibNetworkTests+{+ internal static string Program(double draft=0,double secondHeight=10,string finish="",string hole="")=>$$"""+ Model Junction {+ units: mm+ Box Plate { size: [60mm,50mm,5mm] }+ Path Across { start: Point2(-20mm,0mm); heading: 0deg; Line X { length: 40mm } }+ Path Along { start: Point2(0mm,-15mm); heading: 90deg; Line Y { length: 30mm } }+ Modify Plate {+ Rib<Rectangular> A { on: +Z; path: Across; thickness: 4mm; height: 10mm; draft: {{draft.ToString(System.Globalization.CultureInfo.InvariantCulture)}}deg }+ Rib<Rectangular> B { on: +Z; path: Along; thickness: 4mm; height: {{secondHeight.ToString(System.Globalization.CultureInfo.InvariantCulture)}}mm; draft: {{draft.ToString(System.Globalization.CultureInfo.InvariantCulture)}}deg }+ {{hole}}+ {{finish}}+ }+ }+ """;++ [Theory]+ [InlineData(0,10,"PrismaticSectionArrangement")]+ [InlineData(0,7,"PrismaticSectionArrangement")]+ [InlineData(2,10,"AffineDraftArrangement")]+ public void CrossJunctionIsOneExactClosedBody(double draft,double height,string strategy)+ {+ var source=Program(draft,height);var built=FirmamentBuildAndExport.CompileSource(source);+ Assert.True(built.IsSuccess,string.Join("; ",built.Diagnostics.Select(d=>d.Message)));+ Assert.Equal(strategy,built.Value.RibPlanning!.Strategy);+ Assert.Equal(2,built.Value.MaterializedFeatures.Count);+ Assert.All(built.Value.RuntimeBody!.Topology.Edges,e=>Assert.Equal(2,built.Value.RuntimeBody.Topology.Coedges.Count(c=>c.EdgeId==e.Id)));+ var mass=BrepMassProperties.Evaluate(built.Value.RuntimeBody);+ Assert.True(mass.IsEnclosed&&mass.IsOrientationConsistent,string.Join("; ",mass.Diagnostics));+ var slope=2*Math.Tan(draft*Math.PI/180);+ var expected=15000+70*(4*10-slope*100/2)-(16*10-4*slope*100+slope*slope*1000/3);+ if(height!=10)expected=15000+40*4*10+30*4*height-16*height;+ Assert.InRange(mass.SignedVolume,expected-2,expected+2);+ var read=Step242Importer.ImportBody(built.Value.StepText);+ Assert.True(read.IsSuccess,string.Join("; ",read.Diagnostics.Select(d=>d.Message)));+ Assert.True(BrepMassProperties.Evaluate(read.Value).IsEnclosed);+ }+ [Fact]+ public void UsefulPartCombinesDraftedJunctionsSteppedHolesAndFillet()+ {+ var root=new DirectoryInfo(AppContext.BaseDirectory);+ while(root is not null&&!File.Exists(Path.Combine(root.FullName,"Aetheris.slnx")))root=root.Parent;+ var source=File.ReadAllText(Path.Combine(root!.FullName,"fixtures/Canonical/Features/PathFeatures/reinforced-mounting-plate.firmament"));+ var built=FirmamentBuildAndExport.CompileSource(source);+ Assert.True(built.IsSuccess,string.Join("; ",built.Diagnostics.Select(d=>d.Message)));+ Assert.Equal(5,built.Value.MaterializedFeatures.Count);+ Assert.Equal("AffineDraftArrangement",built.Value.RibPlanning!.Strategy);+ Assert.True(BrepExportPreflight.Validate(built.Value.RuntimeBody!).IsValid);+ }++ [Theory]+ [InlineData("Point2(0mm,0mm)", "15mm")]+ [InlineData("Point2(20mm,0mm)", "15mm")]+ public void TandLJunctionsRemainClosed(string start, string length)+ {+ var source = Program().Replace("Point2(0mm,-15mm)", start).Replace("length: 30mm", "length: " + length);+ AssertClosed(source);+ }++ [Theory]+ [InlineData("Fillet", "radius: 1mm")]+ [InlineData("Chamfer", "distance: 1mm")]+ public void JunctionsCombineWithEachAdmittedThroughHoleAndPerimeterFinish(string kind, string dimension)+ {+ foreach (var (type, fields) in new[] { ("Shaft", ""), ("Counterbore", "counterboreDiameter: 8mm; counterboreDepth: 2mm"), ("Countersink", "countersinkDiameter: 8mm; countersinkAngle: 90deg") })+ AssertClosed(Program(finish: $"EdgeFinish Rim {{ face: +Z; target: Boundary; kind: {kind}; {dimension} }}",+ hole: $"Hole<{type}> Mount {{ on: +Z; center: Point2(-24mm,-18mm); diameter: 4mm; end: ThroughAll; {fields} }}"));+ }++ [Fact]+ public void ClosedRingCrossingStraightRibRetainsItsSupportIslands()+ {+ var source = Program().Replace("Path Along { start: Point2(0mm,-15mm); heading: 90deg; Line Y { length: 30mm } }",+ "Concept Struct Layout { Circle2 Ring { center: Point2(0mm,0mm); radius: 12mm } }").Replace("path: Along", "path: Layout.Ring");+ AssertClosed(source);+ }++ [Theory]+ [InlineData(false, false)]+ [InlineData(false, true)]+ [InlineData(true, false)]+ [InlineData(true, true)]+ public void IsolatedAndJoinedRibsAdmitHolesWithoutRequiringAFinish(bool joined, bool withHoles)+ {+ var hole = withHoles ? """+ Hole<Counterbore> MountA { on: +Z; center: Point2(-24mm,-18mm); diameter: 4mm; end: ThroughAll; counterboreDiameter: 7mm; counterboreDepth: 2mm }+ Hole<Countersink> MountB { on: +Z; center: Point2(24mm,18mm); diameter: 4mm; end: ThroughAll; countersinkDiameter: 7mm; countersinkAngle: 90deg }+ """ : "";+ var source = Program(hole: hole, finish: withHoles ? "" : "EdgeFinish Rim { face: +Z; target: Boundary; kind: Fillet; radius: 1mm }");+ if (!joined) source = string.Join('\n', source.Split('\n').Where(l => !l.Contains("Rib<Rectangular> B")));+ var result = AssertClosed(source);+ Assert.Equal((joined ? 2 : 1) + (withHoles ? 2 : 1), result.MaterializedFeatures.Count);+ Assert.Equal(withHoles ? 0 : 1, result.MaterializedFeatures.Count(f => f.Kind == "EdgeFinish"));+ }++ [Fact]+ public void NoninteractingGrooveCanShareTheReinforcedStock()+ {+ var source = Program().Replace("Modify Plate {", "Path Drain { start: Point2(-15mm,-20mm); heading: 0deg; Line D { length: 30mm } } Modify Plate {")+ .Replace("Rib<Rectangular> A", "Groove<Semicircular> Channel { on: +Z; path: Drain; radius: 1mm } Rib<Rectangular> A");+ AssertClosed(source);+ }++ [Fact]+ public void HoleThroughAJunctionIsRejectedByBothAdmissionPaths()+ {+ var source = Program(hole: "Hole<Shaft> Mount { on: +Z; center: Point2(0mm,0mm); diameter: 4mm; end: ThroughAll }");+ var built = FirmamentBuildAndExport.CompileSource(source);+ Assert.False(built.IsSuccess);+ Assert.Contains(built.Diagnostics, d => d.Message.Contains("intersects Hole 'Mount'"));+ Assert.All(built.Diagnostics.Where(d => d.Severity == Aetheris.Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error), d => Assert.NotNull(d.SourceSpan));+ var validation = FirmamentBuildAdmissionValidation.Admit(FirmamentV2ValidationReportBuilder.Build(+ FirmamentV2Parser.Parse(source), "rib-hole.firmament", sourceText: source), source);+ Assert.Equal("invalid", validation.Status);+ }++ [Theory]+ [InlineData(2, 7, "no admitted rib plan")]+ [InlineData(15, 10, "draft collapses")]+ public void UnsupportedOrCollapsedDraftHasAnHonestFailure(double draft, double height, string reason)+ {+ var built = FirmamentBuildAndExport.CompileSource(Program(draft, height));+ Assert.False(built.IsSuccess);+ Assert.Contains(built.Diagnostics, d => d.Message.Contains(reason, StringComparison.OrdinalIgnoreCase));+ }++ [Fact]+ public void IsolatedRibKeepsTheExistingExactGeometry()+ {+ var source = Program().Split('\n').Where(l => !l.Contains("Rib<Rectangular> B"));+ var text = string.Join('\n', source);+ var document = FirmamentV2Parser.Parse(text).Document!;+ var old = Aetheris.Kernel.Core.Brep.Features.BrepPlanarPathFeature.BuildBox(60, 50, 5, [document.PathFeatures.Single().Feature]);+ Assert.True(old.IsSuccess);+ var expected = Aetheris.Kernel.Firmament.Execution.FirmamentPrimitiveExecutionTranslation.TranslateBody(old.Value.Body, new(0, 0, 2.5));+ var actual = AssertClosed(text);+ Assert.Equal("ExistingAnalyticPatch", actual.RibPlanning!.Strategy);+ Assert.Equal(expected.Geometry.Curves.OrderBy(x => x.Key.Value), actual.RuntimeBody!.Geometry.Curves.OrderBy(x => x.Key.Value));+ Assert.Equal(expected.Geometry.Surfaces.OrderBy(x => x.Key.Value), actual.RuntimeBody.Geometry.Surfaces.OrderBy(x => x.Key.Value));+ foreach (var vertex in expected.Topology.Vertices)+ {+ Assert.True(expected.TryGetVertexPoint(vertex.Id, out var a));+ Assert.True(actual.RuntimeBody.TryGetVertexPoint(vertex.Id, out var b));+ Assert.Equal(a, b);+ }+ }++ [Fact]+ public void JunctionReorderingPreservesExactStepAndStableNames()+ {+ var source = Program(2);+ var lines = source.Split('\n');+ var a = Array.FindIndex(lines, l => l.Contains("Rib<Rectangular> A"));+ var b = Array.FindIndex(lines, l => l.Contains("Rib<Rectangular> B"));+ (lines[a], lines[b]) = (lines[b], lines[a]);+ var first = AssertClosed(source); var second = AssertClosed(string.Join('\n', lines));+ Assert.Equal(first.StepText, second.StepText);+ Assert.Equal(first.RuntimeCorrespondence!.Descendants.Select(d => d.StableId).Order(), second.RuntimeCorrespondence!.Descendants.Select(d => d.StableId).Order());+ }++ private static FirmamentStepExportResult AssertClosed(string source)+ {+ var built = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(built.IsSuccess, string.Join("; ", built.Diagnostics.Select(d => d.Message)));+ var body = built.Value.RuntimeBody!;+ Assert.All(body.Topology.Edges, e => Assert.Equal(2, body.Topology.Coedges.Count(c => c.EdgeId == e.Id)));+ var mass = BrepMassProperties.Evaluate(body);+ Assert.True(mass.IsEnclosed && mass.IsOrientationConsistent, string.Join("; ", mass.Diagnostics));+ var read = Step242Importer.ImportBody(built.Value.StepText);+ Assert.True(read.IsSuccess, string.Join("; ", read.Diagnostics.Select(d => d.Message)));+ Assert.True(BrepMassProperties.Evaluate(read.Value).IsEnclosed);+ return built.Value;+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex cd548025..3b2bb252 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -1460,11 +1460,14 @@ public static partial class FirmamentBuildAndExport}private static KernelResult<FirmamentStepExportResult>? TryExportV2CombinedHoleEdgeFinishBody(FirmamentV2Document document)+ => ExportV2BoxThroughHoleStock(document, allowUnfinished: false);++ private static KernelResult<FirmamentStepExportResult>? ExportV2BoxThroughHoleStock(FirmamentV2Document document, bool allowUnfinished){var modifies = document.ModifyBlocks ?? [];var holesDeclared = modifies.SelectMany(m => m.SemanticHoles).ToArray();var finishes = modifies.SelectMany(m => (m.EdgeFinishes ?? [])).ToArray();- if (holesDeclared.Length == 0 || finishes.Length == 0)+ if (holesDeclared.Length == 0 || finishes.Length == 0 && !allowUnfinished){return null;}@@ -1481,16 +1484,18 @@ public static partial class FirmamentBuildAndExportreturn CombinedFailure($"CombinedFeatureHostUnsupported: Modify target '{modify.TargetSolid}' must resolve to an admitted Box for combined holes and a boundary finish.", sourceSpan: solid?.SourceSpan ?? holesDeclared[0].SourceSpan);}- if (finishes.Length != 1)+ if (finishes.Length > 1 || finishes.Length == 0 && !allowUnfinished){return CombinedFailure($"CombinedFeatureThirdFamilyUnsupported: This Box plan admits one top-boundary EdgeFinish (actual={finishes.Length}).", sourceSpan: finishes[1].SourceSpan);}- var finish = finishes[0];- if (!string.Equals(finish.FaceAxis, "+Z", StringComparison.Ordinal) || !string.Equals(finish.Target, "Boundary", StringComparison.Ordinal)- || finish.Kind is not ("Chamfer" or "Fillet"))+ var finish = finishes.SingleOrDefault();+ var finishSpan = finish?.SourceSpan ?? holesDeclared[0].SourceSpan;+ var finishName = finish?.Name ?? "UnfinishedStock";+ if (finish is not null && (!string.Equals(finish.FaceAxis, "+Z", StringComparison.Ordinal) || !string.Equals(finish.Target, "Boundary", StringComparison.Ordinal)+ || finish.Kind is not ("Chamfer" or "Fillet"))){- return CombinedFailure($"CombinedFeatureSelectionLost: EdgeFinish '{finish.Name}' must select the +Z outer Boundary with Kind Chamfer or Fillet. Other combined selectors are not admitted.", sourceSpan: finish.SourceSpan);+ return CombinedFailure($"CombinedFeatureSelectionLost: EdgeFinish '{finishName}' must select the +Z outer Boundary with Kind Chamfer or Fillet. Other combined selectors are not admitted.", sourceSpan: finishSpan);}var holes = FirmamentV2SemanticHoleLowering.LowerSemanticHoles(document);@@ -1528,35 +1533,35 @@ public static partial class FirmamentBuildAndExport// Preserve the existing chamfer admission and realization unchanged. Fillet// admission is owned by the same bounded final plan that realizes its cylinders.- if (finish.Kind == "Chamfer")+ if (finish?.Kind == "Chamfer"){var compiledFinish = AirTopFaceBoundaryChamferCompiler.Compile(new(- solid.Name, $"{solid.Name}.{finish.Name}", finish.Name,+ solid.Name, $"{solid.Name}.{finishName}", finish.Name,box.Size[0], box.Size[1], box.Size[2], finish.FaceAxis, finish.Target, finish.Kind, finish.Distance,- new AirSourceSpan(finish.SourceSpan.Start, finish.SourceSpan.Length, document.ModelName)));+ new AirSourceSpan(finishSpan.Start, finishSpan.Length, document.ModelName)));if (!compiledFinish.Succeeded || compiledFinish.BRepPlan?.RealizationPlan is null)- return CombinedFailure("CombinedFeatureSelectionLost: post-Hole outer boundary selection did not admit the exact chamfer planner.", compiledFinish.Diagnostics, finish.SourceSpan);+ return CombinedFailure("CombinedFeatureSelectionLost: post-Hole outer boundary selection did not admit the exact chamfer planner.", compiledFinish.Diagnostics, finishSpan);}var parentHolePlan = string.Join(",", holeStages.Select(s => s.Plan!.HoleBRepPlan?.StableId ?? s.Plan!.SemanticFeatureId));var finalPlan = new CombinedTopBoundaryEdgeFinishThroughHolePlan(- $"brep-plan:combined-hole-edgefinish:{solid.Name}:{finish.Name}",+ $"brep-plan:combined-hole-edgefinish:{solid.Name}:{finishName}",$"brep-plan:host:{solid.Name}->[{parentHolePlan}]",- ["HostBRepPlan", "HoleChangedBRepPlan", "EdgeFinishChangedBRepPlan"],- box.Size[0], box.Size[1], host.ZMin, host.ZMax, finish.Distance, combinedHoles,- finish.Kind == "Fillet" ? TopBoundaryEdgeFinishKind.Fillet : TopBoundaryEdgeFinishKind.Chamfer);+ finish is null ? ["HostBRepPlan", "HoleChangedBRepPlan"] : ["HostBRepPlan", "HoleChangedBRepPlan", "EdgeFinishChangedBRepPlan"],+ box.Size[0], box.Size[1], host.ZMin, host.ZMax, finish?.Distance ?? 0, combinedHoles,+ finish is null ? TopBoundaryEdgeFinishKind.None : finish.Kind == "Fillet" ? TopBoundaryEdgeFinishKind.Fillet : TopBoundaryEdgeFinishKind.Chamfer);var materialized = CombinedTopBoundaryEdgeFinishThroughHoleBuilder.Build(finalPlan);if (!materialized.IsSuccess || materialized.Value is null){- return CombinedFailure("CombinedFeatureInteractionUnsupported: the combined Hole and EdgeFinish plan was rejected.", materialized.Diagnostics.Select(d => d.Message), finish.SourceSpan);+ return CombinedFailure("CombinedFeatureInteractionUnsupported: the combined Hole and EdgeFinish plan was rejected.", materialized.Diagnostics.Select(d => d.Message), finishSpan);}var body = materialized.Value;- if (finish.Kind == "Fillet")+ if (finish?.Kind == "Fillet"){var preflight = BrepExportPreflight.Validate(body);if (!preflight.IsValid)- return CombinedFailure("CombinedFeatureMaterializerDiverged: fillet boundary failed analytic export preflight.", preflight.Diagnostics.Select(d => d.Message), finish.SourceSpan);+ return CombinedFailure("CombinedFeatureMaterializerDiverged: fillet boundary failed analytic export preflight.", preflight.Diagnostics.Select(d => d.Message), finishSpan);}if (!FirmamentManifoldChecker.IsManifold(body)){@@ -1583,7 +1588,7 @@ public static partial class FirmamentBuildAndExportvar finalTop = body.Topology.Faces.Single(f => f.Id.Value == 2);var finalBottom = body.Topology.Faces.Single(f => f.Id.Value == 1);// The builder emits the counterbore wall and shoulder before the shaft.- var wallFaceId=11;+ var wallFaceId = finish is null ? 7 : 11;for (var i = 0; i < holes.Count; i++){var source = $"hole:{holes[i].FeatureId}";@@ -1598,9 +1603,9 @@ public static partial class FirmamentBuildAndExportdescendants.Add(new($"combined:{source}:countersink-wall", "Face", SemanticTopologyRole.HoleWallFace, source, Face: new FaceId(wallFaceId++), ParentStableId: holes[i].FeatureId));descendants.Add(new($"combined:{source}:shaft-wall", "Face", SemanticTopologyRole.HoleWallFace, source, Face: new FaceId(wallFaceId++), ParentStableId: holes[i].FeatureId));}- for (var side = 0; side < 4; side++)- descendants.Add(new($"combined:edgefinish:{finish.Name}:replacement:{side}", "Face", SemanticTopologyRole.EdgeFinishReplacementFace,- $"edgefinish:{finish.Name}", Face: new FaceId(4 + 2 * side), ParentStableId: finish.Name));+ for (var side = 0; finish is not null && side < 4; side++)+ descendants.Add(new($"combined:edgefinish:{finishName}:replacement:{side}", "Face", SemanticTopologyRole.EdgeFinishReplacementFace,+ $"edgefinish:{finishName}", Face: new FaceId(4 + 2 * side), ParentStableId: finishName));var correspondence = new SemanticTopologyCorrespondence(solid.Name, descendants, ["HostBRepPlan", "HoleChangedBRepPlan", "EdgeFinishChangedBRepPlan", "AuthoritativeBRepPlan"]);if (correspondence.Descendants.Count(d => d.Role == SemanticTopologyRole.HoleEntryLoop) != holes.Count || correspondence.Descendants.Count(d => d.Role == SemanticTopologyRole.HoleExitLoop) != holes.Count){@@ -1626,7 +1631,7 @@ public static partial class FirmamentBuildAndExportDimensionInspection: document.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.HoleDiameter).Select(p => new FirmamentPmiInspectionDimension("Diameter", p.Target, null, p.Value ?? 0d, "explicit-v2-semantic-pmi", p.Name)).ToArray() ?? [],ConceptIr: document.ConceptIr,Features: featureReports,- Combined: report) { RuntimeBody = body, RuntimeCorrespondence = correspondence, MaterializedFeatures = FirmamentFeatureAccounting.Receipts(solid.Name, "Hole", holes.Select(h => h.Name).ToArray()).Append(new FirmamentFeatureReceipt(solid.Name, "EdgeFinish", finish.Name)).ToArray() });+ Combined: report) { RuntimeBody = body, RuntimeCorrespondence = correspondence, MaterializedFeatures = FirmamentFeatureAccounting.Receipts(solid.Name, "Hole", holes.Select(h => h.Name).ToArray()).Concat(finish is null ? [] : new[] { new FirmamentFeatureReceipt(solid.Name, "EdgeFinish", finish.Name) }).ToArray() });}private static KernelResult<FirmamentStepExportResult> ExportV2TopBoundaryFillet(diff --git a/Aetheris.Kernel.Firmament/FirmamentPathFeatureExport.cs b/Aetheris.Kernel.Firmament/FirmamentPathFeatureExport.csindex 5774c881..62784b08 100644--- a/Aetheris.Kernel.Firmament/FirmamentPathFeatureExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentPathFeatureExport.cs@@ -13,18 +13,11 @@ public static partial class FirmamentBuildAndExportprivate static KernelResult<FirmamentStepExportResult> ExportPathFeatures(FirmamentV2Document document){var stock = document.Solid;- KernelResult<PathFeatureBody> built; double height;- if (stock.Box is { } box)- {- height = box.Size[2];- built = BrepPlanarPathFeature.BuildBox(box.Size[0], box.Size[1], height, document.PathFeatures.Select(f => f.Feature).ToArray());- }- else- {- var cylinder = stock.Cylinder!; height = cylinder.Height;- built = BrepCircumferentialGroove.BuildCylinder(cylinder.Radius, height, document.PathFeatures.Select(f =>- new CircumferentialGroove(f.Feature.Name, f.Feature.Section, f.Feature.Width, f.Feature.Extent, f.Station - height / 2, f.Support == "InnerWall")).ToArray(), stock.Hollow?.WallThickness);- }+ if(stock.Box is not null)return ExportBoxPathNetwork(document);+ var cylinder = stock.Cylinder!;+ var height = cylinder.Height;+ var built = BrepCircumferentialGroove.BuildCylinder(cylinder.Radius, height, document.PathFeatures.Select(f =>+ new CircumferentialGroove(f.Feature.Name, f.Feature.Section, f.Feature.Width, f.Feature.Extent, f.Station - height / 2, f.Support == "InnerWall")).ToArray(), stock.Hollow?.WallThickness);if (!built.IsSuccess)return KernelResult<FirmamentStepExportResult>.Failure(built.Diagnostics.Select(d =>{diff --git a/Aetheris.Kernel.Firmament/FirmamentRibNetworkExport.cs b/Aetheris.Kernel.Firmament/FirmamentRibNetworkExport.csnew file mode 100644index 00000000..2d901195--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentRibNetworkExport.cs@@ -0,0 +1,137 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Features;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Results;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Core.Topology;+using Aetheris.Kernel.Firmament.Execution;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.Materializer;++namespace Aetheris.Kernel.Firmament;++public static partial class FirmamentBuildAndExport+{+ private static KernelResult<FirmamentStepExportResult> ExportBoxPathNetwork(FirmamentV2Document document)+ {+ var stock = document.Solid; var size = stock.Box!.Size; var height = size[2];+ KernelResult<FirmamentStepExportResult> Fail(string text) => CombinedFailure("rib-network-rejected: " + text, sourceSpan: stock.SourceSpan);+ var holes = (document.ModifyBlocks ?? []).SelectMany(m => m.SemanticHoles).ToArray();+ var finishes = (document.ModifyBlocks ?? []).SelectMany(m => m.EdgeFinishes ?? []).ToArray();+ if (finishes.Length > 1 || finishes.Any(f => f.FaceAxis != "+Z" || f.Target != "Boundary" || f.Kind is not ("Fillet" or "Chamfer")))+ return Fail("Mixed ribs currently admit one +Z perimeter Fillet/Chamfer, not arbitrary-edge finishes.");+ if (holes.Any(h => h.EntryFace.Axis != "+Z" || h.EndCondition.Kind != FirmamentV2SemanticHoleEndKind.ThroughAll))+ return Fail("Mixed ribs currently admit top-entry ThroughAll shaft, counterbore and countersink holes.");+ var mixed = holes.Length > 0 || finishes.Length > 0;+ var plan = RibNetworkPlanner.Plan(size[0], size[1], height, document.PathFeatures);+ if (!plan.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(plan.Diagnostics.Select(d => d with { SourceSpan = stock.SourceSpan is { } s ? new(s.Start, s.Length) : null }).ToArray());+ var profiles = document.PathFeatures.ToDictionary(f => f.Feature.Name, f => RibNetworkPlanner.Profile(f.Feature, 0), StringComparer.Ordinal);+ var margin = finishes.SingleOrDefault()?.Distance ?? 0;+ foreach (var f in document.PathFeatures)+ {+ var bounds = RibNetworkPlanner.Bounds(profiles[f.Feature.Name]);+ if (bounds.MinX <= -size[0] / 2 + margin + 1e-7 || bounds.MaxX >= size[0] / 2 - margin - 1e-7 || bounds.MinY <= -size[1] / 2 + margin + 1e-7 || bounds.MaxY >= size[1] / 2 - margin - 1e-7)+ return Fail(f.Feature.Name + ": footprint enters the perimeter finish or leaves the support.");+ foreach (var hole in holes)+ if (!Disjoint(profiles[f.Feature.Name], HoleProfile(hole)))+ return Fail(f.Feature.Name + ": intersects Hole '" + hole.Name + "'. A hole through a rib needs an explicit higher support; it is not silently drilled from the stock datum.");+ }+ foreach (var groove in document.PathFeatures.Where(f => !f.Feature.Add))+ foreach (var other in document.PathFeatures.Where(f => f.Feature.Name != groove.Feature.Name))+ if (!Disjoint(profiles[groove.Feature.Name], profiles[other.Feature.Name]))+ return Fail(groove.Feature.Name + ": groove/rib or groove/groove intersections require a separate local removal plan.");+ var baseDocument = document with { PathFeatures = [], ModifyBlocks = mixed ? [new(stock.Name, [], holes, finishes)] : [] };+ KernelResult<FirmamentStepExportResult>? builtStock = null;+ if (holes.Length > 0 && finishes.Length > 0) builtStock = TryExportV2CombinedHoleEdgeFinishBody(baseDocument);+ else if (holes.Length > 0) builtStock = ExportV2BoxThroughHoleStock(baseDocument, allowUnfinished: true);+ else if (finishes.Length > 0) builtStock = TryExportV2AirChamferBody(baseDocument);+ if (builtStock is { IsSuccess: false }) return builtStock;+ BrepBody host; SemanticTopologyCorrespondence? stockCorrespondence = null;+ if (builtStock?.Value.RuntimeBody is { } existing) { host = existing; stockCorrespondence = builtStock.Value.RuntimeCorrespondence; }+ else if (mixed) return Fail("The existing stock feature owner did not produce an exact body for this combination.");+ else+ {+ var plain = BrepPrimitives.CreateBoxWithTopology(size[0], size[1], height, out var boxTopology);+ if (!plain.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(plain.Diagnostics);+ host = FirmamentPrimitiveExecutionTranslation.TranslateBody(plain.Value, new(0, 0, height / 2));+ stockCorrespondence = BoxConstructionCorrespondence.Create(stock.Name, boxTopology!, stock.SourceSpan);+ }+ var descendants = (stockCorrespondence?.Descendants ?? []).ToList();+ if (plan.Value.Isolated is { } isolated)+ {+ PathFeatureBody body;+ if (!mixed) body = isolated;+ else+ {+ var centered = FirmamentPrimitiveExecutionTranslation.TranslateBody(host, new(0, 0, -height / 2));+ var applied = BrepPlanarPathFeature.BuildOnBox(centered, size[0], size[1], height, document.PathFeatures.Select(f => f.Feature).ToArray());+ if (!applied.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(applied.Diagnostics);+ body = applied.Value;+ }+ host = FirmamentPrimitiveExecutionTranslation.TranslateBody(body.Body, new(0, 0, height / 2));+ foreach (var f in document.PathFeatures)+ descendants.AddRange(body.Faces[f.Feature.Name].Select((face, i) => Descendant(stock.Name, f.Feature.Name, face, i)));+ }+ else+ {+ var grooves = document.PathFeatures.Where(f => !f.Feature.Add).ToArray();+ if (grooves.Length > 0)+ {+ var centered = FirmamentPrimitiveExecutionTranslation.TranslateBody(host, new(0, 0, -height / 2));+ var applied = BrepPlanarPathFeature.BuildOnBox(centered, size[0], size[1], height, grooves.Select(f => f.Feature).ToArray());+ if (!applied.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(applied.Diagnostics);+ host = FirmamentPrimitiveExecutionTranslation.TranslateBody(applied.Value.Body, new(0, 0, height / 2));+ foreach (var f in grooves) descendants.AddRange(applied.Value.Faces[f.Feature.Name].Select((face, i) => Descendant(stock.Name, f.Feature.Name, face, i)));+ }+ var support = TopSupport(host, height);+ var addition = FirmamentPrimitiveExecutionTranslation.TranslateBody(plan.Value.Addition!, new(0, 0, height));+ var attached = BrepPlanarAdditiveAttachment.Attach(host, addition, height, support);+ if (!attached.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(attached.Diagnostics);+ host = attached.Value.Body;+ foreach (var f in document.PathFeatures.Where(f => f.Feature.Add))+ {+ var faces = plan.Value.FaceOwners.Where(pair => pair.Value == f.Feature.Name && attached.Value.AddedFaceMap.ContainsKey(pair.Key))+ .Select(pair => attached.Value.AddedFaceMap[pair.Key]).Distinct().OrderBy(id => id.Value).ToArray();+ if (faces.Length == 0) return Fail(f.Feature.Name + ": rib is redundant or completely buried; no independent boundary survives. Remove it or adjust its guide/section.");+ descendants.AddRange(faces.Select((face, i) => Descendant(stock.Name, f.Feature.Name, face, i)));+ }+ }+ var supportPmi = ValidateV2PmiExportSupport(document); if (!supportPmi.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(supportPmi.Diagnostics);+ var spans = new Dictionary<string, FirmamentV2SourceSpan>(stockCorrespondence?.SourceSpans ?? new Dictionary<string, FirmamentV2SourceSpan>());+ foreach (var f in document.PathFeatures) spans[f.Host + "." + f.Feature.Name] = f.SourceSpan;+ var correspondence = new SemanticTopologyCorrespondence(stock.Name, descendants, ["UnifiedAst", "JudgmentEngine", plan.Value.Strategy, "ExactPlanarInterface"], spans);+ var pmi = BuildV2SemanticPmi(document, [], stock.Name, correspondence: correspondence, body: host);+ var exported = Step242Exporter.ExportBody(host, pmi, new Step242ExportOptions { BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute });+ if (!exported.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(exported.Diagnostics);+ return KernelResult<FirmamentStepExportResult>.Success(new(exported.Value, document.ModelName, 0, "path-feature", "AnalyticPathFeature")+ {+ RuntimeBody = host,+ RuntimeBodySourceName = stock.Name,+ RuntimeCorrespondence = correspondence,+ RibPlanning = plan.Value.Report,+ MaterializedFeatures = (builtStock?.Value.MaterializedFeatures ?? []).Concat(document.PathFeatures.Select(f => new FirmamentFeatureReceipt(f.Host, f.Feature.Add ? "Rib" : "Groove", f.Feature.Name))).ToArray(),+ Features = builtStock?.Value.Features,+ EngineeringFeatures = document.PathFeatures.Select(f => new FirmamentEngineeringFeatureReport(f.Feature.Name, f.Feature.Add ? "Rib" : "Groove", f.Host + "." + f.Feature.Name, f.Host, f.Support, f.GuideReference,+ f.Feature.Extent, f.Feature.Add ? "Height" : "Depth", f.Feature.Add ? "Add" : "Remove", PolicySource: "ManualConceptGuide", MaterializationRoute: plan.Value.Strategy, ToolFamily: f.Feature.Section.ToString())).ToArray()+ }, exported.Diagnostics);+ }+ private static SemanticTopologyDescendant Descendant(string host, string name, FaceId face, int ordinal) => new(host + "." + name + ".Face" + ordinal, "Face", SemanticTopologyRole.PathFeatureFace, host + "." + name,+ Face: face, ParentStableId: host, Addressability: SemanticTopologyAddressability.DerivedStable);+ private static FaceId TopSupport(BrepBody body, double height) => body.Topology.Faces.Where(f => body.Geometry.GetSurface(body.Bindings.GetFaceBinding(f.Id).SurfaceGeometryId).Plane is { } p+ && p.Normal.Z > .999 && Math.Abs(p.Origin.Z - height) < 1e-7).OrderByDescending(f => f.LoopIds.SelectMany(l => body.Topology.GetLoop(l).CoedgeIds).Count()).First().Id;+ private static ResolvedProfile2D HoleProfile(FirmamentV2SemanticHoleDecl hole)+ {+ var radius = (hole.CounterboreDiameter ?? hole.CountersinkDiameter ?? hole.ShaftDiameter) / 2;+ return new(hole.Name, "XY", [new("Outer",true,Enumerable.Range(0,4).Select(i=>new ResolvedProfileSegment2D("q"+i,+ new LineArcCircularArc2D((hole.Center.U,hole.Center.V),radius,i*Math.PI/2,Math.PI/2),new("hole:"+hole.Name,hole.Name,"source","HoleClearance","XY"))).ToArray())]);+ }+ private static bool Disjoint(ResolvedProfile2D a, ResolvedProfile2D b)+ {+ foreach (var first in a.Loops.SelectMany(l => l.Segments)) foreach (var second in b.Loops.SelectMany(l => l.Segments))+ { var hits = ProfileArrangementBuilder.IntersectBounded(first.Geometry, second.Geometry); if (hits.Intersections.Count > 0 || hits.HasBoundedOverlap) return false; }+ static (double X, double Y) Point(LineArcProfileCurve2D c) => c switch { LineArcLineSegment2D l => l.Start, LineArcCircularArc2D arc => (arc.Center.X + arc.Radius * Math.Cos(arc.StartAngleRadians), arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngleRadians)), _ => throw new NotSupportedException() };+ return ProfileArrangementBuilder.PointInProfile(a, Point(b.Loops[0].Segments[0].Geometry)) == ArrangementPointLocation.Outside+ && ProfileArrangementBuilder.PointInProfile(b, Point(a.Loops[0].Segments[0].Geometry)) == ArrangementPointLocation.Outside;+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.csindex 2cc78483..964c6d09 100644--- a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs+++ b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs@@ -56,6 +56,7 @@ public sealed record FirmamentStepExportResult(public FirmamentCirRetention? Cir { get; init; }public FirmamentMakerMarkReport? MakerMark { get; init; }public ProfileEdgeFinishEvidence? EdgeFinishPlanning { get; init; }+ public RibPlanningReport? RibPlanning { get; init; }}public sealed record FirmamentMakerMarkReport(string Content, double HeightMm, double DepthMm, int CounterCount);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.csindex fb481f96..8941f088 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs@@ -206,9 +206,11 @@ public static partial class FirmamentV2Parser{var stock = solids.Values.SingleOrDefault();if (stock is null || stock.Box is null && stock.Cylinder is null- || modifies.Any(m => m.SemanticHoles.Count > 0 || m.EdgeFinishes?.Count > 0 || m.Perforations?.Count > 0)+ || modifies.Any(m => m.Perforations?.Count > 0)|| declarations.Any(d => d.Type.Name.Text == "Thread"))- diagnostics.Add("firmament-path-feature-host: Use direct Box or Cylinder stock without Hole, EdgeFinish, Perforation or Thread operations.");+ diagnostics.Add("firmament-path-feature-host: Use direct Box or Cylinder stock without Perforation or Thread operations.");+ else if(stock.Cylinder is not null && modifies.Any(m=>m.SemanticHoles.Count>0||m.EdgeFinishes?.Count>0))+ diagnostics.Add("firmament-path-feature-host: Mixed holes/finishes currently require Box stock.");else if (stock.Box is not null && pathFeatures.Any(f => f.Support != "+Z") || stock.Cylinder is not null&& pathFeatures.Any(f => f.Feature.Add || f.Support is not ("OuterWall" or "InnerWall")|| f.Feature.Guide.Kind != Aetheris.Kernel.Core.Brep.Features.PlanarGuideKind.Circlediff --git a/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs b/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.csindex 83498a73..7296e6f4 100644--- a/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs+++ b/Aetheris.Kernel.Firmament/Materializer/ProfileArrangement2D.cs@@ -414,7 +414,7 @@ public static class ProfileArrangementBuilder.Select(x => x.Source.StableId).Distinct().OrderBy(x => x, StringComparer.Ordinal).ToArray()));}if (inner.Any(loop => !result.Any(region => PointInProfile(region.Outer, Ends(loop.Fragments[0].Geometry).Start) == ArrangementPointLocation.Inside)))- diagnostics.Add($"arrangement-rejected:inner-loop-not-nested:context={context}");+ diagnostics.Add($"arrangement-rejected:inner-loop-not-nested:context={context}:points={string.Join(";", inner.Select(loop => Ends(loop.Fragments[0].Geometry).Start))}");return result;}@@ -628,6 +628,12 @@ public static class ProfileArrangementBuilder: radialDistance < 0 ? ArrangementPointLocation.Inside : ArrangementPointLocation.Outside;}if (curves.Any(curve => OnCurve(curve, point, out _))) return ArrangementPointLocation.OnBoundary;+ // Shared arc/line endpoints can differ by roundoff. Choose a nearby ray+ // away from endpoint Y values only for mixed analytic loops, after the+ // boundary test. The shift stays below the classification tolerance.+ if (curves.Any(c => c is LineArcCircularArc2D)+ && curves.SelectMany(c => new[] { Ends(c).Start.Y, Ends(c).End.Y }).Any(y => Math.Abs(y - point.Y) <= Tol))+ point = (point.X, point.Y + Tol / 4);// A horizontal ray to +X; half-open endpoint ownership avoids ray-through-vertex double counting.var crossings = 0;foreach (var curve in curves)@@ -639,11 +645,23 @@ public static class ProfileArrangementBuilderreturn crossings % 2 == 1 ? ArrangementPointLocation.Inside : ArrangementPointLocation.Outside;}private static int RayLine((double X, double Y) p, LineArcLineSegment2D line)- { var a = line.Start; var b = line.End; if ((a.Y > p.Y) == (b.Y > p.Y)) return 0; var x = a.X + (p.Y - a.Y) * (b.X - a.X) / (b.Y - a.Y); return x > p.X + Tol ? 1 : 0; }+ {+ var a = line.Start; var b = line.End;+ if ((a.Y > p.Y) == (b.Y > p.Y)) return 0;+ var x = a.X + (p.Y - a.Y) * (b.X - a.X) / (b.Y - a.Y);+ return x > p.X + Tol ? 1 : 0;+ }private static int RayArc((double X, double Y) p, LineArcCircularArc2D arc){var dy = p.Y - arc.Center.Y; if (Math.Abs(dy) >= arc.Radius - Tol) return 0; var dx = Math.Sqrt(Math.Max(0d, arc.Radius * arc.Radius - dy * dy)); var count = 0;- foreach (var x in new[] { arc.Center.X - dx, arc.Center.X + dx }) if (x > p.X + Tol && OnCurve(arc, (x, p.Y), out var t) && t > Tol && t <= 1d + Tol) count++;+ foreach (var x in new[] { arc.Center.X - dx, arc.Center.X + dx })+ {+ if (x <= p.X + Tol || !OnCurve(arc, (x, p.Y), out var t)) continue;+ // Match RayLine's half-open Y ownership. Always excluding the start+ // and including the end miscounts a ray through an arc/line junction.+ var rising = arc.SweepAngleRadians * (x - arc.Center.X);+ if (t <= 1e-12 ? rising > 0 : t >= 1d - 1e-12 ? rising < 0 : true) count++;+ }return count;}private static string GeometryKey(LineArcProfileCurve2D curve)diff --git a/Aetheris.Kernel.Firmament/Materializer/RibNetworkPlanner.cs b/Aetheris.Kernel.Firmament/Materializer/RibNetworkPlanner.csnew file mode 100644index 00000000..7d2ea812--- /dev/null+++ b/Aetheris.Kernel.Firmament/Materializer/RibNetworkPlanner.cs@@ -0,0 +1,199 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Features;+using Aetheris.Kernel.Core.Judgment;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Results;+using Aetheris.Kernel.Core.Topology;+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament.Materializer;++public sealed record RibPlanningCandidate(string Name, bool Admitted, double Utility, string Reason);+public sealed record RibPlanningReport(string Strategy, IReadOnlyList<RibPlanningCandidate> Candidates,+ int CheckedEventIntervals, string ContactPolicy = "ExactPlanarInterface");+internal sealed record RibNetworkPlan(string Strategy, BrepBody? Addition,+ IReadOnlyDictionary<FaceId, string> FaceOwners, PathFeatureBody? Isolated, RibPlanningReport Report);++/// <summary>Choose a bounded representation, then let the existing planar+/// arrangement own intersections. There is no 3D Boolean search or source rewrite.</summary>+internal static class RibNetworkPlanner+{+ private sealed record Context(bool Isolated, bool Prismatic, bool Affine, int Count);+ internal static KernelResult<RibNetworkPlan> Plan(double x, double y, double z, IReadOnlyList<FirmamentV2PathFeature> declarations)+ {+ KernelResult<RibNetworkPlan> Fail(string message) => Failure<RibNetworkPlan>(message);+ var features = declarations.Select(d => d.Feature).ToArray();+ if (features.Select(f => f.Name).Distinct(StringComparer.Ordinal).Count() != features.Length) return Fail("duplicate feature names");+ foreach (var f in features)+ {+ var admitted = BrepPlanarPathFeature.ValidateFeature(f, z);+ if (!admitted.IsSuccess) return KernelResult<RibNetworkPlan>.Failure(admitted.Diagnostics);+ try+ {+ var bounds = Bounds(Profile(f, 0));+ if (bounds.MinX <= -x / 2 + 1e-7 || bounds.MaxX >= x / 2 - 1e-7 || bounds.MinY <= -y / 2 + 1e-7 || bounds.MaxY >= y / 2 - 1e-7)+ return Fail(f.Name + ": footprint leaves its Box support");+ }+ catch (ArgumentException e) { return Fail(f.Name + ": " + e.Message); }+ }+ var isolated = BrepPlanarPathFeature.BuildBox(x, y, z, features);+ var ribs = features.Where(f => f.Add).OrderBy(f => f.Name, StringComparer.Ordinal).ToArray();+ var context = new Context(isolated?.IsSuccess == true,+ ribs.Length > 0 && ribs.All(f => f.DraftDegrees == 0),+ ribs.Length > 0 && ribs.All(f => f.Guide.Kind == PlanarGuideKind.Line && !f.RoundEnds && Math.Abs(f.Extent - ribs[0].Extent) < 1e-8), ribs.Length);+ JudgmentCandidate<Context>[] candidates = [+ new("ExistingAnalyticPatch",c=>c.Isolated,_=>1,_=>"Feature envelopes interact; an arrangement is required.",0),+ new("PrismaticSectionArrangement",c=>c.Prismatic,c=>Utility.Weighted((1,.8),(1/(1+c.Count/64d),.2)),_=>"Connected constant-section networks require zero side draft.",1),+ new("AffineDraftArrangement",c=>c.Affine,c=>Utility.Weighted((.9,.8),(1/(1+c.Count/64d),.2)),_=>"Drafted junctions require Flat-ended straight ribs of one common height.",2)];+ var decision = new JudgmentEngine<Context>().Evaluate(context, candidates);+ var evidence = candidates.Select(c => new RibPlanningCandidate(c.Name, c.IsAdmissible(context), c.IsAdmissible(context) ? c.Score(context) : 0,+ c.IsAdmissible(context) ? "Eligible bounded construction." : c.RejectionReason!(context))).ToArray();+ if (!decision.IsSuccess) return Fail("no admitted rib plan: " + string.Join("; ", evidence.Select(e => e.Name + ": " + e.Reason)));+ var strategy = decision.Selection!.Value.Candidate.Name;+ if (strategy == "ExistingAnalyticPatch") return KernelResult<RibNetworkPlan>.Success(new(strategy, null, new Dictionary<FaceId, string>(), isolated!.Value, new(strategy, evidence, 0)));+ if (strategy == "PrismaticSectionArrangement")+ {+ var profiles = ribs.ToDictionary(f => f.Name, f => Profile(f, 0), StringComparer.Ordinal);+ var dummy = "__attachment_base"; while (profiles.ContainsKey(dummy)) dummy += "_";+ profiles[dummy] = Rectangle(dummy, x, y);+ var operations = new List<PrismaticProfileOperation> { new(dummy, PrismaticProfileIntent.Base, dummy, -1, 0, "AttachmentBase", "generated:attachment") };+ operations.AddRange(ribs.Select(f => new PrismaticProfileOperation(f.Name, PrismaticProfileIntent.Add, f.Name, 0, f.Extent, "Rib", "feature:" + f.Name)));+ var feature = new PrismaticProfileCompositionFeature("RibNetwork", "XY", "+Z", new("WorldXY", 0, 0, 0, "XY", "+Z", "+X", false), operations,+ operations.SelectMany(o => new[] { o.From, o.To }).Distinct().Order().ToArray(), "ManualRibArrangement");+ var stack = PrismaticSectionStackCompiler.Normalize(new(feature, profiles, []), out var errors);+ if (stack is null) return Fail(string.Join("; ", errors));+ var emitted = PrismaticSectionStackEmitter.Emit(stack);+ if (emitted.Body is null) return Fail(string.Join("; ", emitted.Diagnostics));+ var faceOwners = new Dictionary<FaceId, string>();+ foreach (var descendant in emitted.Correspondence?.Descendants ?? [])+ if (descendant.Face is { } face)+ {+ var owner = ribs.FirstOrDefault(r => descendant.SourceStableId.StartsWith("profile:" + r.Name + ".", StringComparison.Ordinal));+ if (owner is not null) faceOwners[face] = owner.Name;+ }+ return KernelResult<RibNetworkPlan>.Success(new(strategy, emitted.Body, faceOwners, null, new(strategy, evidence, stack.Slabs.Count)));+ }+ var h = ribs[0].Extent; var lower = Arrange(ribs, 0); var upper = Arrange(ribs, h);+ if (lower.Arrangement.Diagnostics.Any(d => d.StartsWith("arrangement-rejected", StringComparison.Ordinal))+ || upper.Arrangement.Diagnostics.Any(d => d.StartsWith("arrangement-rejected", StringComparison.Ordinal)))+ return Fail(string.Join("; ", lower.Arrangement.Diagnostics.Concat(upper.Arrangement.Diagnostics)));+ var lo = Canonical(lower.Arrangement); var hi = Canonical(upper.Arrangement);+ if (!lo.Keys.Order().SequenceEqual(hi.Keys.Order())) return Fail("draft changes junction topology between the base and top; reduce height/draft or adjust the guides");+ var stations = EventStations(ribs, h); var intervals = 0;+ foreach (var pair in stations.Zip(stations.Skip(1)))+ {+ var station = (pair.First + pair.Second) / 2; var section = Arrange(ribs, station);+ if (section.Arrangement.Diagnostics.Any(d => d.StartsWith("arrangement-rejected", StringComparison.Ordinal))) return Fail("unqualified junction at height " + station + ": " + string.Join("; ", section.Arrangement.Diagnostics));+ var actual = Canonical(section.Arrangement);+ if (!lo.Keys.Order().SequenceEqual(actual.Keys.Order())) return Fail("draft crosses a junction event near height " + station);+ foreach (var key in lo.Keys)+ for (var i = 0; i < lo[key].Length; i++)+ {+ var a = ((LineArcLineSegment2D)lo[key][i].Geometry).Start; var b = ((LineArcLineSegment2D)hi[key][i].Geometry).Start;+ var p = ((LineArcLineSegment2D)actual[key][i].Geometry).Start; var t = station / h;+ if (Math.Abs(p.X - (a.X + (b.X - a.X) * t)) + Math.Abs(p.Y - (a.Y + (b.Y - a.Y) * t)) > 1e-6)+ return Fail("a drafted boundary changes its supporting planes near height " + station);+ }+ intervals++;+ }+ var regions = new List<RibLoftRegion>();+ foreach (var outer in lower.Arrangement.ResultLoops.Where(l => l.IsOuter))+ {+ var exterior = LoopProfile(outer);+ var loops = new[] { outer }.Concat(lower.Arrangement.ResultLoops.Where(l => !l.IsOuter+ && ProfileArrangementBuilder.PointInProfile(exterior, ((LineArcLineSegment2D)l.Fragments[0].Geometry).Start) == ArrangementPointLocation.Inside)).ToArray();+ regions.Add(new(loops.Select(l =>+ {+ var key = Key(l); var a = lo[key]; var b = hi[key];+ return new RibLoftLoop(a.Select(f => { var p = ((LineArcLineSegment2D)f.Geometry).Start; return new ProfilePoint2D(p.X, p.Y); }).ToArray(),+ b.Select(f => { var p = ((LineArcLineSegment2D)f.Geometry).Start; return new ProfilePoint2D(p.X, p.Y); }).ToArray(), a.Select(f => f.Source.Operation).ToArray());+ }).ToArray()));+ }+ var loft = BrepRuledRibNetwork.Build(regions, h);+ return loft.IsSuccess ? KernelResult<RibNetworkPlan>.Success(new(strategy, loft.Value.Body, loft.Value.SideOwners, null, new(strategy, evidence, intervals)))+ : KernelResult<RibNetworkPlan>.Failure(loft.Diagnostics);+ }++ internal static ResolvedProfile2D Profile(PlanarPathFeature feature, double z)+ {+ var loops = BrepPlanarPathFeature.Footprint(feature, z);+ return new(feature.Name, "XY", loops.Select((loop, k) => new ResolvedProfileLoop2D(k == 0 ? "Outer" : "Inner" + k, k == 0,+ // Section-arrangement source holes use CCW orientation.+ (k == 0 ? loop : loop.Reverse().Select(Reverse).ToArray()).Select((e, i) => new ResolvedProfileSegment2D("Side" + i,+ Curve(e), new("profile:" + feature.Name + "." + (k == 0 ? "Outer" : "Inner" + k) + ".Side" + i, "guide:" + feature.Name, "feature:" + feature.Name, "RibFootprint", "XY"))).ToArray())).ToArray());+ }+ private static PlanarBandSpan Reverse(PlanarBandSpan e) => e with { Start = e.End, End = e.Start, StartAngle = e.StartAngle + e.Sweep, Sweep = -e.Sweep };+ private static LineArcProfileCurve2D Curve(PlanarBandSpan e) => e.Radius == 0 ? new LineArcLineSegment2D((e.Start.X, e.Start.Y), (e.End.X, e.End.Y))+ : new LineArcCircularArc2D((e.Center.X, e.Center.Y), e.Radius, e.StartAngle, e.Sweep);+ private static ResolvedProfile2D Rectangle(string name, double x, double y)+ {+ (double X, double Y)[] p = [(-x / 2, -y / 2), (x / 2, -y / 2), (x / 2, y / 2), (-x / 2, y / 2)];+ return new(name, "XY", [new("Outer",true,p.Select((a,i)=>new ResolvedProfileSegment2D("Side"+i,new LineArcLineSegment2D(a,p[(i+1)%4]),+ new("profile:"+name+".Outer.Side"+i,name,"generated","AttachmentBase","XY"))).ToArray())]);+ }+ internal static (double MinX, double MinY, double MaxX, double MaxY) Bounds(ResolvedProfile2D profile)+ {+ var points = profile.Loops.SelectMany(l => l.Segments).SelectMany(s => Extrema(s.Geometry)).ToArray();+ return (points.Min(p => p.X), points.Min(p => p.Y), points.Max(p => p.X), points.Max(p => p.Y));+ }+ private static IEnumerable<(double X, double Y)> Extrema(LineArcProfileCurve2D curve)+ {+ if (curve is LineArcLineSegment2D l) { yield return l.Start; yield return l.End; yield break; }+ var a = (LineArcCircularArc2D)curve; var from = Math.Min(a.StartAngleRadians, a.StartAngleRadians + a.SweepAngleRadians); var to = Math.Max(a.StartAngleRadians, a.StartAngleRadians + a.SweepAngleRadians);+ yield return (a.Center.X + a.Radius * Math.Cos(from), a.Center.Y + a.Radius * Math.Sin(from)); yield return (a.Center.X + a.Radius * Math.Cos(to), a.Center.Y + a.Radius * Math.Sin(to));+ for (var i = Math.Ceiling(from / (Math.PI / 2)); i <= Math.Floor(to / (Math.PI / 2)); i++) yield return (a.Center.X + a.Radius * Math.Cos(i * Math.PI / 2), a.Center.Y + a.Radius * Math.Sin(i * Math.PI / 2));+ }+ private static ProfileArrangementResult Arrange(IReadOnlyList<PlanarPathFeature> ribs, double z)+ {+ var profiles = ribs.ToDictionary(r => r.Name, r => Profile(r, z), StringComparer.Ordinal);+ return ProfileArrangementBuilder.Compose("XY", ribs.Select(r => new PrismaticProfileOperation(r.Name, PrismaticProfileIntent.Add, r.Name, 0, r.Extent, "Rib", "feature:" + r.Name)).ToArray(), profiles, "RibNetwork@" + z.ToString("R", System.Globalization.CultureInfo.InvariantCulture));+ }+ private static ResolvedProfile2D LoopProfile(ArrangementLoop2D loop) => new("loop", "XY", [new("Outer", true, loop.Fragments.Select((f, i) => new ResolvedProfileSegment2D("s" + i, f.Geometry, f.Source.Provenance)).ToArray())]);+ private static ArrangementFragment2D[] Rotate(ArrangementLoop2D loop)+ {+ var f = loop.Fragments; var starts = Enumerable.Range(0, f.Count).OrderBy(i => string.Join("|", Enumerable.Range(0, f.Count).Select(j => f[(i + j) % f.Count].Source.StableId)), StringComparer.Ordinal).ToArray();+ return Enumerable.Range(0, f.Count).Select(j => f[(starts[0] + j) % f.Count]).ToArray();+ }+ private static string Key(ArrangementLoop2D loop) => (loop.IsOuter ? "outer:" : "inner:") + string.Join("|", Rotate(loop).Select(f => f.Source.StableId));+ private static Dictionary<string, ArrangementFragment2D[]> Canonical(ProfileArrangement2D arrangement) => arrangement.ResultLoops.ToDictionary(Key, Rotate, StringComparer.Ordinal);++ // All section supports are n.x = c0+c1*z. Their pair/triple coincidences+ // enumerate every height at which the finite polygon arrangement can change.+ private static double[] EventStations(IReadOnlyList<PlanarPathFeature> ribs, double h)+ {+ var planes = new List<(double X, double Y, double C, double Rate)>();+ foreach (var r in ribs)+ {+ var a = Profile(r, 0).Loops[0].Segments; var b = Profile(r, h).Loops[0].Segments;+ for (var i = 0; i < a.Count; i++)+ {+ var l = (LineArcLineSegment2D)a[i].Geometry; var u = (LineArcLineSegment2D)b[i].Geometry;+ var dx = l.End.X - l.Start.X; var dy = l.End.Y - l.Start.Y; var length = Math.Sqrt(dx * dx + dy * dy);+ var nx = dy / length; var ny = -dx / length; var c = nx * l.Start.X + ny * l.Start.Y;+ planes.Add((nx, ny, c, (nx * u.Start.X + ny * u.Start.Y - c) / h));+ }+ }+ var values = new List<double> { 0, h };+ void Add(double z) { if (double.IsFinite(z) && z > 1e-7 && z < h - 1e-7) values.Add(z); }+ for (var i = 0; i < planes.Count; i++) for (var j = i + 1; j < planes.Count; j++)+ {+ var a = planes[i]; var b = planes[j]; var det = a.X * b.Y - a.Y * b.X;+ if (Math.Abs(det) < 1e-10)+ {+ var sign = a.X * b.X + a.Y * b.Y >= 0 ? 1d : -1d; var rate = a.Rate - sign * b.Rate;+ if (Math.Abs(rate) > 1e-12) Add((sign * b.C - a.C) / rate);+ continue;+ }+ var x = (a.C * b.Y - a.Y * b.C) / det; var y = (a.X * b.C - a.C * b.X) / det;+ var vx = (a.Rate * b.Y - a.Y * b.Rate) / det; var vy = (a.X * b.Rate - a.Rate * b.X) / det;+ for (var k = j + 1; k < planes.Count; k++)+ {+ var c = planes[k]; var rate = c.X * vx + c.Y * vy - c.Rate;+ if (Math.Abs(rate) > 1e-12) Add((c.C - c.X * x - c.Y * y) / rate);+ }+ }+ return values.Order().Aggregate(new List<double>(), (list, value) => { if (list.Count == 0 || value - list[^1] > 1e-7) list.Add(value); return list; }).ToArray();+ }+ internal static KernelResult<T> Failure<T>(string message) => KernelResult<T>.Failure([+ new(Core.Diagnostics.KernelDiagnosticCode.ValidationFailed,Core.Diagnostics.KernelDiagnosticSeverity.Error,"rib-network-rejected: "+message,"Firmament.RibNetwork")]);+}diff --git a/docs/development/reports/2026-10/rib-junctions-and-mixed-features.md b/docs/development/reports/2026-10/rib-junctions-and-mixed-features.mdnew file mode 100644index 00000000..85026a8e--- /dev/null+++ b/docs/development/reports/2026-10/rib-junctions-and-mixed-features.md@@ -0,0 +1,117 @@+# Manual rib junctions and mixed stock features++Date: 2026-10-27++## Change++Manual `Rib<Rectangular>` features on direct Box top supports now form integrated+T/L/X and closed-loop junction networks. Zero-draft line/arc/circle networks+support unequal heights; drafted networks admit Flat-ended straight ribs of a+common height when exact affine boundary correspondence survives all section+events. Separate groove footprints may share the stock. Top-entry ThroughAll+shaft/counterbore/countersink holes and one top perimeter Fillet/Chamfer reuse the+existing engineering feature owners. Their clearance is proved before attachment.++`reinforced-mounting-plate.firmament` is the motivating production fixture: an+80 � 60 � 6 mm plate, crossing 4 mm ribs, 12 mm height and 2� side draft, two+stepped through holes, and a 1.2 mm top perimeter fillet.++## Ownership and planning++JudgmentEngine chooses among three bounded representations, recording eligibility,+utility and rejection reasons in build JSON `ribPlanning`:++- ExistingAnalyticPatch: preferred for previously admitted isolated geometry.+- PrismaticSectionArrangement: the shared profile arrangement/section-stack owners+ construct zero-draft networks at their exact height transitions.+- AffineDraftArrangement: shared 2D arrangements establish bottom/top boundary+ correspondence; pair/triple support-plane coincidences enumerate potential+ topology events. Every open event interval is checked before exact planar lofting.++A construction-owned planar interface attaches the additive boundary to the+existing stock. Auxiliary section-stack base material is discarded. Exact cap+roles distinguish the outer attachment from support islands; loop traversal is+not substituted for the section owner's explicit hole semantics. All retained+stock entity IDs, curves, surfaces and feature correspondence survive attachment.+There is no general 3D Boolean, mesh union, parser route, or source rewrite.++Additional CLI probes exposed an old composite-hole limit when stepped holes+were used without a perimeter finish. The existing combined stock builder now+has an explicit `None` finish, with no degenerate rim faces or fabricated finish+receipt. Manual features reuse this stock plan with or without a real finish;+previous standalone hole routes remain unchanged. Isolated and joined variants+are covered, with both counterbore and countersink present.++Qualification exposed and repaired two local issues: adding an explicit inner+boundary requires completing the original support's boundary-role evidence; and+line/arc ray endpoint ownership must use the same half-open Y convention,+including endpoint roundoff. The first full run caught a maker-mark polygon+regression from applying endpoint tolerance too broadly. The final correction+leaves polygon-only classification unchanged and disambiguates arc-containing+rays within the existing classification tolerance. Both engraving regressions+pass in the focused rerun. Strict export/import checks were retained. Importer+inner-overlap failures now identify the implicated loop IDs.++## Evidence++- Actual CLI validate: valid, Built, UnifiedMechanical.+- Actual CLI build: AffineDraftArrangement, five materialized feature receipts.+- STEP reimport/wireframe: 28 faces, 67 edges; 20 planes, seven cylinders, one cone.+ All 134 pcurves qualify; maximum reported residual 0.000000435 mm.+- Focused tests cover X/T/L junctions, unequal heights, drafted junctions, a crossed+ circular rib with support islands, noninteracting semicircular removal, all three+ hole variants with both perimeter finish kinds, redundant/collapsed intent,+ validate/build refusal agreement, exact isolated-geometry parity, and exact STEP+ and stable-name equality under junction declaration reordering.+- All six previous manual-rib/groove CLI STEP artifacts are byte-for-byte+ identical after rebuilding: manual-rib, arc-rib, plate-channels,+ plate-seal-groove, shaft-seal-groove and bore-seal-groove. SHA-256 comparisons+ are in `artifacts/local/rib-junctions/geometry-parity.json`; original files in+ `artifacts/local/path-features/` were retained. No baseline was refreshed.+- Four extra real CLI probes pass for isolated-hole, isolated-fillet,+ network-chamfer and network-hole combinations (`mixed-smoke.json`).++Generated evidence lives under ignored `artifacts/local/rib-junctions/`:+`validate.json`, `build.json`, `reinforced-mounting-plate.step`,+`reinforced-mounting-plate.svg` and its browser-rendered PNG. The preview is drawn+from the exported/reimported BRep by the CLI wireframe renderer.++Focused rerun: 43 passed, including the historical maker-mark witnesses.+Complete qualification:++- Release solution build: zero errors (existing analyzer/platform warnings).+- Fast Core lane: 1,164 passed, zero failed.+- Full solution lane: 6,298 passed, zero failed, two optional external PDF-renderer+ skips, twenty test assemblies. Full Core: 1,351 passed; Firmament: 3,341 passed.+ The FrictionLab support assembly contains no discoverable tests.+- Managed/WASM development SDK rebuilt; all nineteen JavaScript SDK tests passed.+- `git diff --check` passed. Task-owned .NET/test hosts exited; no persistent+ services or startup hooks were introduced.++Logs: `artifacts/local/rib-full-build.log`, `rib-fast.log`,+`rib-full-tests.log`, `rib-network-focused.log`, `rib-sdk-build.log`,+`rib-sdk-tests.log`. The initial superseded run remains as+`rib-full-tests-initial.log` for the regression evidence.++## Deliberate limits++Hosts remain direct Box +Z supports. Imported/Compose/other-face supports,+compound guides, arbitrary sections, intersecting removal features, holes through+ribs, varying-height drafted junctions, and topology-changing taper reject.+Groove-only arrangements retain the isolated builder's conservative envelope rule.+Completely buried named ribs reject instead of receiving imaginary independent+face identities. Junction face numbering is deterministic under declaration+reordering; topology changes do not promise persistent individual face numbers.++No AutoRib policy, base blending, mold-release certification, or composite-body+SDF/authoritative volume assertion capability is added. Numerical mass checks in+tests are independent qualification witnesses rather than a new assertion authority.++## Verdict++**Success within the documented manual Box-top boundary.** Useful manually+reinforced parts now combine qualified rib junctions, through-hole stacks,+perimeter finishes and separate grooves without changing the six previously+qualified STEP artifacts. Exact construction, source correspondence and strict+interchange checks remain authoritative. The full gate passed; AutoRib can be+considered separately against this manual construction foundation.diff --git a/docs/public/firmament/grooves-and-ribs.md b/docs/public/firmament/grooves-and-ribs.mdindex e896f0ab..3fcfea17 100644--- a/docs/public/firmament/grooves-and-ribs.md+++ b/docs/public/firmament/grooves-and-ribs.md@@ -52,6 +52,29 @@ ends. Overall length is guide length plus thickness at the relevant height.An [arc rib](../../../fixtures/Canonical/Features/PathFeatures/arc-rib.firmament)uses exact conical sides when drafted.+## Rib junctions and mixed features++Separate named ribs may meet as T, L or X junctions. Their footprints are+united into one material boundary; internal overlapping walls are removed.+Zero-draft line, arc and circular ribs may have different heights. Drafted+junctions currently require straight Flat-ended ribs of one common height.+The compiler proves the boundary stays affine through every possible section+event; topology-changing taper rejects rather than emitting an approximate loft.++The complete [reinforced mounting plate](../../../fixtures/Canonical/Features/PathFeatures/reinforced-mounting-plate.firmament)+combines two crossing drafted ribs, counterbored and countersunk through holes,+and a top perimeter fillet. Top-entry `ThroughAll` holes and one `+Z` perimeter+Fillet or Chamfer reuse the ordinary stock feature builders. Rib and groove+footprints must clear the holes' largest entry diameter and the perimeter finish.+The holes do not require a perimeter finish. Noninteracting grooves may share the same stock. A hole crossing a rib, or a+groove crossing another path feature, is explicitly rejected.++Build JSON exposes `ribPlanning`: the selected construction, candidate admission+and utility, and checked section intervals. Existing isolated constructions are+preferred to preserve their geometry. A completely buried/redundant named rib+is rejected because no independent feature boundary survives. Feature order does+not change a junction network's generated geometry or semantic names.+## Plate channels and circular face grooves[plate-channels.firmament](../../../fixtures/Canonical/Features/PathFeatures/plate-channels.firmament)@@ -117,13 +140,14 @@ requirements; a groove is not an automatic seal-design approval.top-open `Cylinder<Hollow>`, with no bottom blend. Cylindrical ribs,axial/helical cylinder channels and arbitrary surface paths reject.- Open arcs require Flat ends and a positive sweep of at most 180 degrees.- Compound Paths, corners, branch networks and arbitrary sections reject.-- Planar footprints must remain strictly inside the support. Multiple features- require disjoint XY bounding boxes, a conservative admission rule: some- nonintersecting nested or diagonal arrangements are therefore rejected too.+ Compound Paths and arbitrary sections reject; junctions use separate named ribs.+- Planar footprints must remain strictly inside the support. Rib networks use+ exact line/arc arrangements. Grooves remain separate; their interactions reject.+ Groove-only sets retain conservative disjoint XY envelope admission.Cylindrical groove axial envelopes must be disjoint.-- Combining these features with Hole, EdgeFinish, Perforation or Thread in the- same body is not yet admitted. No requested operation is silently dropped.+- Box ribs/channels may combine with the bounded holes and perimeter finish+ described above. Perforation, Thread and mixed cylindrical-groove operations+ remain unsupported. No requested operation is silently dropped.- A rib top may not collapse under draft; a groove must leave positive material.No base fillet, molding-release certification or automatic rib placement isimplied. Existing PlasticShell AutoRib retains its separate qualified limits.diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.mdindex 916a35fd..50e6d2ff 100644--- a/docs/public/firmament/syntax.md+++ b/docs/public/firmament/syntax.md@@ -40,5 +40,5 @@ Model Plate {| Interfaces, mates, datums, motion | [Assemblies and motion](../reference/language/assemblies-and-motion.md) || `Assert`, `measure`, stack-ups | [Checks and measurement](../reference/language/checks.md) || Explicit GD&T, datum precedence, metric PMI passthrough | [Semantic PMI](pmi.md) |-| Named channels, seal grooves and drafted manual ribs | [Grooves and ribs](grooves-and-ribs.md) |+| Named channels, seal grooves, rib junctions and mixed stock features | [Grooves and ribs](grooves-and-ribs.md) || Older V1 forms | [Reading older source](../reference/language/compatibility.md) |diff --git a/docs/public/reference/language/solids-and-features.md b/docs/public/reference/language/solids-and-features.mdindex 179e7516..f8a4e11f 100644--- a/docs/public/reference/language/solids-and-features.md+++ b/docs/public/reference/language/solids-and-features.md@@ -214,3 +214,6 @@ looks plausible is never evidence that everything you asked for was built.is never promoted to a complete hole. `importTolerance` controls how importedgeometry is qualified and has nothing to do with a manufacturing `tol`. See[imported through-hole revisions](../../firmament/imported-feature-recognition.md).++Manual rib junctions and their admitted combinations with holes and perimeter+finishes are described in [Grooves and ribs](../../firmament/grooves-and-ribs.md#rib-junctions-and-mixed-features).diff --git a/fixtures/Canonical/Features/PathFeatures/reinforced-mounting-plate.firmament b/fixtures/Canonical/Features/PathFeatures/reinforced-mounting-plate.firmamentnew file mode 100644index 00000000..2272cefd--- /dev/null+++ b/fixtures/Canonical/Features/PathFeatures/reinforced-mounting-plate.firmament@@ -0,0 +1,19 @@+Model ReinforcedMountingPlate {+ units: mm+ Box Plate { size: [80mm, 60mm, 6mm] }+ Path Across { start: Point2(-25mm, 0mm); heading: 0deg; Line RunX { length: 50mm } }+ Path Along { start: Point2(0mm, -18mm); heading: 90deg; Line RunY { length: 36mm } }+ Modify Plate {+ Rib<Rectangular> CrossWeb { on: +Z; path: Across; thickness: 4mm; height: 12mm; draft: 2deg }+ Rib<Rectangular> LongWeb { on: +Z; path: Along; thickness: 4mm; height: 12mm; draft: 2deg }+ Hole<Counterbore> MountA {+ on: +Z; center: [-30mm, -20mm]; diameter: 5mm; end: ThroughAll+ counterboreDiameter: 8mm; counterboreDepth: 2mm+ }+ Hole<Countersink> MountB {+ on: +Z; center: [30mm, 20mm]; diameter: 5mm; end: ThroughAll+ countersinkDiameter: 9mm; countersinkAngle: 90deg+ }+ EdgeFinish Rim { face: +Z; target: Boundary; kind: Fillet; radius: 1.2mm }+ }+}