Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Expose sheet-metal metrics and wire knot-path details
Yuechen Li47583c5a50c3
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 96c3783b..c3d25c8c 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -874,10 +874,10 @@ public static class CliRunner? Regex.Matches(source,"(DRAUGHTING_MODEL|GEOMETRIC_TOLERANCE|DATUM_FEATURE|ANNOTATION_OCCURRENCE|SHAPE_ASPECT)",RegexOptions.IgnoreCase).Count: authoredSpec.Manufacturing.Datums.Count+authoredSpec.Manufacturing.Dimensions.Count+authoredSpec.Manufacturing.GeometricTolerances.Count+authoredSpec.Manufacturing.Annotations.Count;var exactValidation=flat.ExactBlankContour is null?null:PlanarContourKernel.Validate(flat.ExactBlankContour);- var report=new{command=$"sheetmetal {operation}",success=true,input,sourceAuthority=SheetMetalFirmament.LooksLikeSheetMetal(source)?(source.Contains("Intent: Reconstructed",StringComparison.OrdinalIgnoreCase)?"Firmament reconstructed engineering authority":source.Contains("RecoveredRegion",StringComparison.Ordinal)?"Firmament recovered sheet-metal semantics":"Firmament authored semantics"):"STEP formed BRep (not mutated)",recognitionStatus=part.RecognitionStatus,material=new{authored=part.Material,manufacturingSpecification=authoredSpec?.Manufacturing.MaterialSpecification},thickness=new{nominal=part.Thickness,tolerance=authoredSpec?.Manufacturing.ThicknessTolerancePlus??thickness?.Tolerance,evidencePairs=thickness?.SourcePairs.Count(p=>p.Admitted)??0,outlierFaces=thickness?.OutlierFaceIds.Count??0},geometry=new{bodies=body?.Topology.Bodies.Count()??0,shells=body?.Topology.Shells.Count()??0,faces=body?.Topology.Faces.Count()??0,edges=body?.Topology.Edges.Count()??0,vertices=body?.Topology.Vertices.Count()??0,supportFamilies,pmiIndicators},manufacturing=authoredSpec?.Manufacturing,sheetMetal=new{baseRegion=part.BaseRegionId,regions=part.Regions.Select(r=>new{r.StableId,r.Kind,r.ApproximateArea,sourceFaces=r.Source.FaceIds}),attachmentPaths=(part.AttachmentPaths??[]).Select(p=>new{p.StableId,p.OwningRegionId,p.CarrierPath,p.Inset,length=(p.End-p.Start).Length,p.SpanOffset,p.Start,p.End,p.Tangent,p.InPlaneNormal,p.RegionNormal,p.Capabilities}),bends=part.Bends.Select(b=>new{b.StableId,b.AxisOrigin,b.AxisDirection,angleDegrees=b.BendAngleRadians*180/Math.PI,b.InsideRadius,b.Direction,b.AdjacentRegionA,b.AdjacentRegionB,sourceFaces=b.Source.FaceIds}),cuts=part.Features.Select(f=>new{f.StableId,f.Kind,f.OwningRegionId,f.Diameter,sourceFaces=f.Source.FaceIds}),reliefs=part.Reliefs?.Count??0,semanticLayout=authoredSpec?.SemanticLayout,conceptPaths,templateInstantiations},flatPattern=new{flat.Status,flat.Bounds,bendLines=flat.BendLines.Count,cuts=flat.CutLoops.Count,reliefs=flat.ReliefLoops?.Count??0,exactBlank=flat.ExactBlankContour is not null,outerLoops=flat.ExactBlankContour is null?0:1,innerLoops=flat.ExactBlankContour?.InnerLoops.Count??0,connectedMaterialRegions=flat.ExactBlankContour is null?0:1,selfIntersects=exactValidation?.Diagnostics.Any(x=>x.Code=="planar-contour-self-intersection")??false,exactContoursValid=exactValidation?.IsValid??false,fallbackUsed=authoredSpec is not null&&flat.ExactBlankContour is null,kFactor=flat.Policy.KFactor,flat.DeterministicHash,svg=output,step=flatStepOutput,firmament=firmamentOutput},dfm=new{dfm.Overall,findings=dfm.Findings},diagnostics=allDiagnostics,timingsMilliseconds=new{parse=authoredTimings?.ParseMilliseconds,semanticResolve=authoredTimings?.SemanticResolveMilliseconds,formedLower=authoredTimings?.FormedLowerMilliseconds,authoredFlatLower=authoredTimings?.FlatLowerMilliseconds,import=importTime.TotalMilliseconds,recognition=recognitionTime.TotalMilliseconds,flatten=flattenClock.Elapsed.TotalMilliseconds}};+ var report=new{command=$"sheetmetal {operation}",success=true,input,sourceAuthority=SheetMetalFirmament.LooksLikeSheetMetal(source)?(source.Contains("Intent: Reconstructed",StringComparison.OrdinalIgnoreCase)?"Firmament reconstructed engineering authority":source.Contains("RecoveredRegion",StringComparison.Ordinal)?"Firmament recovered sheet-metal semantics":"Firmament authored semantics"):"STEP formed BRep (not mutated)",recognitionStatus=part.RecognitionStatus,material=new{authored=part.Material,manufacturingSpecification=authoredSpec?.Manufacturing.MaterialSpecification},thickness=new{nominal=part.Thickness,tolerance=authoredSpec?.Manufacturing.ThicknessTolerancePlus??thickness?.Tolerance,evidencePairs=thickness?.SourcePairs.Count(p=>p.Admitted)??0,outlierFaces=thickness?.OutlierFaceIds.Count??0},geometry=new{bodies=body?.Topology.Bodies.Count()??0,shells=body?.Topology.Shells.Count()??0,faces=body?.Topology.Faces.Count()??0,edges=body?.Topology.Edges.Count()??0,vertices=body?.Topology.Vertices.Count()??0,supportFamilies,pmiIndicators},manufacturing=authoredSpec?.Manufacturing,sheetMetal=new{baseRegion=part.BaseRegionId,regions=part.Regions.Select(r=>new{r.StableId,r.Kind,r.ApproximateArea,sourceFaces=r.Source.FaceIds}),attachmentPaths=(part.AttachmentPaths??[]).Select(p=>new{p.StableId,p.OwningRegionId,p.CarrierPath,p.Inset,length=(p.End-p.Start).Length,p.SpanOffset,p.Start,p.End,p.Tangent,p.InPlaneNormal,p.RegionNormal,p.Capabilities}),bends=part.Bends.Select(b=>new{b.StableId,b.AxisOrigin,b.AxisDirection,angleDegrees=b.BendAngleRadians*180/Math.PI,b.InsideRadius,b.Direction,b.AdjacentRegionA,b.AdjacentRegionB,sourceFaces=b.Source.FaceIds}),cuts=part.Features.Select(f=>new{f.StableId,f.Kind,f.OwningRegionId,f.Diameter,sourceFaces=f.Source.FaceIds}),reliefs=part.Reliefs?.Count??0,semanticLayout=authoredSpec?.SemanticLayout,conceptPaths,templateInstantiations},flatPattern=new{flat.Status,MaterialArea=flat.MaterialArea,BoundingArea=flat.BoundingArea,flat.Bounds,bendLines=flat.BendLines.Count,cuts=flat.CutLoops.Count,reliefs=flat.ReliefLoops?.Count??0,exactBlank=flat.ExactBlankContour is not null,outerLoops=flat.ExactBlankContour is null?0:1,innerLoops=flat.ExactBlankContour?.InnerLoops.Count??0,connectedMaterialRegions=flat.ExactBlankContour is null?0:1,selfIntersects=exactValidation?.Diagnostics.Any(x=>x.Code=="planar-contour-self-intersection")??false,exactContoursValid=exactValidation?.IsValid??false,fallbackUsed=authoredSpec is not null&&flat.ExactBlankContour is null,kFactor=flat.Policy.KFactor,flat.DeterministicHash,svg=output,step=flatStepOutput,firmament=firmamentOutput},dfm=new{dfm.Overall,findings=dfm.Findings},diagnostics=allDiagnostics,timingsMilliseconds=new{parse=authoredTimings?.ParseMilliseconds,semanticResolve=authoredTimings?.SemanticResolveMilliseconds,formedLower=authoredTimings?.FormedLowerMilliseconds,authoredFlatLower=authoredTimings?.FlatLowerMilliseconds,import=importTime.TotalMilliseconds,recognition=recognitionTime.TotalMilliseconds,flatten=flattenClock.Elapsed.TotalMilliseconds}};if(json)stdout.WriteLine(JsonSerializer.Serialize(report,JsonOptions));else{- stdout.WriteLine($"Sheet Metal: {part.RecognitionStatus} ({report.sourceAuthority})");if(part.Material is not null)stdout.WriteLine($"Material: {part.Material}");stdout.WriteLine($"Thickness: {part.Thickness:G8} mm{(thickness is null?" authored/recovered":$" ± {thickness.Tolerance:G4} mm, {thickness.SourcePairs.Count(p=>p.Admitted)} paired supports")}");stdout.WriteLine($"Regions: {part.Regions.Count} ({part.Regions.Count(r=>r.Kind==SheetRegionKind.Planar)} planar, {part.Regions.Count(r=>r.Kind==SheetRegionKind.CylindricalBend)} cylindrical)");stdout.WriteLine($"Bends: {part.Bends.Count}; cuts: {part.Features.Count}; base: {part.BaseRegionId}");foreach(var bend in part.Bends)stdout.WriteLine($" {bend.StableId}: {bend.BendAngleRadians*180/Math.PI:G5} deg, R{bend.InsideRadius:G6}, {bend.Direction}, {bend.AdjacentRegionA} -> {bend.AdjacentRegionB}");stdout.WriteLine($"Flat pattern: {flat.Status}; {(flat.Bounds is null?"no bounds":$"{flat.Bounds.Width:G8} x {flat.Bounds.Height:G8} mm")}; K={flat.Policy.KFactor:G4}; hash={flat.DeterministicHash}");if(flatStepOutput is not null)stdout.WriteLine($"STEP: {flatStepOutput}");if(firmamentOutput is not null)stdout.WriteLine($"Firmament: {firmamentOutput}");if(output is not null)stdout.WriteLine($"SVG: {output}");foreach(var d in allDiagnostics)stdout.WriteLine($" [{d.Severity}] {d.Code}: {d.Message}");+ stdout.WriteLine($"Sheet Metal: {part.RecognitionStatus} ({report.sourceAuthority})");if(part.Material is not null)stdout.WriteLine($"Material: {part.Material}");stdout.WriteLine($"Thickness: {part.Thickness:G8} mm{(thickness is null?" authored/recovered":$" ± {thickness.Tolerance:G4} mm, {thickness.SourcePairs.Count(p=>p.Admitted)} paired supports")}");stdout.WriteLine($"Regions: {part.Regions.Count} ({part.Regions.Count(r=>r.Kind==SheetRegionKind.Planar)} planar, {part.Regions.Count(r=>r.Kind==SheetRegionKind.CylindricalBend)} cylindrical)");stdout.WriteLine($"Bends: {part.Bends.Count}; cuts: {part.Features.Count}; base: {part.BaseRegionId}");foreach(var bend in part.Bends)stdout.WriteLine($" {bend.StableId}: {bend.BendAngleRadians*180/Math.PI:G5} deg, R{bend.InsideRadius:G6}, {bend.Direction}, {bend.AdjacentRegionA} -> {bend.AdjacentRegionB}");stdout.WriteLine($"Flat pattern: {flat.Status}; MaterialArea={(flat.MaterialArea is { } materialArea?$"{materialArea:G10} mm^2":"unavailable")}; BoundingArea={(flat.BoundingArea is { } boundingArea?$"{boundingArea:G10} mm^2":"unavailable")}; {(flat.Bounds is null?"no bounds":$"{flat.Bounds.Width:G8} x {flat.Bounds.Height:G8} mm")}; K={flat.Policy.KFactor:G4}; hash={flat.DeterministicHash}");if(flatStepOutput is not null)stdout.WriteLine($"STEP: {flatStepOutput}");if(firmamentOutput is not null)stdout.WriteLine($"Firmament: {firmamentOutput}");if(output is not null)stdout.WriteLine($"SVG: {output}");foreach(var d in allDiagnostics)stdout.WriteLine($" [{d.Severity}] {d.Code}: {d.Message}");}return flat.Status is FlatPatternStatus.Unsupported or FlatPatternStatus.Overlapping?2:0;void WriteFailure(IReadOnlyList<SheetMetalDiagnostic> ds){if(json)stdout.WriteLine(JsonSerializer.Serialize(new{command=$"sheetmetal {operation}",success=false,input,diagnostics=ds},JsonOptions));else foreach(var d in ds)stderr.WriteLine($"[{d.Severity}] {d.Code}: {d.Message}");}@@ -1362,22 +1362,25 @@ Model CanonicalPanel {wireForm = wire is null ? null : new{wireFormId = wire.Name, diameter = wire.DiameterMm, material = wire.Material.Identity.FirmamentPath,- operationCount = wire.Operations.Count, straightCount = wire.Operations.Count(x => x is WireStraightAir), bendCount = wire.Operations.Count(x => x is WireBendAir), coilCount = wire.Operations.Count(x => x is WireCoilAir),+ operationCount = wire.Operations.Count, straightCount = wire.Operations.Count(x => x is WireStraightAir), bendCount = wire.Operations.Count(x => x is WireBendAir), coilCount = wire.Operations.Count(x => x is WireCoilAir), knotCount = wire.Operations.Count(x => x is WireKnotPathAir),totalStraightLength = wire.TotalStraightLengthMm, totalBendLength = wire.TotalBendLengthMm, totalCoilLength = wire.TotalCoilLengthMm, totalWireLength = wire.TotalWireLengthMm,bendRadiusSemantics = "CenterlineRadius", frameTransportPolicy = wire.FrameTransportPolicy,startTerminal = new { position = new[] { wire.StartState.Position.X, wire.StartState.Position.Y, wire.StartState.Position.Z }, tangent = new[] { wire.StartState.Tangent.X, wire.StartState.Tangent.Y, wire.StartState.Tangent.Z }, diameter = wire.DiameterMm },endTerminal = new { position = new[] { wire.EndState.Position.X, wire.EndState.Position.Y, wire.EndState.Position.Z }, tangent = new[] { wire.EndState.Tangent.X, wire.EndState.Tangent.Y, wire.EndState.Tangent.Z }, diameter = wire.DiameterMm },- operations = wire.Operations.Select(operation => new { operation.Ordinal, operation.Name, kind = operation switch { WireStraightAir => "Straight", WireBendAir => "Bend", WireAxisCoilAir => "AxisCoil", WireSurfaceCoilAir => "SurfaceCoil", _ => "Unknown" }, operation.LengthMm,+ operations = wire.Operations.Select(operation => new { operation.Ordinal, operation.Name, kind = operation switch { WireStraightAir => "Straight", WireBendAir => "Bend", WireAxisCoilAir => "AxisCoil", WireSurfaceCoilAir => "SurfaceCoil", WireKnotPathAir => "KnotPath", _ => "Unknown" }, operation.LengthMm,radius = operation is WireBendAir bend ? bend.RadiusMm : (double?)null, angleDegrees = operation is WireBendAir angle ? angle.AngleRadians * 180d / Math.PI : (double?)null,plane = operation is WireBendAir plane ? plane.Plane : null, coilKind = operation is WireCoilAir coil ? coil.CoilKind : null,turns = operation is WireCoilAir turns ? turns.Turns : (double?)null, handedness = operation is WireCoilAir handed ? handed.Handedness.ToString() : null,pitch = operation switch { WireAxisCoilAir axis => axis.PitchMm, WireSurfaceCoilAir surface => surface.AxialPitchMm, _ => (double?)null },progressionLaw = operation is WireCoilAir progression ? progression.ProgressionLaw : null, selfClearance = operation is WireCoilAir self ? self.MinimumSelfClearanceMm : (double?)null,- supportClearance = operation is WireCoilAir support ? support.SupportClearanceMm : null, representation = operation is WireCoilAir ? "ExactEvaluableWindingLaw->NonRationalBSplineTube" : "Analytic",- approximationTolerance = operation is WireCoilAir tolerance ? tolerance.ApproximationToleranceMm : (double?)null,- approximationSegmentCount = operation is WireCoilAir segments ? segments.ApproximationSegmentCount : (int?)null,- approximationMaxError = operation is WireCoilAir maxError ? maxError.ApproximationError.MaxMm : (double?)null,- approximationRmsError = operation is WireCoilAir rmsError ? rmsError.ApproximationError.RmsMm : (double?)null,+ supportClearance = operation is WireCoilAir support ? support.SupportClearanceMm : null, representation = operation switch { WireKnotPathAir => "ExactEvaluablePeriodicKnotLaw->ClosureCorrectedNonRationalBSplineTube", WireCoilAir => "ExactEvaluableWindingLaw->NonRationalBSplineTube", _ => "Analytic" },+ approximationTolerance = operation is WireEvaluablePathAir tolerance ? tolerance.ApproximationToleranceMm : (double?)null,+ approximationSegmentCount = operation is WireEvaluablePathAir segments ? segments.ApproximationSegmentCount : (int?)null,+ approximationMaxError = operation is WireEvaluablePathAir maxError ? maxError.ApproximationError.MaxMm : (double?)null,+ approximationRmsError = operation is WireEvaluablePathAir rmsError ? rmsError.ApproximationError.RmsMm : (double?)null,+ knot = operation is WireKnotPathAir knot ? new { family = knot.Family.ToString(), knot.P, knot.Q, knot.ComponentCount, knot.Closed, knot.ScaleMm, knot.MajorRadiusMm, knot.MinorRadiusMm, handedness = knot.Handedness.ToString(), phaseDegrees = knot.PhaseRadians * 180d / Math.PI, seamParameter = knot.SeamParameter,+ centerlineLength = knot.LengthMm, lengthIntegrationError = knot.Qualification.LengthIntegrationErrorMm, minimumNonlocalCenterlineDistance = knot.Qualification.MinimumNonlocalDistanceMm, minimumLocalCurvatureRadius = knot.Qualification.MinimumCurvatureRadiusMm, tubeRadiusLimit = knot.Qualification.TubeRadiusLimitMm, maximumAdmittedDiameter = knot.Qualification.MaximumAdmittedDiameterMm, closestParameter1 = knot.Qualification.ClosestParameter1, closestParameter2 = knot.Qualification.ClosestParameter2,+ rawClosureRotation = knot.FrameClosure.RawClosureRotationRadians, appliedDistributedCorrection = knot.FrameClosure.AppliedCorrectionRadians, finalClosureRotationError = knot.FrameClosure.FinalClosureErrorRadians, qualificationMethod = knot.Qualification.Method } : null,stableId = operation.StableId(wire.Name), input = operation.Input, output = operation.Output })}, diagnostics = wireDiagnostics};diff --git a/Aetheris.Kernel.Core/Brep/Features/CombinedTopBoundaryChamferThroughHoleBuilder.cs b/Aetheris.Kernel.Core/Brep/Features/CombinedTopBoundaryChamferThroughHoleBuilder.csindex ef39137d..01c4f742 100644--- a/Aetheris.Kernel.Core/Brep/Features/CombinedTopBoundaryChamferThroughHoleBuilder.cs+++ b/Aetheris.Kernel.Core/Brep/Features/CombinedTopBoundaryChamferThroughHoleBuilder.cs@@ -17,7 +17,13 @@ public sealed record CombinedTopBoundaryChamferThroughHole(string FeatureId,double CenterX,double CenterY,- double Radius);+ double Radius,+ double? CounterboreRadius = null,+ double? CounterboreDepth = null)+{+ public bool IsCounterbore => CounterboreRadius is not null;+ public double EntryRadius => CounterboreRadius ?? Radius;+}public sealed record CombinedTopBoundaryChamferThroughHolePlan(string PlanId,@@ -39,7 +45,11 @@ public sealed record CombinedTopBoundaryChamferThroughHolePlan(var bottomArea = Width * Depth;var topArea = (Width - (2d * ChamferDistance)) * (Depth - (2d * ChamferDistance));var chamferedHost = (bottomArea * lowerHeight) + (ChamferDistance / 3d * (bottomArea + topArea + System.Math.Sqrt(bottomArea * topArea)));- return chamferedHost - Holes.Sum(h => System.Math.PI * h.Radius * h.Radius * height);+ var removed = Holes.Sum(h => System.Math.PI * h.Radius * h.Radius * height+ + (h.CounterboreRadius is { } reliefRadius && h.CounterboreDepth is { } reliefDepth+ ? System.Math.PI * (reliefRadius * reliefRadius - h.Radius * h.Radius) * reliefDepth+ : 0d));+ return chamferedHost - removed;}}}@@ -89,8 +99,14 @@ public static class CombinedTopBoundaryChamferThroughHoleBuilder// The periodic circle and its longitudinal seam share endpoint identities.// Coincident but distinct seam/circle vertices produce invalid STEP wires.var seamTop = b.AddVertex(); var seamBottom = b.AddVertex();- return new HoleTopology(h, seamTop, seamBottom,- b.AddEdge(seamTop, seamTop), b.AddEdge(seamBottom, seamBottom), b.AddEdge(seamTop, seamBottom));+ if (!h.IsCounterbore)+ return new HoleTopology(h, seamTop, seamBottom, null, null,+ b.AddEdge(seamTop, seamTop), b.AddEdge(seamBottom, seamBottom), null, null, b.AddEdge(seamTop, seamBottom), null);+ var shoulderOuter = b.AddVertex(); var shoulderInner = b.AddVertex();+ return new HoleTopology(h, seamTop, seamBottom, shoulderOuter, shoulderInner,+ b.AddEdge(seamTop, seamTop), b.AddEdge(seamBottom, seamBottom),+ b.AddEdge(shoulderOuter, shoulderOuter), b.AddEdge(shoulderInner, shoulderInner),+ b.AddEdge(seamTop, shoulderOuter), b.AddEdge(shoulderInner, seamBottom));}).ToArray();var bottomLoops = new List<LoopId> { AddLoop(b, bottomEdges.Select(Forward).ToArray()) };@@ -111,8 +127,25 @@ public static class CombinedTopBoundaryChamferThroughHoleBuilderlowerFaces[i] = b.AddFace([AddLoop(b, [Forward(bottomEdges[i]), Forward(lowerEdges[next]), Reversed(shoulderEdges[i]), Reversed(lowerEdges[i])])]);chamferFaces[i] = b.AddFace([AddLoop(b, [Forward(shoulderEdges[i]), Forward(chamferEdges[next]), Reversed(topEdges[i]), Reversed(chamferEdges[i])])]);}- var holeFaces = holes.Select(h => b.AddFace([AddLoop(b, [Forward(h.Seam), Forward(h.BottomCircle), Reversed(h.Seam), Reversed(h.TopCircle)])])).ToArray();- var shell = b.AddShell([bottomFace, topFace, .. lowerFaces, .. chamferFaces, .. holeFaces]);+ var holeFaces = new List<(HoleTopology Hole, FaceId Face, double Radius, double ZMin, double ZMax)>();+ var shoulderFaces = new List<(HoleTopology Hole, FaceId Face)>();+ foreach (var hole in holes)+ {+ if (!hole.Hole.IsCounterbore)+ {+ var face=b.AddFace([AddLoop(b, [Forward(hole.UpperSeam), Forward(hole.BottomCircle), Reversed(hole.UpperSeam), Reversed(hole.TopCircle)])]);+ holeFaces.Add((hole,face,hole.Hole.Radius,plan.ZMin,plan.ZMax));+ continue;+ }+ var shoulderZ=plan.ZMax-hole.Hole.CounterboreDepth!.Value;+ var boreFace=b.AddFace([AddLoop(b,[Forward(hole.UpperSeam),Forward(hole.ShoulderOuterCircle!.Value),Reversed(hole.UpperSeam),Reversed(hole.TopCircle)])]);+ var shoulderFace=b.AddFace([AddLoop(b,[Reversed(hole.ShoulderOuterCircle.Value)]),AddLoop(b,[Forward(hole.ShoulderInnerCircle!.Value)])]);+ var shaftFace=b.AddFace([AddLoop(b,[Forward(hole.LowerSeam!.Value),Forward(hole.BottomCircle),Reversed(hole.LowerSeam.Value),Reversed(hole.ShoulderInnerCircle.Value)])]);+ holeFaces.Add((hole,boreFace,hole.Hole.CounterboreRadius!.Value,shoulderZ,plan.ZMax));+ shoulderFaces.Add((hole,shoulderFace));+ holeFaces.Add((hole,shaftFace,hole.Hole.Radius,plan.ZMin,shoulderZ));+ }+ var shell = b.AddShell([bottomFace, topFace, .. lowerFaces, .. chamferFaces, .. holeFaces.Select(x=>x.Face), .. shoulderFaces.Select(x=>x.Face)]);b.AddBody([shell]);var geometry = new BrepGeometryStore();@@ -141,25 +174,39 @@ public static class CombinedTopBoundaryChamferThroughHoleBuilderBindPlane(lowerFaces[i], bottom[i], bottom[next] - bottom[i], shoulder[i] - bottom[i]);BindPlane(chamferFaces[i], shoulder[i], shoulder[next] - shoulder[i], top[i] - shoulder[i]);}- foreach (var (hole, index) in holes.Select((h, i) => (h, i)))+ foreach (var hole in holes){var topCurve = new CurveGeometryId(edgeCurve++); var bottomCurve = new CurveGeometryId(edgeCurve++); var seamCurve = new CurveGeometryId(edgeCurve++);var centerTop = new Point3D(hole.Hole.CenterX, hole.Hole.CenterY, plan.ZMax);var centerBottom = new Point3D(hole.Hole.CenterX, hole.Hole.CenterY, plan.ZMin);- geometry.AddCurve(topCurve, CurveGeometry.FromCircle(new Circle3Curve(centerTop, zAxis, hole.Hole.Radius, xAxis)));+ geometry.AddCurve(topCurve, CurveGeometry.FromCircle(new Circle3Curve(centerTop, zAxis, hole.Hole.EntryRadius, xAxis)));geometry.AddCurve(bottomCurve, CurveGeometry.FromCircle(new Circle3Curve(centerBottom, zAxis, hole.Hole.Radius, xAxis)));- geometry.AddCurve(seamCurve, CurveGeometry.FromLine(new Line3Curve(new Point3D(hole.Hole.CenterX + hole.Hole.Radius, hole.Hole.CenterY, plan.ZMin), zAxis)));+ var upperZMin=hole.Hole.IsCounterbore?plan.ZMax-hole.Hole.CounterboreDepth!.Value:plan.ZMin;+ geometry.AddCurve(seamCurve, CurveGeometry.FromLine(new Line3Curve(new Point3D(hole.Hole.CenterX + hole.Hole.EntryRadius, hole.Hole.CenterY, upperZMin), zAxis)));bindings.AddEdgeBinding(new EdgeGeometryBinding(hole.TopCircle, topCurve, new ParameterInterval(0d, 2d * System.Math.PI)));bindings.AddEdgeBinding(new EdgeGeometryBinding(hole.BottomCircle, bottomCurve, new ParameterInterval(0d, 2d * System.Math.PI)));- bindings.AddEdgeBinding(new EdgeGeometryBinding(hole.Seam, seamCurve, new ParameterInterval(0d, plan.ZMax - plan.ZMin)));- var sid = new SurfaceGeometryId(surface++);- geometry.AddSurface(sid, SurfaceGeometry.FromCylinder(new CylinderSurface(new Point3D(hole.Hole.CenterX, hole.Hole.CenterY, plan.ZMin), zAxis, hole.Hole.Radius, xAxis)));- // Hole walls bound void material, so their analytic cylinder sense is- // opposite the retained outer shell.- bindings.AddFaceBinding(new FaceGeometryBinding(holeFaces[index], sid, SameSense: false));- vertexPoints[hole.SeamTopVertex] = new Point3D(hole.Hole.CenterX + hole.Hole.Radius, hole.Hole.CenterY, plan.ZMax);+ bindings.AddEdgeBinding(new EdgeGeometryBinding(hole.UpperSeam, seamCurve, new ParameterInterval(0d, plan.ZMax - upperZMin)));+ vertexPoints[hole.SeamTopVertex] = new Point3D(hole.Hole.CenterX + hole.Hole.EntryRadius, hole.Hole.CenterY, plan.ZMax);vertexPoints[hole.SeamBottomVertex] = new Point3D(hole.Hole.CenterX + hole.Hole.Radius, hole.Hole.CenterY, plan.ZMin);+ if (hole.Hole.IsCounterbore)+ {+ var shoulderZ=upperZMin;+ var outerCurve=new CurveGeometryId(edgeCurve++);var innerCurve=new CurveGeometryId(edgeCurve++);var lowerSeamCurve=new CurveGeometryId(edgeCurve++);+ geometry.AddCurve(outerCurve,CurveGeometry.FromCircle(new Circle3Curve(new(hole.Hole.CenterX,hole.Hole.CenterY,shoulderZ),zAxis,hole.Hole.CounterboreRadius!.Value,xAxis)));+ geometry.AddCurve(innerCurve,CurveGeometry.FromCircle(new Circle3Curve(new(hole.Hole.CenterX,hole.Hole.CenterY,shoulderZ),zAxis,hole.Hole.Radius,xAxis)));+ geometry.AddCurve(lowerSeamCurve,CurveGeometry.FromLine(new Line3Curve(new(hole.Hole.CenterX+hole.Hole.Radius,hole.Hole.CenterY,plan.ZMin),zAxis)));+ bindings.AddEdgeBinding(new(hole.ShoulderOuterCircle!.Value,outerCurve,new(0,2d*System.Math.PI)));+ bindings.AddEdgeBinding(new(hole.ShoulderInnerCircle!.Value,innerCurve,new(0,2d*System.Math.PI)));+ bindings.AddEdgeBinding(new(hole.LowerSeam!.Value,lowerSeamCurve,new(0,shoulderZ-plan.ZMin)));+ vertexPoints[hole.ShoulderOuterVertex!.Value]=new(hole.Hole.CenterX+hole.Hole.CounterboreRadius.Value,hole.Hole.CenterY,shoulderZ);+ vertexPoints[hole.ShoulderInnerVertex!.Value]=new(hole.Hole.CenterX+hole.Hole.Radius,hole.Hole.CenterY,shoulderZ);+ }+ }+ foreach(var wall in holeFaces)+ {+ var sid=new SurfaceGeometryId(surface++);geometry.AddSurface(sid,SurfaceGeometry.FromCylinder(new CylinderSurface(new(wall.Hole.Hole.CenterX,wall.Hole.Hole.CenterY,wall.ZMin),zAxis,wall.Radius,xAxis)));bindings.AddFaceBinding(new(wall.Face,sid,SameSense:false));}+ foreach(var shoulderBinding in shoulderFaces)BindPlane(shoulderBinding.Face,new(shoulderBinding.Hole.Hole.CenterX,shoulderBinding.Hole.Hole.CenterY,plan.ZMax-shoulderBinding.Hole.Hole.CounterboreDepth!.Value),new Vector3D(1,0,0),new Vector3D(0,1,0));var body = new BrepBody(b.Model, geometry, bindings, vertexPoints);var brepValidation = BrepBindingValidator.Validate(body, requireAllEdgeAndFaceBindings: true);@@ -185,14 +232,16 @@ public static class CombinedTopBoundaryChamferThroughHoleBuilder{if (!double.IsFinite(hole.CenterX) || !double.IsFinite(hole.CenterY) || !double.IsFinite(hole.Radius) || hole.Radius <= Tol)return Failure($"CombinedFeaturePlanChainInvalid: hole '{hole.FeatureId}' has invalid cylinder data.");- if (System.Math.Abs(hole.CenterX) + hole.Radius >= plan.Width / 2d - plan.ChamferDistance - Tol || System.Math.Abs(hole.CenterY) + hole.Radius >= plan.Depth / 2d - plan.ChamferDistance - Tol)+ if (hole.IsCounterbore && (hole.CounterboreRadius <= hole.Radius + Tol || hole.CounterboreDepth <= Tol || hole.CounterboreDepth >= plan.ZMax-plan.ZMin-Tol))+ return Failure($"CombinedFeaturePlanChainInvalid: counterbore '{hole.FeatureId}' has invalid relief dimensions.");+ if (System.Math.Abs(hole.CenterX) + hole.EntryRadius >= plan.Width / 2d - plan.ChamferDistance - Tol || System.Math.Abs(hole.CenterY) + hole.EntryRadius >= plan.Depth / 2d - plan.ChamferDistance - Tol)return Failure($"CombinedFeatureInteractionUnsupported: hole '{hole.FeatureId}' intersects or splits the selected outer top-boundary chamfer chain.");}for (var i = 0; i < plan.Holes.Count; i++)for (var j = i + 1; j < plan.Holes.Count; j++){var a = plan.Holes[i]; var b = plan.Holes[j];- if (System.Math.Sqrt(System.Math.Pow(a.CenterX - b.CenterX, 2d) + System.Math.Pow(a.CenterY - b.CenterY, 2d)) <= a.Radius + b.Radius + Tol)+ if (System.Math.Sqrt(System.Math.Pow(a.CenterX - b.CenterX, 2d) + System.Math.Pow(a.CenterY - b.CenterY, 2d)) <= a.EntryRadius + b.EntryRadius + Tol)return Failure($"CombinedFeatureInteractionUnsupported: holes '{a.FeatureId}' and '{b.FeatureId}' overlap.");}return KernelResult<bool>.Success(true);@@ -211,5 +260,7 @@ public static class CombinedTopBoundaryChamferThroughHoleBuilderprivate static Use Forward(EdgeId edge) => new(edge, false);private static Use Reversed(EdgeId edge) => new(edge, true);private readonly record struct Use(EdgeId Edge, bool Reversed);- private sealed record HoleTopology(CombinedTopBoundaryChamferThroughHole Hole, VertexId SeamTopVertex, VertexId SeamBottomVertex, EdgeId TopCircle, EdgeId BottomCircle, EdgeId Seam);+ private sealed record HoleTopology(CombinedTopBoundaryChamferThroughHole Hole, VertexId SeamTopVertex, VertexId SeamBottomVertex,+ VertexId? ShoulderOuterVertex,VertexId? ShoulderInnerVertex,EdgeId TopCircle,EdgeId BottomCircle,+ EdgeId? ShoulderOuterCircle,EdgeId? ShoulderInnerCircle,EdgeId UpperSeam,EdgeId? LowerSeam);}diff --git a/Aetheris.Kernel.Firmament.Tests/KnotPathTests.cs b/Aetheris.Kernel.Firmament.Tests/KnotPathTests.csnew file mode 100644index 00000000..d2b5cd60--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/KnotPathTests.cs@@ -0,0 +1,98 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.Materializer;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class KnotPathTests+{+ [Theory]+ [InlineData("trefoil.firmament", WireKnotFamily.Trefoil, null, null)]+ [InlineData("figure-eight.firmament", WireKnotFamily.FigureEight, null, null)]+ [InlineData("torus-knot-3-5.firmament", WireKnotFamily.TorusKnot, 3, 5)]+ public void NamedFamiliesRetainPeriodicSemanticIdentity(string fixture, WireKnotFamily family, int? p, int? q)+ {+ var parsed = Parse(fixture); var knot = Assert.IsType<WireKnotPathAir>(Assert.Single(parsed.Operations));+ Assert.Equal(family, knot.Family); Assert.Equal(p, knot.P); Assert.Equal(q, knot.Q); Assert.Equal(1, knot.ComponentCount); Assert.True(knot.Closed); Assert.Equal(0d, knot.SeamParameter);+ Assert.True((knot.Evaluate(0d) - knot.Evaluate(1d)).Length < 1e-10);+ Assert.True(Dot(knot.Tangent(0d), knot.Tangent(1d)) > 1d - 1e-12);+ Assert.True(knot.ApproximationError.MaxMm <= knot.ApproximationToleranceMm);+ Assert.True(knot.Qualification.MinimumNonlocalDistanceMm > 0d); Assert.True(knot.Qualification.MinimumCurvatureRadiusMm > 0d);+ Assert.True(knot.Qualification.TubeRadiusLimitMm > parsed.WireRadiusMm);+ }++ [Theory]+ [InlineData("trefoil.firmament")]+ [InlineData("figure-eight.firmament")]+ [InlineData("torus-knot-3-5.firmament")]+ public void ClosedTubeHasNoCapsAndExportsPcurveCompletePolynomialStep(string fixture)+ {+ var built = WireFormBRepMaterializer.Build(Parse(fixture)); Assert.True(built.IsSuccess, Messages(built.Diagnostics));+ Assert.DoesNotContain(built.Value.Body.Geometry.Surfaces, surface => surface.Value.Kind == SurfaceGeometryKind.Plane);+ Assert.All(built.Value.Body.Topology.Edges, edge => Assert.Equal(2, built.Value.Body.Topology.Coedges.Count(use => use.EdgeId == edge.Id)));+ var pcurves = BrepPcurveValidator.Validate(built.Value.Body, 1e-6, true); Assert.True(pcurves.IsValid, string.Join(Environment.NewLine, pcurves.Diagnostics)); Assert.Equal(built.Value.Body.Topology.Coedges.Count(), pcurves.PcurveCount);+ Assert.All(built.Value.Body.Geometry.Surfaces, surface => Assert.Equal(SurfaceGeometryKind.BSplineSurfaceWithKnots, surface.Value.Kind));+ var step = Step242Exporter.ExportBody(built.Value.Body); Assert.True(step.IsSuccess, Messages(step.Diagnostics)); Assert.DoesNotContain("RATIONAL_B_SPLINE_SURFACE", step.Value, StringComparison.Ordinal);+ var imported = Step242Importer.ImportBody(step.Value); Assert.True(imported.IsSuccess, Messages(imported.Diagnostics));+ Assert.All(imported.Value!.Topology.Edges, edge => Assert.Equal(2, imported.Value.Topology.Coedges.Count(use => use.EdgeId == edge.Id)));+ }++ [Fact]+ public void ParallelTransportHolonomyIsMeasuredAndCorrectedAtTheSeam()+ {+ var knot = Assert.IsType<WireKnotPathAir>(Parse("trefoil.firmament").Operations.Single());+ Assert.True(Math.Abs(knot.FrameClosure.RawClosureRotationRadians) > 0.1d);+ Assert.Equal(-knot.FrameClosure.RawClosureRotationRadians, knot.FrameClosure.AppliedCorrectionRadians, 12);+ Assert.True(knot.FrameClosure.FinalClosureErrorRadians < 1e-12);+ }++ [Theory]+ [InlineData("torus-knot-non-coprime.firmament", "wireform-knot-not-single-component")]+ [InlineData("invalid-pq.firmament", "wireform-knot-parameters-invalid")]+ [InlineData("degenerate-scale.firmament", "wireform-knot-scale-invalid")]+ public void InvalidKnotAuthoringFailsTyped(string fixture, string code)+ {+ var parsed = WireFormAuthoring.Parse(File.ReadAllText(InvalidFixture(fixture))); Assert.False(parsed.IsSuccess); Assert.Contains(parsed.Diagnostics, diagnostic => diagnostic.Message.Contains(code, StringComparison.Ordinal));+ }++ [Fact]+ public void TubeLimitAdmitsThinAndNearLimitButRejectsTooThickWithoutStep()+ {+ foreach (var fixture in new[] { "trefoil-thin.firmament", "trefoil-near-limit.firmament" }) Assert.True(WireFormBRepMaterializer.Build(Parse(fixture)).IsSuccess);+ var source = File.ReadAllText(InvalidFixture("trefoil-wire-too-thick.firmament")); var parsed = WireFormAuthoring.Parse(source); Assert.True(parsed.IsSuccess);+ var diagnostics = WireFormBRepMaterializer.Validate(parsed.Value); Assert.Contains(diagnostics, diagnostic => diagnostic.Contains("wireform-knot-tube-self-intersection", StringComparison.Ordinal) && diagnostic.Contains("admitted maximum", StringComparison.Ordinal));+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);+ }++ [Fact]+ public void UniformScaleAndRigidOrientationPreserveIntrinsicQualification()+ {+ var canonicalSource = File.ReadAllText(Fixture("trefoil.firmament")); var canonical = Assert.IsType<WireKnotPathAir>(WireFormAuthoring.Parse(canonicalSource).Value.Operations.Single());+ var doubled = Assert.IsType<WireKnotPathAir>(WireFormAuthoring.Parse(canonicalSource.Replace("Diameter: 6mm", "Diameter: 12mm", StringComparison.Ordinal).Replace("Scale: 20mm", "Scale: 40mm", StringComparison.Ordinal)).Value.Operations.Single());+ Assert.Equal(2d, doubled.LengthMm / canonical.LengthMm, 9); Assert.Equal(2d, doubled.Qualification.MinimumNonlocalDistanceMm / canonical.Qualification.MinimumNonlocalDistanceMm, 9); Assert.Equal(2d, doubled.Qualification.MinimumCurvatureRadiusMm / canonical.Qualification.MinimumCurvatureRadiusMm, 9);+ var rotated = Assert.IsType<WireKnotPathAir>(Parse("rotated-trefoil.firmament").Operations.Single());+ Assert.Equal(canonical.LengthMm, rotated.LengthMm, 9); Assert.Equal(canonical.Qualification.MinimumNonlocalDistanceMm, rotated.Qualification.MinimumNonlocalDistanceMm, 9); Assert.Equal(canonical.Qualification.MinimumCurvatureRadiusMm, rotated.Qualification.MinimumCurvatureRadiusMm, 9);+ Assert.True((canonical.Evaluate(0d) - rotated.Evaluate(0d)).Length > 1d);+ }++ [Fact]+ public void RepeatExportAndStockAccountingAreDeterministic()+ {+ var source = File.ReadAllText(Fixture("trefoil.firmament")); var first = FirmamentBuildAndExport.CompileSource(source); var second = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(first.IsSuccess, Messages(first.Diagnostics)); Assert.True(second.IsSuccess, Messages(second.Diagnostics)); Assert.Equal(first.Value.StepText, second.Value.StepText);+ var report = first.Value.WireForm!; Assert.Equal("Trefoil", report.KnotFamily); Assert.Equal(0, report.Planes); Assert.Equal(0, report.RationalProductSurfaces); Assert.Equal(0, report.FacetedFallback); Assert.True(report.PcurveCount > 0); Assert.True(report.MaximumPcurveErrorMm < 1e-6);+ Assert.Equal(Math.PI * 9d * report.TotalWireLengthMm, report.VolumeMm3, 8); Assert.True(report.MassKilograms > 0d);+ }++ private static WireFormFeatureAir Parse(string fixture)+ {+ var result = WireFormAuthoring.Parse(File.ReadAllText(Fixture(fixture))); Assert.True(result.IsSuccess, Messages(result.Diagnostics)); return result.Value;+ }+ private static double Dot(Aetheris.Kernel.Core.Math.Direction3D a, Aetheris.Kernel.Core.Math.Direction3D b) => a.X * b.X + a.Y * b.Y + a.Z * b.Z;+ private static string Messages(IEnumerable<Aetheris.Kernel.Core.Diagnostics.KernelDiagnostic> diagnostics) => string.Join(Environment.NewLine, diagnostics.Select(x => x.Message));+ private static string Fixture(string name) => Path.Combine(RepoRoot(), "fixtures", "Canonical", "WireForm", "Knot", name);+ private static string InvalidFixture(string name) => Path.Combine(RepoRoot(), "fixtures", "Invalid", "WireForm", "Knot", name);+ private static string RepoRoot() { var directory = new DirectoryInfo(AppContext.BaseDirectory); while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent; return directory?.FullName ?? throw new DirectoryNotFoundException(); }+}diff --git a/Aetheris.Kernel.Firmament.Tests/SemanticAuthorityConvergenceTests.cs b/Aetheris.Kernel.Firmament.Tests/SemanticAuthorityConvergenceTests.csnew file mode 100644index 00000000..18d94e40--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/SemanticAuthorityConvergenceTests.cs@@ -0,0 +1,79 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Verification;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.Materializer;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class SemanticAuthorityConvergenceTests+{+ [Fact]+ public void SequentialBosses_ResolveTopAgainstCurrentFootprintSupport()+ {+ var source=File.ReadAllText(Fixture("Canonical/Features/Composition/boss-stack-current-top.firmament"));+ var parsed=PrismaticProfileCompositionParser.Parse(source);+ Assert.Empty(parsed.Diagnostics);+ var stack=Assert.IsType<PrismaticSectionStackConstruction>(PrismaticSectionStackCompiler.Normalize(parsed,out var diagnostics));+ Assert.Empty(diagnostics);+ Assert.Collection(stack.Feature.Bosses!,+ middle=>{Assert.Equal((10d,16d),(middle.From,middle.To));Assert.Equal("Top",middle.SupportFace);},+ upper=>{Assert.Equal((16d,20d),(upper.From,upper.To));Assert.Equal("Top",upper.SupportFace);});+ Assert.Equal(20d,stack.Slabs.Max(x=>x.To));+ Assert.All(stack.Slabs.Zip(stack.Slabs.Skip(1)),pair=>Assert.True(pair.First.To<=pair.Second.From));+ var emitted=PrismaticSectionStackEmitter.Emit(stack);Assert.NotNull(emitted.Body);+ Assert.True(BrepMassProperties.Evaluate(emitted.Body!).IsEnclosed);+ var step=Step242Exporter.ExportBody(emitted.Body!);Assert.True(step.IsSuccess,string.Join("; ",step.Diagnostics.Select(x=>x.Message)));+ var imported=Step242Importer.ImportBody(step.Value!);Assert.True(imported.IsSuccess,string.Join("; ",imported.Diagnostics.Select(x=>x.Message)));+ Assert.True(BrepMassProperties.Evaluate(imported.Value!).IsEnclosed);+ }++ [Fact]+ public void ExplicitBaseTop_RemainsDistinctFromRelativeCurrentTop()+ {+ var source=File.ReadAllText(Fixture("Canonical/Features/Composition/boss-stack-current-top.firmament"))+ .Replace("Boss Upper { On: Top;","Boss Upper { On: Base.Top;",StringComparison.Ordinal);+ var parsed=PrismaticProfileCompositionParser.Parse(source);Assert.Empty(parsed.Diagnostics);+ var upper=Assert.Single(parsed.Feature!.Bosses!,x=>x.Name=="Upper");+ Assert.Equal((10d,14d),(upper.From,upper.To));Assert.Equal("Base.Top",upper.SupportFace);+ var build=FirmamentBuildAndExport.CompileSource(source);+ Assert.True(build.IsSuccess,string.Join("; ",build.Diagnostics.Select(x=>x.Message)));+ }++ [Fact]+ public void EqualCurrentTopSupports_FailWithTypedAmbiguity()+ {+ var parsed=PrismaticProfileCompositionParser.Parse(File.ReadAllText(Fixture("Invalid/FeatureComposition/feature-support-top-ambiguous.firmament")));+ Assert.Null(parsed.Feature);+ Assert.Contains(parsed.Diagnostics,x=>x.StartsWith("feature-support-ambiguous:Top:feature=Bridge:candidates=Left,Right",StringComparison.Ordinal));+ }++ [Fact]+ public void MultipleBaseRoles_FailTypedWithoutRawSingleException()+ {+ var exception=Record.Exception(()=>PrismaticProfileCompositionParser.Parse(File.ReadAllText(Fixture("Invalid/FeatureComposition/compose-multiple-base.firmament"))));+ Assert.Null(exception);+ var parsed=PrismaticProfileCompositionParser.Parse(File.ReadAllText(Fixture("Invalid/FeatureComposition/compose-multiple-base.firmament")));+ Assert.Null(parsed.Feature);+ Assert.Contains("compose-role-cardinality:Base:expected=1:actual=2",parsed.Diagnostics);+ }++ [Fact]+ public void PrimitiveBoxCounterboreThenChamfer_UsesCombinedCurrentStatePlanAndRoundTrips()+ {+ var build=FirmamentBuildAndExport.CompileSource(File.ReadAllText(Fixture("Canonical/Features/Composition/box-counterbore-chamfer.firmament")));+ Assert.True(build.IsSuccess,string.Join("; ",build.Diagnostics.Select(x=>x.Message)));+ Assert.Equal("CombinedHoleEdgeFinish",build.Value!.Combined!.Route);+ var bottomArea=10d*15d;var topArea=8d*13d;+ var chamferedHost=bottomArea*19d+(bottomArea+topArea+Math.Sqrt(bottomArea*topArea))/3d;+ var expected=chamferedHost-Math.PI*2d*2d*20d-Math.PI*(3.5d*3.5d-2d*2d)*3d;+ Assert.Equal(expected,build.Value.Combined.FinalAnalyticVolume,6);+ var imported=Step242Importer.ImportBody(build.Value.StepText);Assert.True(imported.IsSuccess,string.Join("; ",imported.Diagnostics.Select(x=>x.Message)));+ Assert.True(BrepMassProperties.Evaluate(imported.Value!).IsEnclosed);+ Assert.True(build.Value.StepText.Contains("CYLINDRICAL_SURFACE",StringComparison.Ordinal));+ var repeated=FirmamentBuildAndExport.CompileSource(File.ReadAllText(Fixture("Canonical/Features/Composition/box-counterbore-chamfer.firmament")));+ Assert.True(repeated.IsSuccess,string.Join("; ",repeated.Diagnostics.Select(x=>x.Message)));+ Assert.Equal(build.Value.StepText,repeated.Value!.StepText);+ }++ private static string Fixture(string relative)=>Path.GetFullPath(Path.Combine(AppContext.BaseDirectory,"../../../../fixtures",relative));+}diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex 7ea274da..139230c6 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -312,7 +312,7 @@ public static class FirmamentBuildAndExportreturn KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, authored.Value.Name, 0,"wire-form", "wireform", WireForm: report,EngineeringFeatures: authored.Value.Operations.Select(operation => new FirmamentEngineeringFeatureReport(- operation.Name, operation switch { WireStraightAir => "Straight", WireBendAir => "Bend", WireAxisCoilAir => "AxisCoil", WireSurfaceCoilAir => "SurfaceCoil", _ => "Unknown" }, operation.StableId(authored.Value.Name),+ operation.Name, operation switch { WireStraightAir => "Straight", WireBendAir => "Bend", WireAxisCoilAir => "AxisCoil", WireSurfaceCoilAir => "SurfaceCoil", WireKnotPathAir => "KnotPath", _ => "Unknown" }, operation.StableId(authored.Value.Name),authored.Value.Name, "WireState", "CircularSection", operation.LengthMm, "CenterlineLength", "Add",PolicySource: "WireFormFeatureAir", MaterializationRoute: "WireFormCenterlineAir->CircularSweepBRepPlan")).ToArray()), []);}@@ -980,7 +980,7 @@ public static class FirmamentBuildAndExport? new AirHoleSimpleShaftHost(box.Size[0], box.Size[1], -box.Size[2] / 2d, box.Size[2] / 2d): new AirHoleSimpleShaftHost(box.Size[0], box.Size[1], 0d, box.Size[2]);var holeStages = holes.Select(h => AirHoleSimpleShaftMaterializer.Execute(h, host)).ToArray();- if (holeStages.Any(stage => !stage.Succeeded || stage.Plan is null || stage.Correspondence is null))+ if (holeStages.Any(stage => !stage.Succeeded || stage.Plan is null)){return CombinedFailure("CombinedFeatureMaterializerDiverged: admitted semantic Hole stage did not materialize its authoritative plan.", holeStages.SelectMany(stage => stage.Diagnostics));}@@ -988,11 +988,12 @@ public static class FirmamentBuildAndExportvar combinedHoles = new List<CombinedTopBoundaryChamferThroughHole>(holes.Count);foreach (var (hole, stage) in holes.Zip(holeStages)){- if (hole.EndCondition is not AirHoleEndCondition.ThroughAll || hole.Stack.Kind != AirHoleStackKind.SimpleShaft || hole.Placement is not AirFaceLocalHolePlacement placement || hole.Axis.Direction.Z < 1d - 1e-9)+ if (hole.EndCondition is not AirHoleEndCondition.ThroughAll || hole.Stack.Kind is not (AirHoleStackKind.SimpleShaft or AirHoleStackKind.Counterbore) || hole.Placement is not AirFaceLocalHolePlacement placement || hole.Axis.Direction.Z < 1d - 1e-9){- return CombinedFailure($"CombinedFeaturePlanChainInvalid: Hole '{hole.FeatureId}' is outside X1; only top/+Z simple-shaft ThroughAll holes are admitted.");+ return CombinedFailure($"CombinedFeaturePlanChainInvalid: Hole '{hole.FeatureId}' is outside the shared combined route; only top/+Z shaft or counterbore ThroughAll holes are admitted.");}- combinedHoles.Add(new CombinedTopBoundaryChamferThroughHole(hole.FeatureId, placement.U, placement.V, hole.Shaft.Radius));+ var counterbore=hole.Stack.Components.OfType<AirHoleCounterboreComponent>().SingleOrDefault();+ combinedHoles.Add(new CombinedTopBoundaryChamferThroughHole(hole.FeatureId, placement.U, placement.V, hole.Shaft.Radius,counterbore?.Radius,counterbore?.Depth));}// Resolve and admit the exact EdgeFinish family after the Hole stage. X1's@@ -1044,12 +1045,15 @@ public static class FirmamentBuildAndExportvar descendants = new List<SemanticTopologyDescendant>();var finalTop = body.Topology.Faces.Single(f => f.Id.Value == 2);var finalBottom = body.Topology.Faces.Single(f => f.Id.Value == 1);+ var wallFaceId=11;for (var i = 0; i < holes.Count; i++){var source = $"hole:{holes[i].FeatureId}";descendants.Add(new($"combined:{source}:mouth-loop", "Loop", SemanticTopologyRole.HoleEntryLoop, source, Loop: finalTop.LoopIds[i + 1], ParentStableId: holes[i].FeatureId));descendants.Add(new($"combined:{source}:exit-loop", "Loop", SemanticTopologyRole.HoleExitLoop, source, Loop: finalBottom.LoopIds[i + 1], ParentStableId: holes[i].FeatureId));- descendants.Add(new($"combined:{source}:wall", "Face", SemanticTopologyRole.HoleWallFace, source, Face: new FaceId(11 + i), ParentStableId: holes[i].FeatureId));+ descendants.Add(new($"combined:{source}:shaft-wall", "Face", SemanticTopologyRole.HoleWallFace, source, Face: new FaceId(wallFaceId++), ParentStableId: holes[i].FeatureId));+ if(combinedHoles[i].IsCounterbore)+ descendants.Add(new($"combined:{source}:counterbore-wall", "Face", SemanticTopologyRole.HoleWallFace, source, Face: new FaceId(wallFaceId++), ParentStableId: holes[i].FeatureId));}descendants.Add(new($"combined:edgefinish:{finish.Name}:replacement", "Face", SemanticTopologyRole.EdgeFinishReplacementFace, $"edgefinish:{finish.Name}", Face: new FaceId(7), ParentStableId: finish.Name));var correspondence = new SemanticTopologyCorrespondence(solid.Name, descendants, ["HostBRepPlan", "HoleChangedBRepPlan", "EdgeFinishChangedBRepPlan", "AuthoritativeBRepPlan"]);@@ -1058,14 +1062,15 @@ public static class FirmamentBuildAndExportreturn CombinedFailure("CombinedFeaturePlanChainInvalid: final plan lost Hole mouth or exit correspondence.");}- var holeRemoved = combinedHoles.Sum(h => System.Math.PI * h.Radius * h.Radius * (host.ZMax - host.ZMin));+ var holeRemoved = combinedHoles.Sum(h => System.Math.PI * h.Radius * h.Radius * (host.ZMax - host.ZMin)+ +(h.CounterboreRadius is { } reliefRadius&&h.CounterboreDepth is { } reliefDepth?System.Math.PI*(reliefRadius*reliefRadius-h.Radius*h.Radius)*reliefDepth:0d));var report = new FirmamentCombinedFeaturePlanReport("CombinedHoleEdgeFinish", "Succeeded", finalPlan.ParentHostPlanId!, finalPlan.AppliedFeatureIds, finalPlan.PlanId, "Disjoint",descendants.Count(d => d.SourceStableId.StartsWith("hole:", StringComparison.Ordinal)), 1,box.Size[0] * box.Size[1] * (host.ZMax - host.ZMin), holeRemoved, finalPlan.AnalyticVolume,Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))), body.Topology.Vertices.Count(), body.Topology.Edges.Count(), body.Topology.Faces.Count(),body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Plane), body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Cylinder), true, true);- var featureReports = holes.Select(h => new FirmamentHoleFeatureReport(h.Name, "Hole", h.FeatureId, h.Shaft.Diameter, h.Placement.U, h.Placement.V, null, null, null, null, "top", null, nameof(AirHoleSimpleShaftMaterializer), "HoleChangedBRepPlan", h.Stack.Kind.ToString(), "CombinedHoleEdgeFinish", 1, 0, 0, report.StepSha256, true)).ToArray();+ var featureReports = holes.Select(h => new FirmamentHoleFeatureReport(h.Name, "Hole", h.FeatureId, h.Shaft.Diameter, h.Placement.U, h.Placement.V, null, null, null, null, "top", null, nameof(AirHoleSimpleShaftMaterializer), "HoleChangedBRepPlan", h.Stack.Kind.ToString(), "CombinedHoleEdgeFinish", h.Stack.Kind==AirHoleStackKind.Counterbore?2:1, 0, h.Stack.Kind==AirHoleStackKind.Counterbore?1:0, report.StepSha256, true)).ToArray();return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value,finish.Name,diff --git a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.csindex 4bfc7c4f..8fa36e3c 100644--- a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs+++ b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs@@ -40,7 +40,14 @@ public sealed record FirmamentWireOperationReport(double? HeightMm = null, double? StartPhaseDegrees = null, string? Support = null, string? Side = null,string? ProgressionLaw = null, double? MinimumSelfClearanceMm = null, double? SupportClearanceMm = null,double? CenterlineApproximationToleranceMm = null, int? CenterlineApproximationSegmentCount = null,- double? CenterlineApproximationMaxErrorMm = null, double? CenterlineApproximationRmsErrorMm = null);+ double? CenterlineApproximationMaxErrorMm = null, double? CenterlineApproximationRmsErrorMm = null,+ string? KnotFamily = null, int? P = null, int? Q = null, int? ComponentCount = null, bool? Closed = null,+ double? ScaleMm = null, double? MajorRadiusMm = null, double? MinorRadiusMm = null,+ double? MinimumNonlocalCenterlineDistanceMm = null, double? MinimumLocalCurvatureRadiusMm = null,+ double? TubeRadiusLimitMm = null, double? RawClosureRotationRadians = null,+ double? AppliedDistributedCorrectionRadians = null, double? FinalClosureRotationErrorRadians = null,+ double? KnotApproximationMaxErrorMm = null, double? KnotApproximationRmsErrorMm = null,+ double? ClosestParameter1 = null, double? ClosestParameter2 = null);public sealed record FirmamentWireTerminalReport(string Name, IReadOnlyList<double> Position, IReadOnlyList<double> Tangent, IReadOnlyList<double> Up, double DiameterMm);@@ -56,7 +63,10 @@ public sealed record FirmamentWireFormReport(bool StepReimportSucceeded, bool StepReimportedManifold,int CoilCount = 0, double TotalCoilLengthMm = 0d, double? MinimumSelfClearanceMm = null,int NonRationalBSplineSurfaces = 0, int MaximumPolynomialDegree = 0,- string CoilRepresentation = "NotApplicable");+ string CoilRepresentation = "NotApplicable", int KnotCount = 0, string? KnotFamily = null,+ double? MinimumNonlocalCenterlineDistanceMm = null, double? MinimumLocalCurvatureRadiusMm = null,+ double? TubeRadiusLimitMm = null, double? FinalFrameClosureErrorRadians = null,+ int Vertices = 0, int Edges = 0, int Faces = 0, int PcurveCount = 0, double MaximumPcurveErrorMm = 0d);public sealed record FirmamentSemanticPatternReport(string Name,diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.csindex e27745ad..650383bb 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs@@ -1973,7 +1973,7 @@ public static class FirmamentV2Parser|| code.StartsWith(ConceptIrResolver.PointProjectionUnsupported, StringComparison.Ordinal)|| code.StartsWith("firmament-static-", StringComparison.Ordinal);- public static bool IsFatalDiagnosticCode(string code) => code.StartsWith("firmament-boss-", StringComparison.Ordinal) || code.StartsWith("firmament-pocket-", StringComparison.Ordinal) || code.StartsWith(ModifyTargetNotBoundToActiveCompose, StringComparison.Ordinal) || code.StartsWith("firmament-v2-assert-volume-", StringComparison.Ordinal) || code.StartsWith(SemanticConstraintMalformed, StringComparison.Ordinal) || code.StartsWith(SemanticConstraintUnsupported, StringComparison.Ordinal) || code.StartsWith(SemanticConstraintDimensionMismatch, StringComparison.Ordinal) || code.StartsWith(SemanticConstraintValidationFailed, StringComparison.Ordinal) || code.StartsWith(PmiProjectionUnknownRequire, StringComparison.Ordinal) || code.StartsWith(PmiProjectionUnsupportedKind, StringComparison.Ordinal) || code.StartsWith(PmiProjectedFieldMustNotOverrideSourceConstraint, StringComparison.Ordinal) || code.StartsWith(AssertVolumeKindUnsupported, StringComparison.Ordinal) || code.StartsWith(CanonicalDeclarationUnknown + ":", StringComparison.Ordinal) || code.StartsWith(CanonicalConstructNotYetSupported + ":", StringComparison.Ordinal) || code.StartsWith(EdgeFinishProfileComposeBoundaryUnsupported, StringComparison.Ordinal) || IsConceptFatalDiagnostic(code) || code is UnknownConstructionPolicy or PrimitiveDoesNotSatisfyHollowConstructible or WallThicknessRequired or WallThicknessMustBePositive or UnsupportedOpening or MultipleOpeningsNotSupported or Phase3EdgeFinishSyntaxInvalid or PrimitiveFieldMissing or PrimitiveFieldUnknown or PrimitiveFieldInvalid or MissingModel or MissingUnits or MissingSolid or UnsupportedConstruct or UnknownRecordType or BoxMissingSize or BoxSizeArity or DegenerateDimension or NameUnresolved or DuplicateName or WithRequiresRecord or WithRequiresBoxRecord or WithFieldNotFound or WithFieldTypeMismatch or WithForwardReference or WithDerivedRecordInvalid or ExposeBlockUnsupported or ExposeRequiresBoxRecord or ExposeAliasDuplicate or ExposeAliasInvalid or SelectorUnsupported or SelectorAxisInvalid or SelectorSubselectorUnsupported or FatArrowOutsideExpose or RawBackendIdReferenceForbidden or ModifyTargetUnresolved or ModifyTargetNotSolid or RegionUnsupported or RegionAttachmentSelectorUnsupported or CutUnsupported or CutToolUnsupported or CylinderRadiusMissing or CylinderRadiusInvalid or CylinderRadiusNotFinite or ThroughSelectorUnsupported or AliasUnresolved or AliasRefTypeUnsupported or SideHoleAliasMustResolveToFace or SideHoleAliasResolvesToUnsupportedFace or SideHoleOnlyPlusXMinusXSupported or SideHoleRouteUnsupported or SideHoleSameFaceUnsupported or SideHoleAxisNotYetSupported or SideHoleRadiusExceedsClearance or CylinderCenterInvalid or CylinderCenterArityInvalid or CylinderCenterNotFinite or SideHoleCenterExceedsClearance or HoleVariantUnknown or HoleEntryFaceMissing or HoleCenterMissing or HoleShaftMissing or HoleEndMissing or HoleDiameterInvalid or HoleDepthInvalid or HoleCounterboreInvalid or HoleCountersinkInvalid or PmiKindUnknown or PmiTargetMissing or PmiTargetUnresolved or PmiDiameterInvalid or PmiDuplicateName or InlineStepUnknownBody or InlineStepUnknownFace or PmiImportedTargetNotFace or PmiImportedTargetRequiresCanonicalStep or PmiInvalidImportedTarget or InlineStepPathMissing or InlineStepPathInvalid or InlineStepFileMissing or InlineStepRequiresCanonical or UnknownRecognitionBody or UnknownRecognitionFace or DuplicateRegion or UnknownRecognitionRegion or InvalidRecognitionKind or InvalidRecognitionConfidence or PmiRecognizedRegionKindMismatch or UnknownReplacementBody or UnknownReplacementRegion or ReplacementKindMismatch or ReplacementFaceUnresolved or ReplacementUnsupportedKind or ReplacementVerificationFailed or ReplacementRadiusInvalid or ReplacementEndUnsupported or LetDuplicateName or LetUnknownType or LetMismatch or LetInvalidLiteral or LetUnitMismatch or LetLiteralOnly or LetRecordDuplicateName or LetRecordDuplicateField or LetReferenceUnknownRecord or LetReferenceUnknownField or LetReferenceNonRecord or LetReferenceRecordUsedAsValue or ExpressionUnknownSymbol or ExpressionUnknownRecord or ExpressionUnknownField or ExpressionRecordUsedAsValue or ExpressionScalarUsedAsRecord or ExpressionTypeMismatch or ExpressionInvalidOperator or ExpressionDivisionByZero or ExpressionCycle or ExpressionUnsupported or ToleranceInvalidType or ToleranceUnitMismatch or ToleranceInvalidLiteral or ToleranceNegativeBilateral or ToleranceMissingMinus or ToleranceMissingPlus or ToleranceUnsupported or RecognitionEvidenceRadiusInvalid or RecognitionEvidenceSurfaceFamilyUnknown or RecognitionEvidenceAxisInvalid or SemanticProposalKindMismatch or SemanticProposalRadiusInvalid or SemanticProposalTargetUnresolved or SemanticProposalEndUnsupported or ConceptUnknownFamily or ConceptUnknownConcept or ConceptMissingRequiredField or ConceptUnknownField or ConceptDuplicateField or ConceptFieldTypeMismatch or ConceptInvalidTarget or ConceptDescriptorUnavailable or PmiDuplicateBlock or PmiDuplicateRecord or PmiDuplicateDatum or PmiUnknownRecordKind or PmiMissingRequiredField or PmiUnknownField or PmiDuplicateField or PmiInvalidTarget or PmiUnknownDatum or PmiDimensionTypeMismatch or PmiDimensionMissingTolerance or PmiToleranceTypeMismatch or StandaloneFillRegionRequired or UnsupportedStandaloneFillPattern or InvalidCellCount or CellSizeMustBePositive or StrutRadiusMustBePositive or NodeRadiusMustBePositive or MaterialBoundsMismatch or StandaloneFillMultipleUnsupported;+ public static bool IsFatalDiagnosticCode(string code) => code.StartsWith("firmament-boss-", StringComparison.Ordinal) || code.StartsWith("firmament-pocket-", StringComparison.Ordinal) || code.StartsWith("feature-support-", StringComparison.Ordinal) || code.StartsWith("compose-role-cardinality:", StringComparison.Ordinal) || code.StartsWith(ModifyTargetNotBoundToActiveCompose, StringComparison.Ordinal) || code.StartsWith("firmament-v2-assert-volume-", StringComparison.Ordinal) || code.StartsWith(SemanticConstraintMalformed, StringComparison.Ordinal) || code.StartsWith(SemanticConstraintUnsupported, StringComparison.Ordinal) || code.StartsWith(SemanticConstraintDimensionMismatch, StringComparison.Ordinal) || code.StartsWith(SemanticConstraintValidationFailed, StringComparison.Ordinal) || code.StartsWith(PmiProjectionUnknownRequire, StringComparison.Ordinal) || code.StartsWith(PmiProjectionUnsupportedKind, StringComparison.Ordinal) || code.StartsWith(PmiProjectedFieldMustNotOverrideSourceConstraint, StringComparison.Ordinal) || code.StartsWith(AssertVolumeKindUnsupported, StringComparison.Ordinal) || code.StartsWith(CanonicalDeclarationUnknown + ":", StringComparison.Ordinal) || code.StartsWith(CanonicalConstructNotYetSupported + ":", StringComparison.Ordinal) || code.StartsWith(EdgeFinishProfileComposeBoundaryUnsupported, StringComparison.Ordinal) || IsConceptFatalDiagnostic(code) || code is UnknownConstructionPolicy or PrimitiveDoesNotSatisfyHollowConstructible or WallThicknessRequired or WallThicknessMustBePositive or UnsupportedOpening or MultipleOpeningsNotSupported or Phase3EdgeFinishSyntaxInvalid or PrimitiveFieldMissing or PrimitiveFieldUnknown or PrimitiveFieldInvalid or MissingModel or MissingUnits or MissingSolid or UnsupportedConstruct or UnknownRecordType or BoxMissingSize or BoxSizeArity or DegenerateDimension or NameUnresolved or DuplicateName or WithRequiresRecord or WithRequiresBoxRecord or WithFieldNotFound or WithFieldTypeMismatch or WithForwardReference or WithDerivedRecordInvalid or ExposeBlockUnsupported or ExposeRequiresBoxRecord or ExposeAliasDuplicate or ExposeAliasInvalid or SelectorUnsupported or SelectorAxisInvalid or SelectorSubselectorUnsupported or FatArrowOutsideExpose or RawBackendIdReferenceForbidden or ModifyTargetUnresolved or ModifyTargetNotSolid or RegionUnsupported or RegionAttachmentSelectorUnsupported or CutUnsupported or CutToolUnsupported or CylinderRadiusMissing or CylinderRadiusInvalid or CylinderRadiusNotFinite or ThroughSelectorUnsupported or AliasUnresolved or AliasRefTypeUnsupported or SideHoleAliasMustResolveToFace or SideHoleAliasResolvesToUnsupportedFace or SideHoleOnlyPlusXMinusXSupported or SideHoleRouteUnsupported or SideHoleSameFaceUnsupported or SideHoleAxisNotYetSupported or SideHoleRadiusExceedsClearance or CylinderCenterInvalid or CylinderCenterArityInvalid or CylinderCenterNotFinite or SideHoleCenterExceedsClearance or HoleVariantUnknown or HoleEntryFaceMissing or HoleCenterMissing or HoleShaftMissing or HoleEndMissing or HoleDiameterInvalid or HoleDepthInvalid or HoleCounterboreInvalid or HoleCountersinkInvalid or PmiKindUnknown or PmiTargetMissing or PmiTargetUnresolved or PmiDiameterInvalid or PmiDuplicateName or InlineStepUnknownBody or InlineStepUnknownFace or PmiImportedTargetNotFace or PmiImportedTargetRequiresCanonicalStep or PmiInvalidImportedTarget or InlineStepPathMissing or InlineStepPathInvalid or InlineStepFileMissing or InlineStepRequiresCanonical or UnknownRecognitionBody or UnknownRecognitionFace or DuplicateRegion or UnknownRecognitionRegion or InvalidRecognitionKind or InvalidRecognitionConfidence or PmiRecognizedRegionKindMismatch or UnknownReplacementBody or UnknownReplacementRegion or ReplacementKindMismatch or ReplacementFaceUnresolved or ReplacementUnsupportedKind or ReplacementVerificationFailed or ReplacementRadiusInvalid or ReplacementEndUnsupported or LetDuplicateName or LetUnknownType or LetMismatch or LetInvalidLiteral or LetUnitMismatch or LetLiteralOnly or LetRecordDuplicateName or LetRecordDuplicateField or LetReferenceUnknownRecord or LetReferenceUnknownField or LetReferenceNonRecord or LetReferenceRecordUsedAsValue or ExpressionUnknownSymbol or ExpressionUnknownRecord or ExpressionUnknownField or ExpressionRecordUsedAsValue or ExpressionScalarUsedAsRecord or ExpressionTypeMismatch or ExpressionInvalidOperator or ExpressionDivisionByZero or ExpressionCycle or ExpressionUnsupported or ToleranceInvalidType or ToleranceUnitMismatch or ToleranceInvalidLiteral or ToleranceNegativeBilateral or ToleranceMissingMinus or ToleranceMissingPlus or ToleranceUnsupported or RecognitionEvidenceRadiusInvalid or RecognitionEvidenceSurfaceFamilyUnknown or RecognitionEvidenceAxisInvalid or SemanticProposalKindMismatch or SemanticProposalRadiusInvalid or SemanticProposalTargetUnresolved or SemanticProposalEndUnsupported or ConceptUnknownFamily or ConceptUnknownConcept or ConceptMissingRequiredField or ConceptUnknownField or ConceptDuplicateField or ConceptFieldTypeMismatch or ConceptInvalidTarget or ConceptDescriptorUnavailable or PmiDuplicateBlock or PmiDuplicateRecord or PmiDuplicateDatum or PmiUnknownRecordKind or PmiMissingRequiredField or PmiUnknownField or PmiDuplicateField or PmiInvalidTarget or PmiUnknownDatum or PmiDimensionTypeMismatch or PmiDimensionMissingTolerance or PmiToleranceTypeMismatch or StandaloneFillRegionRequired or UnsupportedStandaloneFillPattern or InvalidCellCount or CellSizeMustBePositive or StrutRadiusMustBePositive or NodeRadiusMustBePositive or MaterialBoundsMismatch or StandaloneFillMultipleUnsupported;private static IReadOnlyList<FirmamentV2Exposure> ParseExposures(string body, List<string> diagnostics){diff --git a/Aetheris.Kernel.Firmament/Materializer/PlanarContour2.cs b/Aetheris.Kernel.Firmament/Materializer/PlanarContour2.csindex 3fae68d5..eb7ca2e2 100644--- a/Aetheris.Kernel.Firmament/Materializer/PlanarContour2.cs+++ b/Aetheris.Kernel.Firmament/Materializer/PlanarContour2.cs@@ -118,6 +118,18 @@ public static class PlanarContourKernelreturn new(!diagnostics.Any(x => x.Severity == PlanarContourDiagnosticSeverity.Error), diagnostics);}+ /// <summary>+ /// Exact signed-loop integration of the final material contour. Outer material+ /// is positive and inner loops are voids; lines, circular arcs, and full circles+ /// are integrated analytically.+ /// </summary>+ public static double Area(PlanarContour2 contour)+ {+ ArgumentNullException.ThrowIfNull(contour);+ return Math.Abs(SignedArea(contour.OuterLoop))+ - contour.InnerLoops.Sum(loop => Math.Abs(SignedArea(loop)));+ }+/// <summary>/// Offsets a known closed line/arc chain and resolves each neighboring support/// intersection as a miter. Collapsed arcs and ambiguous/self-intersecting resultsdiff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.csindex 9741c37d..fa1ea6d4 100644--- a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs@@ -108,7 +108,7 @@ public static class PrismaticProfileCompositionParserprivate static readonly Regex BossHeader = new(@"\bBoss\s+(?<n>\w+)\s*\{", RegexOptions.CultureInvariant);private static readonly Regex PocketHeader = new(@"\bPocket\s+(?<n>\w+)\s*\{", RegexOptions.CultureInvariant);private static readonly Regex SemanticProfile = new(@"\bProfile\s*:\s*(?<profile>\w+)", RegexOptions.CultureInvariant);- private static readonly Regex SemanticSupport = new(@"\bOn\s*:\s*(?<face>\w+|[+-][XYZ])", RegexOptions.CultureInvariant);+ private static readonly Regex SemanticSupport = new(@"\bOn\s*:\s*(?<face>[A-Za-z_]\w*(?:\.Top)?|[+-][XYZ])", RegexOptions.CultureInvariant);private static readonly Regex BossHeight = new(@"\bHeight\s*:\s*(?<value>[-+.\d]+)mm", RegexOptions.CultureInvariant);private static readonly Regex PocketDepth = new(@"\bDepth\s*:\s*(?<value>[-+.\d]+)mm", RegexOptions.CultureInvariant);private static readonly Regex PocketMinimumFloor = new(@"\bMinimumFloorThickness\s*:\s*(?<value>[-+.\d]+)mm", RegexOptions.CultureInvariant);@@ -240,10 +240,14 @@ public static class PrismaticProfileCompositionParserif (!double.IsFinite(from) || !double.IsFinite(to) || from >= to) diagnostics.Add($"compose-invalid-interval:{name}:{from:R}:{to:R}");operations.Add(new(name, Enum.Parse<PrismaticProfileIntent>(match.Groups["intent"].Value), profile, from, to, match.Groups["role"].Success ? match.Groups["role"].Value : match.Groups["intent"].Value, $"offset:{match.Index}"));}- if (operations.Count(o => o.Intent == PrismaticProfileIntent.Base) != 1) diagnostics.Add("compose-requires-exactly-one-base-operation");+ var baseOperations = operations.Where(o => o.Intent == PrismaticProfileIntent.Base).ToArray();+ if (baseOperations.Length != 1)+ diagnostics.Add($"compose-role-cardinality:Base:expected=1:actual={baseOperations.Length}");var bosses = new List<PrismaticBossFeature>();var pockets = new List<PrismaticPocketFeature>();- var stock = operations.SingleOrDefault(operation => operation.Intent == PrismaticProfileIntent.Base);+ // Cardinality is authored semantics, not a LINQ assertion. Never call+ // Single/SingleOrDefault while malformed input can still reach this boundary.+ var stock = baseOperations.Length == 1 ? baseOperations[0] : null;if (stock is not null){foreach (Match header in BossHeader.Matches(composeBody))@@ -256,12 +260,17 @@ public static class PrismaticProfileCompositionParservar profileName = profileMatch.Groups["profile"].Value; var face = support.Groups["face"].Value; var height = N(heightMatch, "value");if (!names.Add(name)) { diagnostics.Add($"compose-duplicate-operation:{name}"); continue; }if (!profiles.TryGetValue(profileName, out var bossProfile)) { diagnostics.Add($"firmament-boss-invalid-profile:{name}:profile={profileName}"); continue; }- if (face is not ("Top" or "+Z")) { diagnostics.Add($"firmament-boss-invalid-target:{name}:On={face}:supported=Top"); continue; }+ if (!IsTopSelector(face)) { diagnostics.Add($"firmament-boss-invalid-target:{name}:On={face}:supported=Top-or-<feature>.Top"); continue; }if (!double.IsFinite(height) || height <= 0d) { diagnostics.Add($"firmament-boss-height-must-be-positive:{name}:height={height:R}mm"); continue; }- if (!HasConnectedBossSupport(stock, bossProfile, profiles)) { diagnostics.Add($"firmament-boss-disconnected-from-host:{name}:host={compose.Groups["n"].Value}:profile={profileName}:support=Top"); continue; }+ var candidates = ResolveTopSupports(face, stock, operations, bossProfile, profiles);+ if (candidates.Count == 0) { diagnostics.Add(face.EndsWith(".Top", StringComparison.Ordinal)+ ? $"feature-support-not-found:{name}:{face}:host={compose.Groups["n"].Value}:profile={profileName}"+ : $"firmament-boss-disconnected-from-host:{name}:host={compose.Groups["n"].Value}:profile={profileName}:support=Top"); continue; }+ if (candidates.Count > 1) { diagnostics.Add($"feature-support-ambiguous:Top:feature={name}:candidates={string.Join(",", candidates.Select(x => x.Name).Order(StringComparer.Ordinal))}"); continue; }+ var selectedSupport = candidates[0];var stableId = $"boss:{compose.Groups["n"].Value}.{name}"; var sourceSpan = $"offset:{header.Index}";- bosses.Add(new(name, stableId, compose.Groups["n"].Value, "Top", profileName, height, stock.To, stock.To + height, sourceSpan));- operations.Add(new(name, PrismaticProfileIntent.Add, profileName, stock.To, stock.To + height, "Boss", sourceSpan, stableId, "Boss"));+ bosses.Add(new(name, stableId, compose.Groups["n"].Value, face, profileName, height, selectedSupport.To, selectedSupport.To + height, sourceSpan));+ operations.Add(new(name, PrismaticProfileIntent.Add, profileName, selectedSupport.To, selectedSupport.To + height, "Boss", sourceSpan, stableId, "Boss"));}foreach (Match header in PocketHeader.Matches(composeBody))@@ -274,10 +283,13 @@ public static class PrismaticProfileCompositionParservar profileName = profileMatch.Groups["profile"].Value; var face = support.Groups["face"].Value; var depth = N(depthMatch, "value");if (!names.Add(name)) { diagnostics.Add($"compose-duplicate-operation:{name}"); continue; }if (!profiles.TryGetValue(profileName, out var pocketProfile)) { diagnostics.Add($"firmament-pocket-invalid-profile:{name}:profile={profileName}"); continue; }- if (face is not ("Top" or "+Z")) { diagnostics.Add($"firmament-pocket-invalid-target:{name}:On={face}:supported=Top"); continue; }+ if (!IsTopSelector(face)) { diagnostics.Add($"firmament-pocket-invalid-target:{name}:On={face}:supported=Top-or-<feature>.Top"); continue; }if (!double.IsFinite(depth) || depth <= 0d) { diagnostics.Add($"firmament-pocket-depth-must-be-positive:{name}:depth={depth:R}mm"); continue; }- if (!IsPocketFootprintInsideStock(stock, pocketProfile, profiles)) { diagnostics.Add($"firmament-pocket-invalid-profile:{name}:profile={profileName}:footprint-must-be-enclosed-by-host"); continue; }- var hostThickness = stock.To - stock.From; var remaining = hostThickness - depth;+ var candidates = ResolveTopSupports(face, stock, operations, pocketProfile, profiles, requireContainment: true);+ if (candidates.Count == 0) { diagnostics.Add($"feature-support-not-found:{name}:{face}:profile={profileName}:footprint-must-be-enclosed-by-support"); continue; }+ if (candidates.Count > 1) { diagnostics.Add($"feature-support-ambiguous:Top:feature={name}:candidates={string.Join(",", candidates.Select(x => x.Name).Order(StringComparer.Ordinal))}"); continue; }+ var selectedSupport = candidates[0];+ var hostThickness = selectedSupport.To - selectedSupport.From; var remaining = hostThickness - depth;var (minimumFloor, policySource) = ResolveMinimumFloor(source, body);if (!double.IsFinite(minimumFloor) || minimumFloor <= 0d){@@ -295,8 +307,8 @@ public static class PrismaticProfileCompositionParsercontinue;}var stableId = $"pocket:{compose.Groups["n"].Value}.{name}"; var sourceSpan = $"offset:{header.Index}";- pockets.Add(new(name, stableId, compose.Groups["n"].Value, "Top", profileName, depth, hostThickness, remaining, minimumFloor, policySource, stock.To - depth, stock.To, sourceSpan));- operations.Add(new(name, PrismaticProfileIntent.Remove, profileName, stock.To - depth, stock.To, "Pocket", sourceSpan, stableId, "Pocket"));+ pockets.Add(new(name, stableId, compose.Groups["n"].Value, face, profileName, depth, hostThickness, remaining, minimumFloor, policySource, selectedSupport.To - depth, selectedSupport.To, sourceSpan));+ operations.Add(new(name, PrismaticProfileIntent.Remove, profileName, selectedSupport.To - depth, selectedSupport.To, "Pocket", sourceSpan, stableId, "Pocket"));}}var shaftHoles = new List<PrismaticShaftHoleFeature>();@@ -433,6 +445,43 @@ public static class PrismaticProfileCompositionParserreturn new(feature, profiles, diagnostics.Distinct().ToArray(), expansion.Evidence);}+ private static bool IsTopSelector(string selector) => selector is "Top" or "+Z" || selector.EndsWith(".Top", StringComparison.Ordinal);++ private static IReadOnlyList<PrismaticProfileOperation> ResolveTopSupports(+ string selector,+ PrismaticProfileOperation stock,+ IReadOnlyList<PrismaticProfileOperation> operations,+ ResolvedProfile2D footprint,+ IReadOnlyDictionary<string, ResolvedProfile2D> profiles,+ bool requireContainment = false)+ {+ IEnumerable<PrismaticProfileOperation> supports;+ var relative = !selector.EndsWith(".Top", StringComparison.Ordinal);+ if (selector.EndsWith(".Top", StringComparison.Ordinal))+ {+ var owner = selector[..^4];+ supports = owner == "Base"+ ? [stock]+ : operations.Where(operation => operation.Intent != PrismaticProfileIntent.Remove+ && string.Equals(operation.Name, owner, StringComparison.Ordinal));+ }+ else supports = operations.Where(operation => operation.Intent != PrismaticProfileIntent.Remove);++ var admitted = supports.Where(support => profiles.TryGetValue(support.ProfileReference, out var supportProfile)+ && (requireContainment+ ? IsPocketFootprintInsideStock(support, footprint, profiles)+ : HasConnectedBossSupport(support, footprint, profiles)))+ .ToArray();+ if (!relative || admitted.Length == 0) return admitted;++ // A stepped current body can retain several upward plateaus. Resolve the+ // highest semantic support under this feature footprint, not the globally+ // largest Z face and not the original Base. Equal highest supports are a+ // typed ambiguity rather than topology-order selection.+ var currentTop = admitted.Max(operation => operation.To);+ return admitted.Where(operation => Math.Abs(operation.To - currentTop) <= 1e-9d).ToArray();+ }+private static bool HasConnectedBossSupport(PrismaticProfileOperation stock, ResolvedProfile2D boss, IReadOnlyDictionary<string, ResolvedProfile2D> profiles){var probe = ProfileArrangementBuilder.Compose("XY", [stock with { From = 0d, To = 1d }, new("BossSupportProbe", PrismaticProfileIntent.Add, boss.Name, 0d, 1d, "Boss", "generated")], profiles, "boss-connectivity-probe");diff --git a/Aetheris.Kernel.Firmament/Materializer/WireCoils.cs b/Aetheris.Kernel.Firmament/Materializer/WireCoils.csindex 1d27dcb3..bef5084b 100644--- a/Aetheris.Kernel.Firmament/Materializer/WireCoils.cs+++ b/Aetheris.Kernel.Firmament/Materializer/WireCoils.cs@@ -182,17 +182,7 @@ public static class WireCoilGeometryfor (var i = 0; i < points.Length; i++) for (var j = i + exclusion; j < points.Length; j++) best = Math.Min(best, (points[i] - points[j]).Length);return best - diameter;}- public static (double MaxMm, double RmsMm) MeasureCenterlineApproximation(WireCoilAir coil, int segments)- {- var squared = 0d; var maximum = 0d; var count = 0;- for (var segment = 0; segment < segments; segment++)- {- var t0 = (double)segment / segments; var t1 = (double)(segment + 1) / segments; var p0 = coil.Evaluate(t0); var p1 = coil.Evaluate(t1); var chord = (p1 - p0).Length;- var controls = new[] { p0, p0 + coil.Tangent(t0).ToVector() * (chord / 3d), p1 - coil.Tangent(t1).ToVector() * (chord / 3d), p1 };- foreach (var local in new[] { .25d, .5d, .75d }) { var inverse = 1d - local; var approximate = new Point3D(controls[0].X * inverse * inverse * inverse + 3d * controls[1].X * inverse * inverse * local + 3d * controls[2].X * inverse * local * local + controls[3].X * local * local * local, controls[0].Y * inverse * inverse * inverse + 3d * controls[1].Y * inverse * inverse * local + 3d * controls[2].Y * inverse * local * local + controls[3].Y * local * local * local, controls[0].Z * inverse * inverse * inverse + 3d * controls[1].Z * inverse * inverse * local + 3d * controls[2].Z * inverse * local * local + controls[3].Z * local * local * local); var exact = coil.Evaluate(t0 + (t1 - t0) * local); var error = (approximate - exact).Length; maximum = Math.Max(maximum, error); squared += error * error; count++; }- }- return (maximum, Math.Sqrt(squared / count));- }+ public static (double MaxMm, double RmsMm) MeasureCenterlineApproximation(WireCoilAir coil, int segments) => WireEvaluablePathGeometry.MeasureCenterlineApproximation(coil, segments);public static Direction3D TransportUp(Direction3D initial, Func<double, Direction3D> tangent, int count){var up = initial.ToVector(); var previous = tangent(0d).ToVector(); for (var i = 1; i <= count; i++) { var next = tangent((double)i / count).ToVector(); up = RotateFromTo(up, previous, next); up -= next * WireFormAuthoring.Dot(up, next); up = Direction3D.Create(up).ToVector(); previous = next; } return Direction3D.Create(up);@@ -206,6 +196,23 @@ public static class WireCoilGeometryinternal static Vector3D Rotate(Vector3D v, Vector3D a, double angle) => v * Math.Cos(angle) + WireFormAuthoring.Cross(a, v) * Math.Sin(angle) + a * (WireFormAuthoring.Dot(a, v) * (1d - Math.Cos(angle)));}+public static class WireEvaluablePathGeometry+{+ public static (double MaxMm, double RmsMm) MeasureCenterlineApproximation(WireEvaluablePathAir path, int segments)+ {+ var squared = 0d; var maximum = 0d; var count = 0;+ for (var segment = 0; segment < segments; segment++)+ {+ var t0 = (double)segment / segments; var t1 = (double)(segment + 1) / segments; var p0 = path.Evaluate(t0); var p1 = path.Evaluate(t1); var chord = (p1 - p0).Length;+ var d0 = path is WireKnotPathAir knot0 ? WireKnotGeometry.Derivative(knot0, t0) / segments : path.Tangent(t0).ToVector() * chord;+ var d1 = path is WireKnotPathAir knot1 ? WireKnotGeometry.Derivative(knot1, t1) / segments : path.Tangent(t1).ToVector() * chord;+ var controls = new[] { p0, p0 + d0 / 3d, p1 - d1 / 3d, p1 };+ foreach (var local in new[] { .25d, .5d, .75d }) { var inverse = 1d - local; var approximate = new Point3D(controls[0].X * inverse * inverse * inverse + 3d * controls[1].X * inverse * inverse * local + 3d * controls[2].X * inverse * local * local + controls[3].X * local * local * local, controls[0].Y * inverse * inverse * inverse + 3d * controls[1].Y * inverse * inverse * local + 3d * controls[2].Y * inverse * local * local + controls[3].Y * local * local * local, controls[0].Z * inverse * inverse * inverse + 3d * controls[1].Z * inverse * inverse * local + 3d * controls[2].Z * inverse * local * local + controls[3].Z * local * local * local); var exact = path.Evaluate(t0 + (t1 - t0) * local); var error = (approximate - exact).Length; maximum = Math.Max(maximum, error); squared += error * error; count++; }+ }+ return (maximum, Math.Sqrt(squared / count));+ }+}+internal static class WireCoilBRepMaterializer{private sealed record Station(Point3D Point, Direction3D Tangent, Direction3D Up, double StepLength);diff --git a/Aetheris.Kernel.Firmament/Materializer/WireForm.cs b/Aetheris.Kernel.Firmament/Materializer/WireForm.csindex aeb35b9f..7b31d21a 100644--- a/Aetheris.Kernel.Firmament/Materializer/WireForm.cs+++ b/Aetheris.Kernel.Firmament/Materializer/WireForm.cs@@ -23,6 +23,17 @@ public abstract record WireFormOperationAir(string Name, int Ordinal, WireStatepublic string StableId(string wireFormName) => $"wireform:{wireFormName}:operation:{Ordinal}:{Name}";}+/// <summary>Shared semantic authority for bounded evaluable wire paths. Samples are evidence, never authoring input.</summary>+public abstract record WireEvaluablePathAir(string Name, int Ordinal, WireState Input, WireState Output, double LengthMm,+ double ApproximationToleranceMm) : WireFormOperationAir(Name, Ordinal, Input, Output, LengthMm)+{+ public abstract Point3D Evaluate(double parameter);+ public abstract Direction3D Tangent(double parameter);+ public abstract int ApproximationSegmentCount { get; }+ public abstract bool Closed { get; }+ public (double MaxMm, double RmsMm) ApproximationError => WireEvaluablePathGeometry.MeasureCenterlineApproximation(this, ApproximationSegmentCount);+}+public sealed record WireStraightAir(string Name, int Ordinal, double AuthoredLengthMm, WireState Input, WireState Output): WireFormOperationAir(Name, Ordinal, Input, Output, AuthoredLengthMm);@@ -36,15 +47,13 @@ public enum WireSurfaceSide { Outside, Inside }/// <summary>An evaluable winding law retained as semantic authority; samples are never authoring input.</summary>public abstract record WireCoilAir(string Name, int Ordinal, double Turns, WireCoilHandedness Handedness,double StartPhaseRadians, WireState Input, WireState Output, double LengthMm, double MinimumSelfClearanceMm,- double ApproximationToleranceMm) : WireFormOperationAir(Name, Ordinal, Input, Output, LengthMm)+ double ApproximationToleranceMm) : WireEvaluablePathAir(Name, Ordinal, Input, Output, LengthMm, ApproximationToleranceMm){- public abstract Point3D Evaluate(double parameter);- public abstract Direction3D Tangent(double parameter);public abstract string CoilKind { get; }public abstract string ProgressionLaw { get; }public virtual double? SupportClearanceMm => null;- public int ApproximationSegmentCount => Math.Max(16, (int)Math.Ceiling(Turns * 32d));- public (double MaxMm, double RmsMm) ApproximationError => WireCoilGeometry.MeasureCenterlineApproximation(this, ApproximationSegmentCount);+ public override int ApproximationSegmentCount => Math.Max(16, (int)Math.Ceiling(Turns * 32d));+ public override bool Closed => false;}public sealed record WireAxisCoilAir(string Name, int Ordinal, double RadiusMm, double Turns, double PitchMm,@@ -97,7 +106,7 @@ public static class WireFormAuthoring{public const string FrameTransportPolicy = "The authored local Up/Right bend-plane axis is rotated with the tangent through each bend (rotation-minimal rigid transport about the bend normal); Straight preserves the frame.";private static readonly Regex Declaration = new(@"\bWireForm\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);- private static readonly Regex Operation = new(@"\b(?<kind>Straight|Bend|AxisCoil|SurfaceCoil|Coil)\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);+ private static readonly Regex Operation = new(@"\b(?<kind>Straight|Bend|AxisCoil|SurfaceCoil|Coil|Knot)\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);public static bool IsWireFormSource(string source) => Declaration.IsMatch(source);@@ -161,6 +170,14 @@ public static class WireFormAuthoringif (!coil.IsSuccess) return KernelResult<WireFormFeatureAir>.Failure(coil.Diagnostics);operations.Add(coil.Value); state = coil.Value.Output; continue;}+ if (match.Groups["kind"].Value == "Knot")+ {+ if (operations.Count != 0 || Operation.Matches(body).Count != 1)+ return Fail("wireform-knot-composition-unsupported", $"{operationName}: X2 KnotPath must be the sole closed operation in a WireForm.");+ var knotResult = WireKnotAuthoring.Create(operationName, ordinal, operationBody, state, diameter);+ if (!knotResult.IsSuccess) return KernelResult<WireFormFeatureAir>.Failure(knotResult.Diagnostics);+ operations.Add(knotResult.Value); state = knotResult.Value.Output; continue;+ }if (!TryLength(Property(operationBody, "Radius"), out var radius) || radius <= 0d)return Fail("wireform-bend-radius-invalid", $"{operationName}: centerline Radius must be finite and greater than zero.");@@ -184,9 +201,11 @@ public static class WireFormAuthoringoperations.Add(new WireBendAir(operationName, ordinal, radius, angle, plane, axis, center, startRadial, state, bendOutput));state = bendOutput;}- if (operations.Count == 0) return Fail("wireform-operations-empty", $"WireForm '{name}' requires at least one Straight, Bend, AxisCoil, or SurfaceCoil operation.");+ if (operations.Count == 0) return Fail("wireform-operations-empty", $"WireForm '{name}' requires at least one Straight, Bend, AxisCoil, SurfaceCoil, or Knot operation.");+ var authoredStart = new WireState(new(origin.X, origin.Y, origin.Z), tangent, up, 0d);return KernelResult<WireFormFeatureAir>.Success(new(name, diameter, materialReference, material.Material,- new WireState(new(origin.X, origin.Y, origin.Z), tangent, up, 0d), operations, FrameTransportPolicy));+ operations[0] is WireKnotPathAir ? operations[0].Input : authoredStart, operations,+ operations[0] is WireKnotPathAir knot ? knot.FrameClosure.Policy : FrameTransportPolicy));}internal static string? Property(string body, string name)@@ -259,6 +278,8 @@ public static class WireFormBRepMaterializer{var diagnostics = Validate(feature);if (diagnostics.Count > 0) return KernelResult<WireFormBuildResult>.Failure(diagnostics.Select(Error).ToArray());+ if (feature.Operations.Any(operation => operation is WireKnotPathAir))+ return WireKnotBRepMaterializer.Build(feature);if (feature.Operations.Any(operation => operation is WireCoilAir))return WireCoilBRepMaterializer.Build(feature);try@@ -338,6 +359,17 @@ public static class WireFormBRepMaterializerdiagnostics.Add($"wireform-coil-turn-clearance:{coil.Name}: adjacent turns overlap by {-coil.MinimumSelfClearanceMm:G6} mm.");if (operation is WireCoilAir approximated && approximated.ApproximationError.MaxMm > approximated.ApproximationToleranceMm)diagnostics.Add($"wireform-coil-approximation-tolerance:{approximated.Name}: measured centerline error {approximated.ApproximationError.MaxMm:G6} mm exceeds {approximated.ApproximationToleranceMm:G6} mm.");+ if (operation is WireKnotPathAir knot)+ {+ if (knot.ApproximationError.MaxMm > knot.ApproximationToleranceMm)+ diagnostics.Add($"wireform-knot-approximation-limit:{knot.Name}: measured centerline error {knot.ApproximationError.MaxMm:G6} mm exceeds {knot.ApproximationToleranceMm:G6} mm.");+ if (feature.WireRadiusMm + Tolerance.Linear >= knot.Qualification.TubeRadiusLimitMm)+ {+ var code = knot.Qualification.MinimumCurvatureRadiusMm < knot.Qualification.MinimumNonlocalDistanceMm / 2d+ ? "wireform-knot-local-curvature-limit" : "wireform-knot-tube-self-intersection";+ diagnostics.Add($"{code}:{knot.Name}: requested diameter {feature.DiameterMm:G12} mm exceeds the admitted maximum {knot.Qualification.MaximumAdmittedDiameterMm:G12} mm; closest nonlocal parameters t1={knot.Qualification.ClosestParameter1:G9}, t2={knot.Qualification.ClosestParameter2:G9}.");+ }+ }}var clearance = feature.DiameterMm;for (var i = 0; i + 1 < feature.Operations.Count; i++)@@ -386,7 +418,7 @@ public static class WireFormBRepMaterializer{WireStraightAir line => [line.Input.Position, line.Output.Position],WireBendAir bend => Enumerable.Range(0, count + 1).Select(i => bend.Center + Rotate(bend.StartRadial.ToVector(), bend.PlaneNormal.ToVector(), Math.Abs(bend.AngleRadians) * i / count) * bend.RadiusMm).ToArray(),- WireCoilAir coil => Enumerable.Range(0, count + 1).Select(i => coil.Evaluate((double)i / count)).ToArray(),+ WireEvaluablePathAir path => Enumerable.Range(0, count + 1).Select(i => path.Evaluate((double)i / count)).ToArray(),_ => []};private static double SegmentDistance(Point3D p1, Point3D q1, Point3D p2, Point3D q2)@@ -410,12 +442,12 @@ public static class WireFormReportFactoryvar feature = built.Feature;var surfaces = built.Body.Topology.Faces.Select(face => built.Body.GetFaceSurface(face.Id).Kind).ToArray();var operations = feature.Operations.Select(operation => new FirmamentWireOperationReport(- operation.Ordinal, operation.Name, operation switch { WireStraightAir => "Straight", WireBendAir => "Bend", WireAxisCoilAir => "AxisCoil", WireSurfaceCoilAir => "SurfaceCoil", _ => "Unknown" }, operation.LengthMm,+ operation.Ordinal, operation.Name, operation switch { WireStraightAir => "Straight", WireBendAir => "Bend", WireAxisCoilAir => "AxisCoil", WireSurfaceCoilAir => "SurfaceCoil", WireKnotPathAir => "KnotPath", _ => "Unknown" }, operation.LengthMm,operation is WireBendAir bend ? bend.RadiusMm : null,operation is WireBendAir bendAngle ? bendAngle.AngleRadians * 180d / Math.PI : null,operation is WireBendAir bendPlane ? bendPlane.Plane : null, operation.StableId(feature.Name),- State(operation.Input), State(operation.Output), operation switch { WireStraightAir => "LineSegment", WireBendAir => "CircularArc", WireCoilAir => "EvaluableWindingLaw", _ => "Unknown" },- operation switch { WireStraightAir => "Cylinder", WireBendAir => "Torus", WireCoilAir => "NonRationalBSplineTube", _ => "Unknown" },+ State(operation.Input), State(operation.Output), operation switch { WireStraightAir => "LineSegment", WireBendAir => "CircularArc", WireCoilAir => "EvaluableWindingLaw", WireKnotPathAir => "EvaluablePeriodicKnotLaw", _ => "Unknown" },+ operation switch { WireStraightAir => "Cylinder", WireBendAir => "Torus", WireEvaluablePathAir => "NonRationalBSplineTube", _ => "Unknown" },operation is WireCoilAir coil ? coil.CoilKind : null, operation is WireCoilAir turns ? turns.Turns : null,operation is WireCoilAir handed ? handed.Handedness.ToString() : null,operation switch { WireAxisCoilAir axis => axis.PitchMm, WireSurfaceCoilAir surface => surface.AxialPitchMm, _ => null },@@ -426,25 +458,50 @@ public static class WireFormReportFactoryoperation is WireCoilAir progression ? progression.ProgressionLaw : null,operation is WireCoilAir self ? self.MinimumSelfClearanceMm : null,operation is WireCoilAir supportClearance ? supportClearance.SupportClearanceMm : null,- operation is WireCoilAir approximation ? approximation.ApproximationToleranceMm : null,- operation is WireCoilAir segmentCount ? segmentCount.ApproximationSegmentCount : null,- operation is WireCoilAir maximumError ? maximumError.ApproximationError.MaxMm : null,- operation is WireCoilAir rmsError ? rmsError.ApproximationError.RmsMm : null)).ToArray();+ operation is WireEvaluablePathAir approximation ? approximation.ApproximationToleranceMm : null,+ operation is WireEvaluablePathAir segmentCount ? segmentCount.ApproximationSegmentCount : null,+ operation is WireEvaluablePathAir maximumError ? maximumError.ApproximationError.MaxMm : null,+ operation is WireEvaluablePathAir rmsError ? rmsError.ApproximationError.RmsMm : null,+ operation is WireKnotPathAir knot ? knot.Family.ToString() : null,+ operation is WireKnotPathAir knotP ? knotP.P : null,+ operation is WireKnotPathAir knotQ ? knotQ.Q : null,+ operation is WireKnotPathAir knotComponents ? knotComponents.ComponentCount : null,+ operation is WireKnotPathAir knotClosed ? knotClosed.Closed : null,+ operation is WireKnotPathAir knotScale ? knotScale.ScaleMm : null,+ operation is WireKnotPathAir knotMajor ? knotMajor.MajorRadiusMm : null,+ operation is WireKnotPathAir knotMinor ? knotMinor.MinorRadiusMm : null,+ operation is WireKnotPathAir knotMinDistance ? knotMinDistance.Qualification.MinimumNonlocalDistanceMm : null,+ operation is WireKnotPathAir knotMinRadius ? knotMinRadius.Qualification.MinimumCurvatureRadiusMm : null,+ operation is WireKnotPathAir knotLimit ? knotLimit.Qualification.TubeRadiusLimitMm : null,+ operation is WireKnotPathAir knotRawFrame ? knotRawFrame.FrameClosure.RawClosureRotationRadians : null,+ operation is WireKnotPathAir knotCorrection ? knotCorrection.FrameClosure.AppliedCorrectionRadians : null,+ operation is WireKnotPathAir knotFinalFrame ? knotFinalFrame.FrameClosure.FinalClosureErrorRadians : null,+ operation is WireKnotPathAir knotError ? knotError.ApproximationError.MaxMm : null,+ operation is WireKnotPathAir knotRms ? knotRms.ApproximationError.RmsMm : null,+ operation is WireKnotPathAir knotT1 ? knotT1.Qualification.ClosestParameter1 : null,+ operation is WireKnotPathAir knotT2 ? knotT2.Qualification.ClosestParameter2 : null)).ToArray();return new(feature.Name, feature.DiameterMm, feature.Material.Identity.FirmamentPath, feature.Operations.Count,feature.Operations.Count(x => x is WireStraightAir), feature.Operations.Count(x => x is WireBendAir),feature.TotalStraightLengthMm, feature.TotalBendLengthMm, feature.TotalWireLengthMm, built.VolumeMm3, built.MassKilograms,Terminal("TerminalStart", feature.StartState, feature.DiameterMm), Terminal("TerminalEnd", feature.EndState, feature.DiameterMm),feature.Operations.OfType<WireBendAir>().Select(x => x.RadiusMm).DefaultIfEmpty(double.NaN).Min(),"CenterlineRadius", "GeometricOnly: centerline bend radius must exceed Diameter/2",- "Nonadjacent operations use deterministic 3D chord witnesses with arc-sagitta error bounds; contact/overlap fails closed.",+ feature.Operations.Any(x => x is WireKnotPathAir) ? "Closed KnotPath uses deterministic nonlocal periodic separation plus local curvature-radius qualification; excessive tube diameter fails closed." : "Nonadjacent operations use deterministic 3D chord witnesses with arc-sagitta error bounds; contact/overlap fails closed.",feature.FrameTransportPolicy, operations, built.Bounds,surfaces.Count(x => x == SurfaceGeometryKind.Cylinder), surfaces.Count(x => x == SurfaceGeometryKind.Torus),surfaces.Count(x => x == SurfaceGeometryKind.Plane), surfaces.Count(x => x is not (SurfaceGeometryKind.Cylinder or SurfaceGeometryKind.Torus or SurfaceGeometryKind.Plane)),0, 0, true, stepSha256, true, reimportedManifold,feature.Operations.Count(x => x is WireCoilAir), feature.TotalCoilLengthMm,feature.Operations.OfType<WireCoilAir>().Select(x => (double?)x.MinimumSelfClearanceMm).DefaultIfEmpty(null).Min(),- surfaces.Count(x => x == SurfaceGeometryKind.BSplineSurfaceWithKnots), feature.Operations.Any(x => x is WireCoilAir) ? 3 : 0,- feature.Operations.Any(x => x is WireCoilAir) ? "ExactEvaluableWindingLaw->DeterministicCubicNonRationalBSplineTube" : "ExactAnalyticLineArcSweep");+ surfaces.Count(x => x == SurfaceGeometryKind.BSplineSurfaceWithKnots), feature.Operations.Any(x => x is WireEvaluablePathAir) ? 3 : 0,+ feature.Operations.Any(x => x is WireKnotPathAir) ? "ExactEvaluablePeriodicKnotLaw->ClosureCorrectedDeterministicCubicNonRationalBSplineTube" : feature.Operations.Any(x => x is WireCoilAir) ? "ExactEvaluableWindingLaw->DeterministicCubicNonRationalBSplineTube" : "ExactAnalyticLineArcSweep",+ feature.Operations.Count(x => x is WireKnotPathAir), feature.Operations.OfType<WireKnotPathAir>().SingleOrDefault()?.Family.ToString(),+ feature.Operations.OfType<WireKnotPathAir>().SingleOrDefault()?.Qualification.MinimumNonlocalDistanceMm,+ feature.Operations.OfType<WireKnotPathAir>().SingleOrDefault()?.Qualification.MinimumCurvatureRadiusMm,+ feature.Operations.OfType<WireKnotPathAir>().SingleOrDefault()?.Qualification.TubeRadiusLimitMm,+ feature.Operations.OfType<WireKnotPathAir>().SingleOrDefault()?.FrameClosure.FinalClosureErrorRadians,+ built.Body.Topology.Vertices.Count(), built.Body.Topology.Edges.Count(), built.Body.Topology.Faces.Count(),+ built.Body.Bindings.PcurveBindings.Count(), BrepPcurveValidator.Validate(built.Body, 1e-6).MaximumReconstructionDeviation);}private static FirmamentWireStateReport State(WireState state) => new(V(state.Position), V(state.Tangent), V(state.Up), V(state.Right), state.AccumulatedLengthMm);diff --git a/Aetheris.Kernel.Firmament/Materializer/WireKnots.cs b/Aetheris.Kernel.Firmament/Materializer/WireKnots.csnew file mode 100644index 00000000..091a7c6c--- /dev/null+++ b/Aetheris.Kernel.Firmament/Materializer/WireKnots.cs@@ -0,0 +1,325 @@+using System.Globalization;+using Aetheris.Kernel.Core.Brep;+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.Firmament.Materializer;++public enum WireKnotFamily { Trefoil, FigureEight, TorusKnot }++public sealed record WireKnotQualification(+ double MinimumNonlocalDistanceMm,+ double MinimumCurvatureRadiusMm,+ double TubeRadiusLimitMm,+ double MaximumAdmittedDiameterMm,+ double ClosestParameter1,+ double ClosestParameter2,+ double LengthIntegrationErrorMm,+ string Method);++public sealed record WireKnotFrameClosure(+ double RawClosureRotationRadians,+ double AppliedCorrectionRadians,+ double FinalClosureErrorRadians,+ string Policy);++/// <summary>A named, evaluable, inherently periodic mathematical knot centerline.</summary>+public sealed record WireKnotPathAir(+ string Name,+ int Ordinal,+ WireKnotFamily Family,+ int? P,+ int? Q,+ int ComponentCount,+ double ScaleMm,+ double? MajorRadiusMm,+ double? MinorRadiusMm,+ WireCoilHandedness Handedness,+ double PhaseRadians,+ Point3D Origin,+ Direction3D BasisX,+ Direction3D BasisY,+ Direction3D BasisZ,+ WireKnotQualification Qualification,+ WireKnotFrameClosure FrameClosure,+ WireState Input,+ WireState Output,+ double LengthMm,+ double ApproximationToleranceMm,+ int Segments)+ : WireEvaluablePathAir(Name, Ordinal, Input, Output, LengthMm, ApproximationToleranceMm)+{+ public override bool Closed => true;+ public override int ApproximationSegmentCount => Segments;+ public double SeamParameter => 0d;+ public override Point3D Evaluate(double parameter) => WireKnotGeometry.Evaluate(this, parameter);+ public override Direction3D Tangent(double parameter) => Direction3D.Create(WireKnotGeometry.Derivative(this, parameter));+}++internal static class WireKnotAuthoring+{+ private const double ApproximationTolerance = 0.01d;++ internal static KernelResult<WireKnotPathAir> Create(string name, int ordinal, string body, WireState authoredFrame, double diameter)+ {+ var familyText = WireFormAuthoring.Property(body, "Family") ?? name;+ if (!Enum.TryParse<WireKnotFamily>(familyText, false, out var family))+ return Fail("wireform-knot-parameters-invalid", name, "Family must be Trefoil, FigureEight, or TorusKnot.");+ var handText = WireFormAuthoring.Property(body, "Handedness") ?? "RightHanded";+ if (!Enum.TryParse<WireCoilHandedness>(handText, false, out var handedness))+ return Fail("wireform-knot-parameters-invalid", name, "Handedness must be RightHanded or LeftHanded.");+ var phase = 0d;+ var phaseText = WireFormAuthoring.Property(body, "Phase") ?? WireFormAuthoring.Property(body, "StartPhase");+ if (phaseText is not null && !WireFormAuthoring.TryAngle(phaseText, out phase))+ return Fail("wireform-knot-parameters-invalid", name, "Phase must be a finite angle.");++ int? p = null, q = null;+ double scale, major = 0d, minor = 0d;+ if (family == WireKnotFamily.TorusKnot)+ {+ if (!Integer(body, "P", out var pi) || !Integer(body, "Q", out var qi) || pi < 2 || qi < 2)+ return Fail("wireform-knot-parameters-invalid", name, "TorusKnot requires integers P >= 2 and Q >= 2.");+ if (Gcd(pi, qi) != 1)+ return Fail("wireform-knot-not-single-component", name, $"P={pi}, Q={qi} have gcd={Gcd(pi, qi)} and define a link, not one knot component.");+ if (!Length(body, "MajorRadius", out major) || !Length(body, "MinorRadius", out minor) || major <= 0d || minor <= 0d || major <= minor)+ return Fail("wireform-knot-parameters-invalid", name, "TorusKnot requires MajorRadius > MinorRadius > 0.");+ p = pi; q = qi; scale = major;+ }+ else+ {+ if (!Length(body, "Scale", out scale) || scale <= 0d)+ return Fail("wireform-knot-scale-invalid", name, "Scale must be a finite positive length.");+ }++ var basisX = authoredFrame.Tangent;+ var basisZ = authoredFrame.Up;+ var basisY = Direction3D.Create(WireFormAuthoring.Cross(basisZ.ToVector(), basisX.ToVector()));+ var harmonics = family switch { WireKnotFamily.Trefoil => 3, WireKnotFamily.FigureEight => 4, _ => Math.Max(p!.Value, q!.Value) };+ var segments = Math.Max(96, harmonics * 32);+ var emptyQualification = new WireKnotQualification(0d, 0d, 0d, 0d, 0d, 0d, 0d, "pending");+ var emptyClosure = new WireKnotFrameClosure(0d, 0d, 0d, "pending");+ var seed = new WireKnotPathAir(name, ordinal, family, p, q, 1, scale,+ family == WireKnotFamily.TorusKnot ? major : null, family == WireKnotFamily.TorusKnot ? minor : null,+ handedness, phase, authoredFrame.Position, basisX, basisY, basisZ, emptyQualification, emptyClosure,+ authoredFrame, authoredFrame, 0d, ApproximationTolerance, segments);+ var (length, integrationError) = WireKnotGeometry.IntegrateLength(seed);+ var startPoint = seed.Evaluate(0d); var startTangent = seed.Tangent(0d);+ var projectedUp = basisZ.ToVector() - startTangent.ToVector() * WireFormAuthoring.Dot(basisZ.ToVector(), startTangent.ToVector());+ if (projectedUp.Length < 1e-10) projectedUp = basisY.ToVector() - startTangent.ToVector() * WireFormAuthoring.Dot(basisY.ToVector(), startTangent.ToVector());+ var startState = new WireState(startPoint, startTangent, Direction3D.Create(projectedUp), authoredFrame.AccumulatedLengthMm);+ seed = seed with { Input = startState, Output = startState with { AccumulatedLengthMm = authoredFrame.AccumulatedLengthMm + length }, LengthMm = length };+ var qualification = WireKnotGeometry.Qualify(seed, integrationError);+ var closure = WireKnotGeometry.MeasureFrameClosure(seed);+ return KernelResult<WireKnotPathAir>.Success(seed with { Qualification = qualification, FrameClosure = closure });+ }++ private static bool Length(string body, string name, out double value) => WireFormAuthoring.TryLength(WireFormAuthoring.Property(body, name), out value);+ private static bool Integer(string body, string name, out int value) => int.TryParse(WireFormAuthoring.Property(body, name), NumberStyles.Integer, CultureInfo.InvariantCulture, out value);+ private static int Gcd(int a, int b) { while (b != 0) (a, b) = (b, a % b); return Math.Abs(a); }+ private static KernelResult<WireKnotPathAir> Fail(string code, string name, string message) => KernelResult<WireKnotPathAir>.Failure([new(+ Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Core.Diagnostics.KernelDiagnosticSeverity.Error,+ $"{code}:{name}: {message}", "FirmamentV2.WireForm.KnotPath")]);+}++public static class WireKnotGeometry+{+ public static Point3D Evaluate(WireKnotPathAir knot, double t)+ {+ var (p, _, _) = Jet(knot, t);+ return knot.Origin + Transform(knot, p);+ }++ public static Vector3D Derivative(WireKnotPathAir knot, double t)+ {+ var (_, d1, _) = Jet(knot, t);+ return Transform(knot, d1);+ }++ private static Vector3D SecondDerivative(WireKnotPathAir knot, double t)+ {+ var (_, _, d2) = Jet(knot, t);+ return Transform(knot, d2);+ }++ private static (Vector3D P, Vector3D D1, Vector3D D2) Jet(WireKnotPathAir knot, double t)+ {+ var a = 2d * Math.PI * t + knot.PhaseRadians;+ var w = 2d * Math.PI;+ var mirror = knot.Handedness == WireCoilHandedness.RightHanded ? 1d : -1d;+ if (knot.Family == WireKnotFamily.Trefoil)+ {+ var s = knot.ScaleMm;+ return (new((Math.Sin(a) + 2d * Math.Sin(2d * a)) * s, (Math.Cos(a) - 2d * Math.Cos(2d * a)) * s, -mirror * Math.Sin(3d * a) * s),+ new((Math.Cos(a) + 4d * Math.Cos(2d * a)) * w * s, (-Math.Sin(a) + 4d * Math.Sin(2d * a)) * w * s, -mirror * 3d * Math.Cos(3d * a) * w * s),+ new((-Math.Sin(a) - 8d * Math.Sin(2d * a)) * w * w * s, (-Math.Cos(a) + 8d * Math.Cos(2d * a)) * w * w * s, mirror * 9d * Math.Sin(3d * a) * w * w * s));+ }+ if (knot.Family == WireKnotFamily.FigureEight)+ {+ var s = knot.ScaleMm; var r = 2d + Math.Cos(2d * a); var rp = -2d * Math.Sin(2d * a); var rpp = -4d * Math.Cos(2d * a);+ var x = r * Math.Cos(3d * a); var y = r * Math.Sin(3d * a); var z = mirror * Math.Sin(4d * a);+ var xa = rp * Math.Cos(3d * a) - 3d * r * Math.Sin(3d * a); var ya = rp * Math.Sin(3d * a) + 3d * r * Math.Cos(3d * a); var za = mirror * 4d * Math.Cos(4d * a);+ var xaa = rpp * Math.Cos(3d * a) - 6d * rp * Math.Sin(3d * a) - 9d * r * Math.Cos(3d * a); var yaa = rpp * Math.Sin(3d * a) + 6d * rp * Math.Cos(3d * a) - 9d * r * Math.Sin(3d * a); var zaa = -mirror * 16d * Math.Sin(4d * a);+ return (new(x * s, y * s, z * s), new(xa * w * s, ya * w * s, za * w * s), new(xaa * w * w * s, yaa * w * w * s, zaa * w * w * s));+ }+ var p = knot.P!.Value; var q = knot.Q!.Value; var major = knot.MajorRadiusMm!.Value; var minor = knot.MinorRadiusMm!.Value;+ var radial = major + minor * Math.Cos(q * a); var radialA = -minor * q * Math.Sin(q * a); var radialAA = -minor * q * q * Math.Cos(q * a);+ var x0 = radial * Math.Cos(p * a); var y0 = radial * Math.Sin(p * a); var z0 = mirror * minor * Math.Sin(q * a);+ var x1 = radialA * Math.Cos(p * a) - p * radial * Math.Sin(p * a); var y1 = radialA * Math.Sin(p * a) + p * radial * Math.Cos(p * a); var z1 = mirror * minor * q * Math.Cos(q * a);+ var x2 = radialAA * Math.Cos(p * a) - 2d * p * radialA * Math.Sin(p * a) - p * p * radial * Math.Cos(p * a); var y2 = radialAA * Math.Sin(p * a) + 2d * p * radialA * Math.Cos(p * a) - p * p * radial * Math.Sin(p * a); var z2 = -mirror * minor * q * q * Math.Sin(q * a);+ return (new(x0, y0, z0), new(x1 * w, y1 * w, z1 * w), new(x2 * w * w, y2 * w * w, z2 * w * w));+ }++ internal static (double Length, double Error) IntegrateLength(WireKnotPathAir knot)+ {+ double Simpson(int n)+ {+ var total = Derivative(knot, 0d).Length + Derivative(knot, 1d).Length;+ for (var i = 1; i < n; i++) total += (i % 2 == 0 ? 2d : 4d) * Derivative(knot, (double)i / n).Length;+ return total / (3d * n);+ }+ var coarse = Simpson(4096); var fine = Simpson(8192);+ return (fine, Math.Abs(fine - coarse) / 15d);+ }++ internal static WireKnotQualification Qualify(WireKnotPathAir knot, double integrationError)+ {+ const int count = 1024; const double safety = 1e-4;+ var points = Enumerable.Range(0, count).Select(i => knot.Evaluate((double)i / count)).ToArray();+ // Exclude one eighth of the periodic domain in either direction. This is a+ // deliberately bounded nonlocal witness: it excludes the same smooth strand+ // and its seam-neighbourhood rather than mistaking nearby arclength for a+ // distinct crossing branch.+ var exclusion = count / 8; var best = double.PositiveInfinity; var bestI = 0; var bestJ = 0;+ for (var i = 0; i < count; i++) for (var j = i + 1; j < count; j++)+ {+ var cyclic = Math.Min(j - i, count - (j - i));+ if (cyclic < exclusion) continue;+ var distance = (points[i] - points[j]).Length;+ if (distance < best) { best = distance; bestI = i; bestJ = j; }+ }+ var chordError = 0d;+ for (var i = 0; i < count; i++)+ {+ var midpoint = knot.Evaluate((i + .5d) / count); var chordMidpoint = points[i] + (points[(i + 1) % count] - points[i]) * .5d;+ chordError = Math.Max(chordError, (midpoint - chordMidpoint).Length);+ }+ var conservativeDistance = Math.Max(0d, best - 2d * chordError);+ var minCurvature = double.PositiveInfinity;+ for (var i = 0; i < 8192; i++)+ {+ var t = (double)i / 8192; var d1 = Derivative(knot, t); var d2 = SecondDerivative(knot, t);+ var cross = WireFormAuthoring.Cross(d1, d2).Length;+ if (cross > 1e-20) minCurvature = Math.Min(minCurvature, d1.Length * d1.Length * d1.Length / cross);+ }+ var limit = Math.Min(conservativeDistance / 2d, minCurvature);+ return new(conservativeDistance, minCurvature, limit, Math.Max(0d, 2d * (limit - safety)),+ (double)bestI / count, (double)bestJ / count, integrationError,+ "Deterministic sampled conservative chord bound; approximate tube admissibility, not a formal reach proof");+ }++ internal static WireKnotFrameClosure MeasureFrameClosure(WireKnotPathAir knot)+ {+ var initial = knot.Input.Up.ToVector(); var up = initial; var previous = knot.Tangent(0d).ToVector();+ var count = knot.ApproximationSegmentCount;+ for (var i = 1; i <= count; i++)+ {+ var next = knot.Tangent((double)i / count).ToVector(); up = WireCoilGeometry.RotateFromTo(up, previous, next);+ up = Direction3D.Create(up - next * WireFormAuthoring.Dot(up, next)).ToVector(); previous = next;+ }+ var tangent = knot.Tangent(0d).ToVector(); var raw = SignedAngle(initial, up, tangent); var correction = -raw;+ var corrected = WireCoilGeometry.Rotate(up, tangent, correction); var final = Math.Abs(SignedAngle(initial, corrected, tangent));+ return new(raw, correction, final, "Rotation-minimizing transport with deterministic linear distributed holonomy correction");+ }++ internal static double SignedAngle(Vector3D from, Vector3D to, Vector3D axis)+ => Math.Atan2(WireFormAuthoring.Dot(axis, WireFormAuthoring.Cross(from, to)), WireFormAuthoring.Dot(from, to));+ private static Vector3D Transform(WireKnotPathAir knot, Vector3D local)+ => knot.BasisX.ToVector() * local.X + knot.BasisY.ToVector() * local.Y + knot.BasisZ.ToVector() * local.Z;+}++internal static class WireKnotBRepMaterializer+{+ private sealed record Station(Point3D Point, Direction3D Tangent, Direction3D Up);++ internal static KernelResult<WireFormBuildResult> Build(WireFormFeatureAir feature)+ {+ try+ {+ var knot = (WireKnotPathAir)feature.Operations.Single();+ var diagnostics = WireFormBRepMaterializer.Validate(feature);+ if (diagnostics.Count > 0) return KernelResult<WireFormBuildResult>.Failure(diagnostics.Select(Diagnostic).ToArray());+ var stations = Stations(knot); var r = feature.WireRadiusMm;+ var builder = new TopologyBuilder(); var geometry = new BrepGeometryStore(); var bindings = new BrepBindingModel(); var points = new Dictionary<VertexId, Point3D>(); var curves = 1; var surfaces = 1;+ var vertices = new VertexId[stations.Count, 4]; var rings = new EdgeId[stations.Count, 4]; var ringControls = new Point3D[stations.Count, 4][];+ for (var i = 0; i < stations.Count; i++)+ {+ var right = Direction3D.Create(WireFormAuthoring.Cross(stations[i].Tangent.ToVector(), stations[i].Up.ToVector()));+ for (var q = 0; q < 4; q++) { var controls = Quarter(stations[i].Point, stations[i].Up, right, r, q); ringControls[i, q] = controls; vertices[i, q] = builder.AddVertex(); points[vertices[i, q]] = controls[0]; }+ for (var q = 0; q < 4; q++) { rings[i, q] = builder.AddEdge(vertices[i, q], vertices[i, (q + 1) % 4]); geometry.AddCurve(new(curves), CurveGeometry.FromBSpline(Bezier(ringControls[i, q]))); bindings.AddEdgeBinding(new(rings[i, q], new(curves++), new ParameterInterval(0, 1))); }+ }+ var faces = new List<FaceId>();+ for (var i = 0; i < stations.Count; i++)+ {+ var next = (i + 1) % stations.Count; var center = CenterBezier(stations[i], stations[next], knot, i); var nets = new Point3D[4][][];+ for (var q = 0; q < 4; q++)+ {+ var net = new Point3D[4][];+ for (var u = 0; u < 4; u++)+ {+ var alpha = u / 3d; var tangent = Direction3D.Create(stations[i].Tangent.ToVector() * (1d - alpha) + stations[next].Tangent.ToVector() * alpha);+ var upVector = stations[i].Up.ToVector() * (1d - alpha) + stations[next].Up.ToVector() * alpha; var up = Direction3D.Create(upVector - tangent.ToVector() * WireFormAuthoring.Dot(upVector, tangent.ToVector()));+ net[u] = Quarter(center[u], up, Direction3D.Create(WireFormAuthoring.Cross(tangent.ToVector(), up.ToVector())), r, q);+ }+ nets[q] = net;+ }+ var longitudinal = new EdgeId[4];+ for (var q = 0; q < 4; q++) { longitudinal[q] = builder.AddEdge(vertices[i, q], vertices[next, q]); geometry.AddCurve(new(curves), CurveGeometry.FromBSpline(Bezier(nets[q].Select(row => row[0]).ToArray()))); bindings.AddEdgeBinding(new(longitudinal[q], new(curves++), new ParameterInterval(0, 1))); }+ for (var q = 0; q < 4; q++)+ {+ var surfaceId = new SurfaceGeometryId(surfaces++); geometry.AddSurface(surfaceId, SurfaceGeometry.FromBSplineSurfaceWithKnots(new(3, 3, nets[q], "UNSPECIFIED", false, false, false, [4, 4], [4, 4], [0d, 1d], [0d, 1d], "UNSPECIFIED")));+ var (face, coedges) = AddFace(builder, [(longitudinal[q], false), (rings[next, q], false), (longitudinal[(q + 1) % 4], true), (rings[i, q], true)]); bindings.AddFaceBinding(new(face, surfaceId)); faces.Add(face);+ AddPcurve(bindings, coedges[0], face, surfaceId, new(0, 0), new(1, 0)); AddPcurve(bindings, coedges[1], face, surfaceId, new(1, 0), new(1, 1));+ AddPcurve(bindings, coedges[2], face, surfaceId, new(0, 1), new(1, 1)); AddPcurve(bindings, coedges[3], face, surfaceId, new(0, 0), new(0, 1));+ }+ }+ var shell = builder.AddShell(faces); builder.AddBody([shell]); var body = new BrepBody(builder.Model, geometry, bindings, points);+ var bindingValidation = BrepBindingValidator.Validate(body, true); if (!bindingValidation.IsSuccess) return KernelResult<WireFormBuildResult>.Failure(bindingValidation.Diagnostics);+ var pcurves = BrepPcurveValidator.Validate(body, 1e-6, true); if (!pcurves.IsValid) return KernelResult<WireFormBuildResult>.Failure(pcurves.Diagnostics.Select(Diagnostic).ToArray());+ var preflight = BrepExportPreflight.Validate(body); if (!preflight.IsValid) return KernelResult<WireFormBuildResult>.Failure(preflight.Diagnostics.Where(x => x.Severity == BrepExportPreflightSeverity.Error).Select(x => Diagnostic($"wireform-knot-brep-invalid:{x.Code}:{x.Message}")).ToArray());+ var samples = Enumerable.Range(0, 2048).Select(i => knot.Evaluate((double)i / 2048)).ToArray(); var bounds = new[] { samples.Min(p => p.X) - r, samples.Min(p => p.Y) - r, samples.Min(p => p.Z) - r, samples.Max(p => p.X) + r, samples.Max(p => p.Y) + r, samples.Max(p => p.Z) + r };+ var volume = Math.PI * r * r * knot.LengthMm; var mass = volume * 1e-9 * feature.Material.Structural!.Density.SiValue;+ return KernelResult<WireFormBuildResult>.Success(new(feature, body, volume, mass, bounds,+ ["wireform-knot-periodic-semantic-centerline", "wireform-knot-frame-holonomy-corrected", $"wireform-knot-pcurves:{pcurves.PcurveCount}:max-error={pcurves.MaximumReconstructionDeviation:R}", "wireform-knot-non-rational-bspline-sweep", "wireform-knot-no-terminal-caps"]));+ }+ catch (Exception exception) when (exception is ArgumentException or InvalidOperationException)+ { return KernelResult<WireFormBuildResult>.Failure([Diagnostic("wireform-knot-brep-construction-failed: " + exception.Message)]); }+ }++ private static List<Station> Stations(WireKnotPathAir knot)+ {+ var result = new List<Station>(); var count = knot.ApproximationSegmentCount; var up = knot.Input.Up.ToVector(); var previous = knot.Tangent(0d).ToVector(); var correction = knot.FrameClosure.AppliedCorrectionRadians;+ for (var i = 0; i < count; i++)+ {+ var t = (double)i / count; var tangent = knot.Tangent(t);+ if (i > 0) up = WireCoilGeometry.RotateFromTo(up, previous, tangent.ToVector());+ up = Direction3D.Create(up - tangent.ToVector() * WireFormAuthoring.Dot(up, tangent.ToVector())).ToVector();+ var corrected = WireCoilGeometry.Rotate(up, tangent.ToVector(), correction * t); result.Add(new(knot.Evaluate(t), tangent, Direction3D.Create(corrected))); previous = tangent.ToVector();+ }+ return result;+ }++ private static Point3D[] CenterBezier(Station a, Station b, WireKnotPathAir knot, int span)+ {+ var dt = 1d / knot.ApproximationSegmentCount; var t0 = (double)span / knot.ApproximationSegmentCount; var t1 = (double)(span + 1) / knot.ApproximationSegmentCount;+ var p0 = knot.Evaluate(t0); var p1 = knot.Evaluate(t1); return [p0, p0 + WireKnotGeometry.Derivative(knot, t0) * (dt / 3d), p1 - WireKnotGeometry.Derivative(knot, t1) * (dt / 3d), p1];+ }+ private static Point3D[] Quarter(Point3D center, Direction3D up, Direction3D right, double radius, int quarter) { var a = quarter * Math.PI / 2d; var b = a + Math.PI / 2d; const double k = .5522847498307936; Vector3D E(double x) => up.ToVector() * Math.Cos(x) + right.ToVector() * Math.Sin(x); Vector3D D(double x) => up.ToVector() * -Math.Sin(x) + right.ToVector() * Math.Cos(x); return [center + E(a) * radius, center + (E(a) + D(a) * k) * radius, center + (E(b) - D(b) * k) * radius, center + E(b) * radius]; }+ private static BSpline3Curve Bezier(IReadOnlyList<Point3D> controls) => new(3, controls, [4, 4], [0d, 1d], "UNSPECIFIED", false, false, "UNSPECIFIED");+ private static (FaceId Face, CoedgeId[] Coedges) AddFace(TopologyBuilder builder, IReadOnlyList<(EdgeId Edge, bool Reversed)> uses) { var loop = builder.AllocateLoopId(); var ids = uses.Select(_ => builder.AllocateCoedgeId()).ToArray(); for (var i = 0; i < uses.Count; i++) builder.AddCoedge(new(ids[i], uses[i].Edge, loop, ids[(i + 1) % ids.Length], ids[(i + ids.Length - 1) % ids.Length], uses[i].Reversed)); builder.AddLoop(new Loop(loop, ids)); return (builder.AddFace([loop]), ids); }+ private static void AddPcurve(BrepBindingModel bindings, CoedgeId coedge, FaceId face, SurfaceGeometryId surface, SurfaceParameterPoint start, SurfaceParameterPoint end) => bindings.AddPcurveBinding(new(coedge, face, surface, PcurveGeometry.Line(new(0, 1), start, end)));+ private static Core.Diagnostics.KernelDiagnostic Diagnostic(string message) => new(Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Core.Diagnostics.KernelDiagnosticSeverity.Error, message, "FirmamentV2.WireForm.KnotPath");+}diff --git a/Aetheris.SheetMetal.Tests/SheetMetalMaterialAreaAuthorityTests.cs b/Aetheris.SheetMetal.Tests/SheetMetalMaterialAreaAuthorityTests.csnew file mode 100644index 00000000..876ace59--- /dev/null+++ b/Aetheris.SheetMetal.Tests/SheetMetalMaterialAreaAuthorityTests.cs@@ -0,0 +1,58 @@+using Aetheris.Kernel.Firmament.Materializer;+using Xunit;++namespace Aetheris.SheetMetal.Tests;++public sealed class SheetMetalMaterialAreaAuthorityTests+{+ [Fact]+ public void AddProfileDelta_IncreasesAreaFromFinalExactRegion()+ {+ var result=Compile("profiledelta-add-area.firmament");+ var wall=Assert.Single(result.Part!.Regions,x=>x.StableId=="Wall");+ Assert.NotNull(wall.ExactContour);+ Assert.Equal(3590d,PlanarContourKernel.Area(wall.ExactContour!),8);+ Assert.Equal(3590d,wall.ApproximateArea,8);+ Assert.NotNull(result.FlatPattern!.ExactBlankContour);+ Assert.Equal(PlanarContourKernel.Area(result.FlatPattern.ExactBlankContour!),result.FlatPattern.MaterialArea!.Value,10);+ Assert.True(result.FlatPattern.MaterialArea<result.FlatPattern.BoundingArea);+ }++ [Fact]+ public void RemoveProfileDelta_DecreasesAreaFromFinalExactRegion()+ {+ var result=Compile("profiledelta-remove-area.firmament");+ var wall=Assert.Single(result.Part!.Regions,x=>x.StableId=="Wall");+ Assert.NotNull(wall.ExactContour);+ Assert.Equal(3410d,PlanarContourKernel.Area(wall.ExactContour!),8);+ Assert.Equal(3410d,wall.ApproximateArea,8);+ Assert.Equal(PlanarContourKernel.Area(result.FlatPattern!.ExactBlankContour!),result.FlatPattern.MaterialArea!.Value,10);+ }++ [Fact]+ public void InnerCut_IsSubtractedByExactContourIntegration()+ {+ var outer=PlanarContourKernel.FromPolygon("outer","XY",[(0,0),(20,0),(20,10),(0,10)],"test");+ var inner=PlanarContourKernel.FromPolygon("inner","XY",[(5,2),(9,2),(9,5),(5,5)],"test").OuterLoop with { IsOuter=false,Segments=PlanarContourKernel.FromPolygon("inner-reverse","XY",[(5,5),(9,5),(9,2),(5,2)],"test").OuterLoop.Segments };+ var contour=outer with { InnerLoops=[inner] };+ Assert.Equal(188d,PlanarContourKernel.Area(contour),10);+ }++ [Fact]+ public void AddProfileDeltaAndHole_ComposeInOneFinalMaterialRegion()+ {+ var tab=Compile("profiledelta-add-area.firmament");+ var tabAndHole=Compile("profiledelta-add-hole-area.firmament");+ Assert.Equal(tab.FlatPattern!.MaterialArea!.Value-Math.PI*4d*4d,tabAndHole.FlatPattern!.MaterialArea!.Value,8);+ Assert.Single(tabAndHole.FlatPattern.CutLoops);+ Assert.Single(tabAndHole.FlatPattern.ExactBlankContour!.InnerLoops);+ }++ private static SheetMetalAuthoringResult Compile(string fixture)+ {+ var path=Path.GetFullPath(Path.Combine(AppContext.BaseDirectory,"../../../../fixtures/Canonical/SheetMetal",fixture));+ var result=SheetMetalFirmament.Compile(File.ReadAllText(path));+ Assert.True(result.IsSuccess,string.Join("; ",result.Diagnostics.Select(x=>$"{x.Code}:{x.Message}")));+ return result;+ }+}diff --git a/Aetheris.SheetMetal/SheetMetalAuthoredLowering.cs b/Aetheris.SheetMetal/SheetMetalAuthoredLowering.csindex fac65d9c..47f60aa9 100644--- a/Aetheris.SheetMetal/SheetMetalAuthoredLowering.cs+++ b/Aetheris.SheetMetal/SheetMetalAuthoredLowering.cs@@ -490,8 +490,12 @@ internal static class AuthoredSheetMetalLoweringcorrespondence.Add(new(corner.Source.CornerPath,"ProfileCorner",corner.Source.CornerPath,$"flat-{corner.Source.CornerPath}"));var plane = new SheetPlaneReference(tangentA, normal, axis, direction, true);var flangeId=stableRegions[flange.Name];- var fragmentArea=tabs.Sum(x=>x.Width*x.Extension)-steppedNotches.Sum(x=>x.Width*x.Depth)-profileDeltas.Sum(x=>DeltaArea(x.Program));- regions.Add(new(flangeId, SheetRegionKind.Planar, Developable("Authored planar flange."), plane, null, boundary, (edge.B-edge.A).Length * flange.Length+fragmentArea, source, evidence,exactContour));+ // The resolved exact contour is the material-region authority. It+ // already contains tabs, notches, ProfileDelta overlap/clipping, and+ // corner programs; reconstructing a signed feature-area ledger here+ // previously treated every ProfileDelta as a removal.+ var materialArea=PlanarContourKernel.Area(exactContour);+ regions.Add(new(flangeId, SheetRegionKind.Planar, Developable("Authored planar flange."), plane, null, boundary, materialArea, source, evidence,exactContour));patches.Add(PlanePatch(flangeId, SheetRegionKind.Planar, boundary, normal, t,plane,exactContour));// Bend termination is finite bend-strip authority. It must not@@ -651,11 +655,6 @@ internal static class AuthoredSheetMetalLowering};return delta with { Anchor=anchor,Side=-delta.Side,Members=reversed };}- private static double DeltaArea(SemanticProfileDeltaIr delta)- {- var levels=delta.Levels.ToDictionary(level=>level.Name,level=>Math.Abs(level.Offset),StringComparer.Ordinal);var current=0d;var area=0d;- foreach(var member in delta.Members){var target=levels.GetValueOrDefault(member.ToLevel);area+=(current+target)*member.Run/2d;current=target;}return area;- }private static (double X,double Y) End(LineArcProfileCurve2D curve)=>curve switch{LineArcLineSegment2D line=>line.End,diff --git a/Aetheris.SheetMetal/SheetMetalIr.cs b/Aetheris.SheetMetal/SheetMetalIr.csindex 597f3be6..dd9e0b0b 100644--- a/Aetheris.SheetMetal/SheetMetalIr.cs+++ b/Aetheris.SheetMetal/SheetMetalIr.cs@@ -344,7 +344,13 @@ public sealed record SheetMetalFlatPatternIr(string DeterministicHash,PlanarContour2? ExactBlankContour = null,IReadOnlyList<FlatReliefLoop>? ReliefLoops = null,- BlankCompositionPlan? CompositionPlan = null);+ BlankCompositionPlan? CompositionPlan = null)+{+ /// <summary>Actual material area from the authoritative final flat region.</summary>+ public double? MaterialArea => ExactBlankContour is null ? null : PlanarContourKernel.Area(ExactBlankContour);+ /// <summary>Rectangular nesting envelope area; not material usage.</summary>+ public double? BoundingArea => Bounds is null ? null : Bounds.Width * Bounds.Height;+}public sealed record SheetMetalRecognitionResult(SheetMetalPartIr? Part,diff --git a/docs/public/firmament/geometry.md b/docs/public/firmament/geometry.mdindex 734ff208..29606c53 100644--- a/docs/public/firmament/geometry.md+++ b/docs/public/firmament/geometry.md@@ -19,7 +19,7 @@ Compose Body {}```-The active Compose body is the semantic target; `On: Top` is its admitted support face. The boss footprint must overlap the host with a proper connected region. A disjoint or point-tangent footprint, missing profile, unsupported support, or non-positive height fails with a `firmament-boss-*` diagnostic. Boss retains a stable `boss:<host>.<name>` identity, then lowers to the existing section-stack `Add` operation. It never emits an arbitrary second solid and does not introduce public Boolean authoring.+The active Compose body is the semantic target. Relative `On: Top` resolves against the current semantic body state under the authored footprint: a later Boss over an earlier Boss therefore starts at the earlier Boss top, while a feature elsewhere on an exposed base plateau still resolves that plateau. Equal highest semantic supports fail with `feature-support-ambiguous:Top`; topology order is never a tie-break. Named `<feature>.Top` retains explicit support identity, and `Base.Top` explicitly selects the original Base operation. The boss footprint must overlap the selected support with a proper connected region. A disjoint or point-tangent footprint, missing profile, unsupported support, or non-positive height fails typed. Boss retains a stable `boss:<host>.<name>` identity, then lowers to the existing section-stack `Add` operation. It never emits an arbitrary second solid and does not introduce public Boolean authoring.### Complete Boss + through-hole source@@ -114,7 +114,7 @@ Model PocketBlock {}```-To author a block containing both features, declare all three profiles in one `Concept Struct ... On XY`, then place both the documented `Boss` and `Pocket` declarations after the unique `Base` in the same Compose. Feature declaration order does not replace their explicit finite intervals. Apply post-construction `EdgeFinish` in `Modify Body`; its semantic profile target is such as `BaseProfile.Outer`, not the primitive-only `Boundary` selector.+To author a block containing both features, declare all three profiles in one `Concept Struct ... On XY`, then place both the documented `Boss` and `Pocket` declarations after the unique `Base` in the same Compose. `Base` cardinality is validated explicitly; zero or multiple Base operations produce `compose-role-cardinality:Base:expected=1:actual=<n>`, never a raw LINQ exception. Apply post-construction `EdgeFinish` in `Modify Body`; its semantic profile target is such as `BaseProfile.Outer`, not the primitive-only `Boundary` selector.The canonical [Boss + Pocket block](../../../fixtures/Canonical/Features/Boss/boss-pocket-block.firmament) combines a cylindrical boss, through shaft hole, and shallow rectangular pocket using public Firmament only. The focused [rectangular Pocket](../../../fixtures/Canonical/Features/Pocket/rectangular-pocket.firmament) reinforces finite depth and minimum-floor intent. Existing lower-level `Compose Add` / `Remove` remains compatible for bounded blockout work.diff --git a/docs/public/firmament/mathematical-knots.md b/docs/public/firmament/mathematical-knots.mdnew file mode 100644index 00000000..896c5485--- /dev/null+++ b/docs/public/firmament/mathematical-knots.md@@ -0,0 +1,45 @@+# Mathematical Knot WireForms++`Knot` authors a named smooth closed mathematical curve as a constant-diameter WireForm tube. It describes a geometric sculpture, not the physical process of tying rope or bending and welding stock. Contact, friction, tightening, elastic deformation, and a closure manufacturing method are unspecified.++```firmament+WireForm Knot1 {+ Diameter: 6mm+ Material: Standard.Materials.StainlessSteel.304_Annealed+ StartFrame { Origin: [0mm,0mm,0mm]; Tangent: [1,0,0]; Up: [0,0,1] }+ Knot Sculpture {+ Family: Trefoil+ Scale: 20mm+ Handedness: RightHanded+ Phase: 0deg+ }+}+```++WIRE-X2 supports `Trefoil`, `FigureEight`, and bounded `TorusKnot` families. `StartFrame` is the rigid placement frame: its origin locates the canonical curve center and its tangent/up axes orient the canonical x/z axes. `Phase` moves the stable semantic seam around the same periodic family. `Handedness` mirrors the canonical z coordinate; it preserves explicit Trefoil chirality instead of asking an agent to infer it from geometry.++The exact parameterizations use `a = 2πt + Phase`, with periodic `t` and seam `t = 0`:++- Trefoil: `Scale × (sin(a)+2sin(2a), cos(a)-2cos(2a), -sin(3a))` for right-handed authoring; left-handed mirrors z.+- FigureEight: `Scale × ((2+cos(2a))cos(3a), (2+cos(2a))sin(3a), sin(4a))`. This is the mathematical figure-eight knot embedding, not a planar figure-eight curve.+- TorusKnot: `((R+r cos(Qa))cos(Pa), (R+r cos(Qa))sin(Pa), r sin(Qa))`, authored with `MajorRadius: R`, `MinorRadius: r`, and coprime integers `P,Q >= 2`.++`TorusKnot` rejects non-coprime P/Q because those parameters define a multi-component torus link. X2 does not silently label a link as a knot and does not yet materialize multi-component WireForms.++## Tube qualification++A mathematical knot can be a valid centerline while still being impossible to realize with thick wire. Aetheris checks both local curvature and nonlocal strand spacing before sweeping the tube. It reports a conservative sampled nonlocal separation, its approximate parameter pair, the minimum sampled local curvature radius, and:++```text+TubeRadiusLimit = min(MinimumNonlocalDistance / 2, MinimumLocalCurvatureRadius)+```++The requested wire radius must stay below that limit with numeric margin. Excess thickness fails with a typed diagnostic and produces no STEP. This is deterministic approximate tube-admissibility evidence, not a formal proof of geometric reach. Knot identity comes from the authored semantic family; Aetheris does not claim to reconstruct or prove knot type from sampled BRep geometry.++## Closed frames and representation++On a closed 3D path, transporting a section frame around one loop can accumulate rotation. Aetheris measures that closure rotation and distributes a deterministic correction so the swept wire closes without a twist seam. Inspection reports the raw mismatch, applied distributed correction, and final closure error. The method is rotation-minimizing parallel transport rather than a Frenet-only frame, so inflections do not introduce a Frenet flip.++The semantic curve is evaluable and periodic; control points are never authoring authority. Materialization uses stable-seam cubic non-rational B-spline centerline/tube patches, four polynomial quarter-section patches per span, shared closed topology, and face-local pcurves. There are no terminal caps, rational product surfaces, or faceted fallback. Ideal stock length is deterministic numerical integration of the semantic centerline; circular area times length gives volume, and catalog density gives mass. Forming strain and closure joining are not modeled.++Canonical sources are the [Trefoil](../../../fixtures/Canonical/WireForm/Knot/trefoil.firmament), [Figure Eight](../../../fixtures/Canonical/WireForm/Knot/figure-eight.firmament), and [(3,5) Torus Knot](../../../fixtures/Canonical/WireForm/Knot/torus-knot-3-5.firmament). `aetheris inspect source.firmament --json` exposes family identity, P/Q, component count, closure, length, clearance, frame, approximation, and stock evidence. `aetheris build` emits deterministic AP242 STEP.diff --git a/docs/public/firmament/sheet-metal.md b/docs/public/firmament/sheet-metal.mdindex 58d320ff..a1d3c9a9 100644--- a/docs/public/firmament/sheet-metal.md+++ b/docs/public/firmament/sheet-metal.md@@ -36,6 +36,8 @@ aetheris sheetmetal flatten fixtures/Canonical/SheetMetal/l-bracket-with-hole.fi[`profile-delta-tab-family.firmament`](../../../fixtures/Canonical/SheetMetal/profile-delta-tab-family.firmament) is the modern data-driven profile example: a finite Table selects `ProfileTabSpec`, `with` derives the shop variant, and the standard-library `ProfileDelta Tab` modifies the wall edge while preserving formed/flat semantic identity.+Flat inspection distinguishes `MaterialArea` from `BoundingArea`. `MaterialArea` is exact line/arc integration of the final flat material contour after additive ProfileDelta regions, notches, holes, cutouts, and overlap clipping. `BoundingArea` is only the rectangular nesting envelope. If no validated exact blank contour exists, material area is reported as unavailable rather than reconstructed from feature bookkeeping.+Sheet Metal holes use `Hole Mount { On: Base; Center: (40mm, 20mm); Diameter: 8mm; }`. Model-domain `Hole<Shaft>` is deliberately rejected here with `sheetmetal-hole-domain-syntax`. `On` targets a named planar semantic region (`Base`, a named flange, or a verified exposed region/path), not `face(+Z)`. Manufacturing PMI likewise uses `DatumFeature A { Target: Base; }` inside `Pmi`, together with a named `Manufacturing` block; Model-domain `Datum`/`face(-Z)` syntax is rejected with `sheetmetal-pmi-domain-syntax`.The JSON `part.features` count is the number of lowered cuts/openings in `SheetMetalPartIr`; bends are reported separately as `part.bends`. Authoring and imported reconstruction are separate workflows. Commands such as `sheetmetal recognize`, `recover-flat`, and `recover` operate on imported STEP and may be partial; they do not turn arbitrary geometry into authoritative authored intent.diff --git a/docs/public/firmament/wire-form.md b/docs/public/firmament/wire-form.mdindex 7fba05fe..2f1c3759 100644--- a/docs/public/firmament/wire-form.md+++ b/docs/public/firmament/wire-form.md@@ -59,7 +59,7 @@ SurfaceCoil Winding {The semantic/evaluable winding law remains authoritative. Coil-containing forms lower through deterministic rotation-minimal frame transport to cubic non-rational B-spline tube patches and planar caps; STEP uses no rational product surfaces and no faceted fallback. Coil-free forms still use exact cylinders and tori. The current approximation uses 32 longitudinal cubic spans per turn and four cubic polynomial quarter patches around the circular section; the compiler measures maximum/RMS centerline error against the winding law and fails if its 0.01 mm bound is exceeded.-X1 supports one continuous, unbranched, open wire with constant circular section. It does not support arbitrary/freeform supports, variable pitch or section, intentional turn contact, spring mechanics, contact dynamics, knots, branching, or closed-wire authoring. Surface support identity is authored rather than imported-face-ID based. Direct `Concept Path` plus `Sweep` remains the lower-level choice for explicitly authored line/arc trajectories.+X1 coils remain continuous, unbranched, open paths. WIRE-X2 adds a distinct closed `Knot` operation for named mathematical knot families; it does not turn coils into closed paths or force Straight/Bend through spline approximation. See [Mathematical Knots](mathematical-knots.md). Arbitrary/freeform supports, variable pitch or section, intentional contact, spring mechanics, contact dynamics, and branching remain unsupported. Surface support identity is authored rather than imported-face-ID based. Direct `Concept Path` plus `Sweep` remains the lower-level choice for explicitly authored line/arc trajectories.See the canonical [axis coil](../../../fixtures/Canonical/WireForm/axis-coil.firmament), [frustum SurfaceCoil](../../../fixtures/Canonical/WireForm/frustum-surface-coil.firmament), [sphere SurfaceCoil](../../../fixtures/Canonical/WireForm/sphere-surface-coil.firmament), [composed Straight/Coil/Straight](../../../fixtures/Canonical/WireForm/straight-coil-straight.firmament), [90-degree bend](../../../fixtures/Canonical/WireForm/single-bend-90.firmament), and [Paperclip](../../../fixtures/Canonical/WireForm/paperclip.firmament).diff --git a/docs/public/reference/supported-features.md b/docs/public/reference/supported-features.mdindex f343a167..18fefb9c 100644--- a/docs/public/reference/supported-features.md+++ b/docs/public/reference/supported-features.md@@ -15,7 +15,7 @@| SectionChain ruled loft substrate | Bounded (SURF-X3b subset) | Firmament authoring lowers into ordered framed, same-topology semantic SectionChain IR; one-to-one ruled transitions; shared edges; Cap/Open; strict pcurves; deterministic intersection checks; persistent typed BodyState Add/Remove through documented planar housing lanes; no generic CSG authoring, rational product surface, or faceted fallback. See [Section chains](../firmament/section-chains.md). || Structural / weldment | Bounded (X2) | Explicit 3D nodes and straight paths; identifiable members; square/rectangular/round tube, angle, flat/round bar; orientation; catalog material; two-member butt and polygonal miter joints; semantic fillet welds; AP242 member assembly and deterministic JSON Cut List. No coping, curved routing, multi-member miter, connection design, weld analysis, or structural FEA. See [guide](../firmament/structural.md). || Semantic piping / routing | Bounded (X3a) | Logical connections; equipment-owned port Interfaces and hollow nozzle stubs; target-port-scoped owner KeepOut exemptions; coincident endpoint mates; explicit orthogonal 3D routes; deterministic A* proposals; editable accepted routes; 90-degree elbows; bounded local rerouting; AP242 assembly, BOM, and pipe Cut List. No freeform, stress-, flow-, slope-, or plant-scale routing. See [guide](../firmament/piping.md). |-| Boss | Bounded | First-class connected finite `On: Top` profile addition on an admitted Compose host; positive height; lowers through existing `Add`; no arbitrary solid union |+| Boss | Bounded | First-class connected finite profile addition; relative `On: Top` resolves the highest current semantic support under the footprint, named `<feature>.Top`/`Base.Top` is explicit, ambiguity fails typed; positive height; lowers through existing `Add`; no arbitrary solid union || Pocket | Bounded | First-class enclosed finite-depth `On: Top` profile removal; positive depth, non-through termination, and minimum remaining floor enforced; lowers through existing `Remove` || Lower-level profile composition | Bounded | Existing prismatic `Compose` `Add`/`Remove` remains compatible for bounded blockout authoring || Semantic holes, slots, patterns | Bounded | Qualified shaft/counterbore/countersink and finite static pattern routes; no stable generated-instance selector |diff --git a/docs/release/HARDEN-X1-SEMANTIC-AUTHORITY-CONVERGENCE.md b/docs/release/HARDEN-X1-SEMANTIC-AUTHORITY-CONVERGENCE.mdnew file mode 100644index 00000000..099e3a62--- /dev/null+++ b/docs/release/HARDEN-X1-SEMANTIC-AUTHORITY-CONVERGENCE.md@@ -0,0 +1,101 @@+# HARDEN-X1 — Semantic authority convergence++## Executive verdict++**Accepted.** Sequential feature supports, primitive Box feature composition, flat material accounting, and invalid Compose cardinality now resolve through their strongest available semantic representations. The canonical witnesses build through the real CLI, STEP-reimport as enclosed manifolds, and expose no raw authoring exception.++## Authority map++| Concern | Authority | Stale or duplicated path removed |+|---|---|---|+| Relative feature support | Current ordered Compose operations plus semantic profile footprint | Boss/Pocket no longer read only the original Base `To` level |+| Named support | Stable Base/Boss operation name and `.Top` support | No raw BRep face index or topology-order rebinding |+| Compose Base role | Explicit semantic cardinality validation | `SingleOrDefault` no longer enforces authored cardinality |+| Box Hole → EdgeFinish | Ordered `AirHoleFeature` plan followed by the combined final BRep plan | Counterbore is no longer rejected by the primitive combined lane while its Profile route succeeds |+| Flat material area | Validated final `ExactBlankContour` | No `base + tabs - notches - every ProfileDelta` reconstruction |++## Bug A — current-state support++The old Boss parser retained the unique Base operation as `stock`, then assigned every Boss `[stock.To, stock.To + Height]`. A second relative Boss consequently succeeded semantically while occupying the first Boss interval.++Relative `Top` now considers current additive semantic supports that overlap or contain the authored feature footprint, selects the highest support level, and preserves all equal-highest candidates. One candidate attaches; zero fails not-found/disconnected; multiple fail `feature-support-ambiguous:Top` with stable candidate names. Explicit `Base.Top`, `Stock.Top`, and `<BossName>.Top` bypass relative selection and retain named support intent.++The flagship [boss-stack-current-top fixture](../../fixtures/Canonical/Features/Composition/boss-stack-current-top.firmament) proves:++- Base top Z: 10 mm.+- Middle Boss: support `Top`, Z 10–16 mm, height 6 mm.+- Upper Boss: support `Top`, Z 16–20 mm, height 4 mm.+- Final bounds: X −20..20, Y −15..15, Z 0..20 mm.+- One body, one shell, 16 planar faces, enclosed manifold after STEP reimport.+- Slab intervals are ordered without overlap or submergence.++Replacing Upper with `On: Base.Top` produces Z 10–14 mm, proving explicit original-base support remains distinct. The invalid [ambiguous support fixture](../../fixtures/Invalid/FeatureComposition/feature-support-top-ambiguous.firmament) reports `feature-support-ambiguous:Top:feature=Bridge:candidates=Left,Right`.++## Bug A2 — Compose cardinality++Compose previously appended `compose-requires-exactly-one-base-operation`, then called `SingleOrDefault` on the same malformed sequence. Multiple Base roles therefore escaped as `InvalidOperationException: Sequence contains more than one matching element`.++The parser now materializes the Base candidates once, validates their count, and only reads element zero when the count is exactly one. The invalid [multiple-Base fixture](../../fixtures/Invalid/FeatureComposition/compose-multiple-base.firmament) reports `compose-role-cardinality:Base:expected=1:actual=2`; CLI build returns failure and writes no STEP file. Compose cardinality and feature-support diagnostics are classified as fatal authored semantics by validation.++The scoped raw-exception audit found the same Base assumption in counterbore footprint containment. It is now unreachable after typed cardinality validation. Test-only assertions and already-validated internal topology cardinalities were not mechanically changed.++## Bug B — primitive feature composition++The Box combined route already ordered `HostBRepPlan → HoleChangedBRepPlan → EdgeFinishChangedBRepPlan`, but it hard-rejected every stack other than `SimpleShaft`. The ordinary Air hole materializer already planned and materialized Counterbore, so the rejection duplicated a weaker feature-family gate.++The final combined plan now consumes either a through Shaft or through Counterbore from the same `AirHoleFeature` stage. Counterbore carries shaft radius, entry radius, and relief depth into one final exact topology containing the shaft cylinder, relief cylinder, annular shoulder, and the later top-boundary chamfer. Primitive Box semantics remain intact.++The [10 × 15 × 20 mm Box witness](../../fixtures/Canonical/Features/Composition/box-counterbore-chamfer.firmament) has a 4 mm through shaft, 7 mm counterbore, 3 mm relief depth, and 1 mm top chamfer. CLI/STEP evidence:++- Bounds preserved at 10 × 15 × 20 mm.+- One body, one shell, 13 faces, 26 edges, 16 vertices.+- 11 planar and 2 cylindrical surfaces.+- Removed hole volume 329.0818304635 mm³; final analytic volume 2647.2181561925 mm³.+- STEP SHA-256 `56753B44A4220E7B82F0E2BB83DF75F2EDF97CDE9E7906B33D45E8AFCC42D908`.+- STEP reimport succeeds as an enclosed manifold.++Qualification covers Box Shaft/Counterbore, Hole-only, EdgeFinish-only, and Hole → EdgeFinish routes, plus Profile/Compose Shaft/Counterbore and EdgeFinish witnesses. EdgeFinish → Hole remains intentionally order-sensitive: the declared sequence is not claimed to commute, and the combined production route continues to apply Hole before EdgeFinish.++## Bug C — final flat material region++Authored lowering already constructed the exact final flange contour, including ProfileDelta members, but set `ApproximateArea` using reconstructed arithmetic with `- profileDeltas.Sum(DeltaArea)`. That assumed every ProfileDelta removed material and produced 3410 mm² for an additive 90 mm² tab.++`PlanarContourKernel.Area` now analytically integrates final outer and inner loops for lines, circular arcs, and full circles. Authored planar regions use that exact result. `SheetMetalFlatPatternIr.MaterialArea` reads the validated final `ExactBlankContour`; it returns unavailable when exact authority is absent. `BoundingArea` remains a separate envelope quantity. CLI text and JSON report both names explicitly.++Evidence:++- [Add witness](../../fixtures/Canonical/SheetMetal/profiledelta-add-area.firmament): 3500 + 15×6 = **3590 mm²** for the final Wall contour.+- [Remove witness](../../fixtures/Canonical/SheetMetal/profiledelta-remove-area.firmament): 3500 − 15×6 = **3410 mm²**.+- [Tab + hole witness](../../fixtures/Canonical/SheetMetal/profiledelta-add-hole-area.firmament): the same additive tab plus an 8 mm through hole subtracts exactly `π × 4² mm²` from the final blank.+- Inner-loop integration witness: 200 − 12 = **188 mm²**.+- Full tabbed blank: `MaterialArea = 8982.699081698724 mm²`; `BoundingArea = 9492.699081698724 mm²`.++Existing manufacturing flat STEP generation already consumes `ExactBlankContour`, so it shares this authority. DFM exact-blank validation, SVG, flat STEP, and inspection now agree. Region `ApproximateArea` keeps its compatibility name but, for authored exact planar regions, contains the exact contour measurement.++## Artifacts and reproduction++Generated evidence follows repository policy and remains under ignored `artifacts/local/harden-x1/`:++- `harden-x1-boss-stack.step` and `.wireframe.svg`.+- `harden-x1-box-counterbore-chamfer.step` and `.wireframe.svg`.+- `harden-x1-tabbed-sheet-flat.step` and `.svg`.++Reproduce with:++```powershell+dotnet run --project Aetheris.CLI -c Release -- build fixtures/Canonical/Features/Composition/boss-stack-current-top.firmament --output artifacts/local/harden-x1/harden-x1-boss-stack.step --json+dotnet run --project Aetheris.CLI -c Release -- build fixtures/Canonical/Features/Composition/box-counterbore-chamfer.firmament --output artifacts/local/harden-x1/harden-x1-box-counterbore-chamfer.step --json+dotnet run --project Aetheris.CLI -c Release -- sheetmetal flatten fixtures/Canonical/SheetMetal/profiledelta-add-area.firmament --step artifacts/local/harden-x1/harden-x1-tabbed-sheet-flat.step --svg artifacts/local/harden-x1/harden-x1-tabbed-sheet-flat.svg --json+dotnet run --project Aetheris.CLI -c Release -- wireframe artifacts/local/harden-x1/harden-x1-boss-stack.step --out artifacts/local/harden-x1/harden-x1-boss-stack.wireframe.svg --view iso --density 8+dotnet run --project Aetheris.CLI -c Release -- wireframe artifacts/local/harden-x1/harden-x1-box-counterbore-chamfer.step --out artifacts/local/harden-x1/harden-x1-box-counterbore-chamfer.wireframe.svg --view iso --density 8+```++## Validation++- Release solution build: clean, zero warnings/errors.+- Focused Firmament Boss/Pocket/Hole/Counterbore/EdgeFinish/combined suite: 361 passed.+- Focused Sheet Metal ProfileDelta/flat/CTC/manufacturing suite: 39 passed.+- Flagship CLI build, inspect, STEP reimport, manifold, and wireframe qualification: passed.+- Full serial solution suite: 3,235 passed, 0 failed across all discovered test assemblies; the FrictionLab assembly reports no discoverable tests.+- Canonical fixture qualification: 134 passed after the final tab + hole witness was added (133 in the full corpus pass plus the final witness qualified through the same CLI route).+- Repository layout guard, local Markdown-link check, and `git diff --check`: passed.diff --git a/docs/release/WIRE-X2-MATHEMATICAL-KNOTS.md b/docs/release/WIRE-X2-MATHEMATICAL-KNOTS.mdnew file mode 100644index 00000000..c6edafb4--- /dev/null+++ b/docs/release/WIRE-X2-MATHEMATICAL-KNOTS.md@@ -0,0 +1,86 @@+# WIRE-X2 — Mathematical Knot Paths++## Executive verdict++**Accepted.** Aetheris can author named Trefoil, mathematical Figure Eight, and coprime TorusKnot families as closed semantic WireForm paths; qualify a finite tube using deterministic nonlocal separation and local curvature evidence; reconcile transported-frame holonomy; and export pcurve-complete, enclosed, non-rational AP242 sculptures. The qualification is honestly described as a conservative numerical criterion, not a formal proof of reach or knot type.++## Substrate audit and architecture++WIRE-X2 reuses WIRE-X1 rather than introducing an arbitrary-curve stack. `WireEvaluablePathAir` is the shared semantic/evaluable operation substrate; `WireCoilAir` remains its open winding specialization and `WireKnotPathAir` is its inherently periodic named-family specialization. Straight/Bend remain exact line/arc state transitions with cylinder/torus realization.++```text+WireForm / Knot family identity+ → WireKnotPathAir (exact evaluable periodic law; seam t=0)+ → deterministic cubic polynomial centerline spans+ → rotation-minimizing frame transport+ → measured holonomy + linearly distributed correction+ → four non-rational polynomial quarter-tube patches per span+ → shared closed BRep + face-local pcurves+ → deterministic AP242 export/reimport+```++Audit answers:++1. KnotPath reuses the WIRE-X1 evaluator, deterministic approximation, tangent transport helpers, polynomial B-spline geometry, topology bindings, STEP exporter/importer, renderer, and WireForm stock accounting.+2. Closed curves require explicit periodic semantics, cyclic station/span topology, no duplicated semantic endpoint, no caps, cyclic nonlocal-neighbour exclusion, one stable seam, frame-holonomy correction, and seam pcurves.+3. WIRE-X1 propagates orientation by the minimal rotation mapping each sampled tangent to the next, then reprojects/normalizes the up vector.+4. Without correction, the final section orientation can differ from the initial orientation and create a twist discontinuity at the seam. X2 measures the signed residual about the tangent and distributes its inverse over the full domain.+5. X0/X1 already had deterministic sampled segment/chord separation for distinct operations and turn-spacing witnesses. X2 adds a cyclic single-curve nonlocal witness and sampled curvature-radius bound because open operation-pair logic cannot qualify tube reach.+6. Turns, pitch/height resolution, support offset/clearance, support families, latitude progression, and adjacent-turn clearance remain coil-only.++## Family and tube evidence++| Family | Closed | Single component | Diameter (mm) | Valid tube | STEP |+| --- | --- | --- | ---: | --- | --- |+| Trefoil, right-handed | yes | yes | 6 | yes | enclosed manifold |+| FigureEight | yes | yes | 6 | yes | enclosed manifold |+| TorusKnot(3,5) | yes | yes (`gcd=1`) | 5 | yes | enclosed manifold |+| TorusKnot(2,4) | semantic family only | no (`gcd=2`) | — | rejected | none |++| Family | Centerline length (mm) | Min nonlocal distance (mm) | Min curvature radius (mm) | Wire radius (mm) | Tube radius limit (mm) | Safety margin (mm) |+| --- | ---: | ---: | ---: | ---: | ---: | ---: |+| Trefoil | 576.525803979 | 24.284904872 | 25.746163949 | 3.0 | 12.142452436 | 9.142452436 |+| FigureEight | 773.395525000 | 20.530164330 | 14.839340545 | 3.0 | 10.265082165 | 7.265082165 |+| TorusKnot(3,5) | 910.394968258 | 22.153729016 | 32.313624401 | 2.5 | 11.076864508 | 8.576864508 |++The 20 mm-scale Trefoil admits a maximum diameter of approximately 24.284705 mm after numeric margin. The canonical thin (3 mm) and near-limit (22 mm) fixtures pass. The 100 mm invalid fixture fails `wireform-knot-tube-self-intersection` with requested/admitted diameters and closest parameters `t1≈0.306640625`, `t2≈0.693359375`; compilation emits no STEP. Uniform 2× scale plus 2× diameter preserves the dimensionless ratios. Rigid frame rotation preserves intrinsic length and clearance.++## Frame closure++| Family | Initial frame source | Raw transported mismatch (rad) | Distributed correction (rad) | Final error (rad) |+| --- | --- | ---: | ---: | ---: |+| Trefoil | projected authored Up at `t=0` | -2.225490679 | +2.225490679 | 1.11e-16 |+| FigureEight | projected authored Up at `t=0` | +0.536591895 | -0.536591895 | 0 |+| TorusKnot(3,5) | projected authored Up at `t=0` | +3.109257060 | -3.109257060 | 2.15e-16 |++The final cyclic span consumes the last fraction of the distributed correction and reuses the initial ring, so the topology and section frame close together. The general wireframe renderer successfully traverses every face and recovered every emitted pcurve without a knot-specific rendering path.++## Approximation and representation++| Family | Semantic authority | Degree | Spans | Max/RMS centerline error (mm) | Faces / edges / vertices | Pcurves | Max authored pcurve error (mm) |+| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: |+| Trefoil | evaluable periodic named law | 3 | 96 | 0.000082880 / 0.000046239 | 384 / 768 / 384 | 1,536 | < 4.6e-14 |+| FigureEight | evaluable periodic named law | 3 | 128 | 0.000140117 / 0.000079406 | 512 / 1,024 / 512 | 2,048 | 4.37e-14 |+| TorusKnot(3,5) | evaluable periodic named law | 3 | 160 | 0.000199003 / 0.000134698 | 640 / 1,280 / 640 | 2,560 | 4.50e-14 |++Every canonical product contains only degree-3 non-rational B-spline curves/surfaces: analytic product surfaces `0`, rational product surfaces `0`, faceted fallback `0`, and terminal planes/caps `0`. Every export reimports as one body, one enclosed shell, with every edge incident to two coedges. Renderer-side STEP pcurve recovery for the Trefoil recovered 1,536 pcurves with maximum residual `5.61e-9 mm`; no curve/surface family was unsupported.++Canonical SHA-256 values:++- Trefoil: `6502bfd9dbafa597d2efacad5c593690a9967a2bebc891e90a298dbbd106dd25`+- Figure Eight: `cc70d9f97655cd320df22545752d8adba7438da6fc8a535911314a0b2f725514`+- TorusKnot(3,5): `3faa38954166abd7f96f4041bc40faa2c636873bc2672e5f87e95b03b2f66c10`++## Scope and validation++The geometric family identity is authored semantics; sampling validates closure, approximation, and finite-diameter embedding but does not prove a reconstructed knot-theory classification. Closure manufacturing is unspecified. X2 deliberately excludes physical tying, friction/contact, deformation, arbitrary parametric expressions, links, braids, multi-strand weaving, variable diameter, and topology inference.++Focused coverage exercises all three generators, P/Q constraints, periodic position/tangent closure, deterministic approximation, numerical length, cyclic nonlocal distance, curvature limit, tube radius limit, too-thick failure/no STEP, scale/orientation invariance, holonomy correction, cyclic no-cap BRep topology, pcurves, polynomial-only STEP/reimport, renderer, determinism, and stock/volume/mass. The existing WireForm suite retains Straight/Bend/Paperclip and Axis/SurfaceCoil coverage. The warning-free Release solution build passed, followed by a clean full serial run of 3,248 tests with zero failures/skips; the intentionally empty FrictionLab test assembly remains without discoverable tests. One preceding loaded run tripped an existing through-hole performance threshold, then passed in isolation and in the clean full rerun.++Manual generated artifacts and iso/front/top previews live under ignored `artifacts/local/` per repository policy:++1. `wire-x2-knot-1-trefoil.step`+2. `wire-x2-figure-eight.step`+3. `wire-x2-torus-knot-3-5.step`++Reproduce with `aetheris build <fixture> --output artifacts/local/<name>.step` and `aetheris wireframe <step> --out <preview>.svg --view iso --density 8`.diff --git a/fixtures/Canonical/Features/Composition/boss-stack-current-top.firmament b/fixtures/Canonical/Features/Composition/boss-stack-current-top.firmamentnew file mode 100644index 00000000..62b129b0--- /dev/null+++ b/fixtures/Canonical/Features/Composition/boss-stack-current-top.firmament@@ -0,0 +1,31 @@+Model BossStackCurrentTop {+ Units: mm+ Concept Struct Layout On XY {+ Rect2 BaseRect { Center: [0mm, 0mm]; Size: [40mm, 30mm] }+ Rect2 MiddleRect { Center: [0mm, 0mm]; Size: [24mm, 18mm] }+ Rect2 UpperRect { Center: [0mm, 0mm]; Size: [12mm, 8mm] }+ }+ Profile BaseProfile Using Layout { Loop Outer {+ Segment B { Trace: BaseRect.Bottom; From: BaseRect.BottomLeft; To: BaseRect.BottomRight }+ Segment R { Trace: BaseRect.Right; From: BaseRect.BottomRight; To: BaseRect.TopRight }+ Segment T { Trace: BaseRect.Top; From: BaseRect.TopRight; To: BaseRect.TopLeft }+ Segment L { Trace: BaseRect.Left; From: BaseRect.TopLeft; To: BaseRect.BottomLeft }+ } }+ Profile MiddleProfile Using Layout { Loop Outer {+ Segment B { Trace: MiddleRect.Bottom; From: MiddleRect.BottomLeft; To: MiddleRect.BottomRight }+ Segment R { Trace: MiddleRect.Right; From: MiddleRect.BottomRight; To: MiddleRect.TopRight }+ Segment T { Trace: MiddleRect.Top; From: MiddleRect.TopRight; To: MiddleRect.TopLeft }+ Segment L { Trace: MiddleRect.Left; From: MiddleRect.TopLeft; To: MiddleRect.BottomLeft }+ } }+ Profile UpperProfile Using Layout { Loop Outer {+ Segment B { Trace: UpperRect.Bottom; From: UpperRect.BottomLeft; To: UpperRect.BottomRight }+ Segment R { Trace: UpperRect.Right; From: UpperRect.BottomRight; To: UpperRect.TopRight }+ Segment T { Trace: UpperRect.Top; From: UpperRect.TopRight; To: UpperRect.TopLeft }+ Segment L { Trace: UpperRect.Left; From: UpperRect.TopLeft; To: UpperRect.BottomLeft }+ } }+ Struct Part { Compose Body {+ Base Stock { Profile: BaseProfile; From: 0mm; To: 10mm; Role: Stock }+ Boss Middle { On: Top; Profile: MiddleProfile; Height: 6mm }+ Boss Upper { On: Top; Profile: UpperProfile; Height: 4mm }+ } }+}diff --git a/fixtures/Canonical/Features/Composition/box-counterbore-chamfer.firmament b/fixtures/Canonical/Features/Composition/box-counterbore-chamfer.firmamentnew file mode 100644index 00000000..66fc4a8a--- /dev/null+++ b/fixtures/Canonical/Features/Composition/box-counterbore-chamfer.firmament@@ -0,0 +1,8 @@+Model BoxCounterboreChamfer {+ Units: mm+ Box Base { Size: [10mm, 15mm, 20mm] }+ Modify Base {+ Hole<Counterbore> Mount { On: +Z Center: Point2(0mm, 0mm) Diameter: 4mm CounterboreDiameter: 7mm CounterboreDepth: 3mm End: ThroughAll }+ EdgeFinish TopBreak { Face: +Z Target: Boundary Kind: Chamfer Distance: 1mm }+ }+}diff --git a/fixtures/Canonical/SheetMetal/profiledelta-add-area.firmament b/fixtures/Canonical/SheetMetal/profiledelta-add-area.firmamentnew file mode 100644index 00000000..65ceb4a5--- /dev/null+++ b/fixtures/Canonical/SheetMetal/profiledelta-add-area.firmament@@ -0,0 +1,14 @@+Use Profile.Modifications;++Static AddedTab: ProfileTabSpec = ProfileTabSpec {+ Center: 50mm+ Width: 15mm+ Extension: 6mm+}+ProfileDelta ServiceTab = Tab < P: AddedTab, Owner: Wall.Outer >++SheetMetal TabAreaWitness {+ Thickness: 1mm;+ Base Deck { Profile: Rectangle { Width: 100mm; Height: 50mm; }; }+ Flange Wall { From: Deck.Front; Height: 35mm; Angle: 90deg; Radius: 2mm; }+}diff --git a/fixtures/Canonical/SheetMetal/profiledelta-add-hole-area.firmament b/fixtures/Canonical/SheetMetal/profiledelta-add-hole-area.firmamentnew file mode 100644index 00000000..fc3142df--- /dev/null+++ b/fixtures/Canonical/SheetMetal/profiledelta-add-hole-area.firmament@@ -0,0 +1,15 @@+Use Profile.Modifications;++Static AddedTab: ProfileTabSpec = ProfileTabSpec {+ Center: 50mm+ Width: 15mm+ Extension: 6mm+}+ProfileDelta ServiceTab = Tab < P: AddedTab, Owner: Wall.Outer >++SheetMetal TabHoleAreaWitness {+ Thickness: 1mm;+ Base Deck { Profile: Rectangle { Width: 100mm; Height: 50mm; }; }+ Flange Wall { From: Deck.Front; Height: 35mm; Angle: 90deg; Radius: 2mm; }+ Hole Mount { On: Deck; Center: (50mm, 25mm); Diameter: 8mm; }+}diff --git a/fixtures/Canonical/SheetMetal/profiledelta-remove-area.firmament b/fixtures/Canonical/SheetMetal/profiledelta-remove-area.firmamentnew file mode 100644index 00000000..a21d0711--- /dev/null+++ b/fixtures/Canonical/SheetMetal/profiledelta-remove-area.firmament@@ -0,0 +1,16 @@+ProfileDelta ServiceNotch {+ On: Wall.Outer;+ Anchor: CenteredAt 50mm;+ Side: Inward;+ Level Carrier { Offset: 0mm; }+ Level Cut { Offset: 6mm; }+ Transition Enter { Kind: Step; To: Cut; }+ Span Land { Run: 15mm; At: Cut; }+ Transition Exit { Kind: Step; To: Carrier; }+}++SheetMetal NotchAreaWitness {+ Thickness: 1mm;+ Base Deck { Profile: Rectangle { Width: 100mm; Height: 50mm; }; }+ Flange Wall { From: Deck.Front; Height: 35mm; Angle: 90deg; Radius: 2mm; }+}diff --git a/fixtures/Canonical/WireForm/Knot/figure-eight.firmament b/fixtures/Canonical/WireForm/Knot/figure-eight.firmamentnew file mode 100644index 00000000..69e32f50--- /dev/null+++ b/fixtures/Canonical/WireForm/Knot/figure-eight.firmament@@ -0,0 +1,9 @@+Model KnotFigureEight {+ Units: mm+ WireForm FigureEightSculpture {+ Diameter: 6mm+ Material: Standard.Materials.StainlessSteel.304_Annealed+ StartFrame { Origin: [0mm,0mm,0mm]; Tangent: [1,0,0]; Up: [0,0,1] }+ Knot Sculpture { Family: FigureEight; Scale: 18mm; Phase: 0deg }+ }+}diff --git a/fixtures/Canonical/WireForm/Knot/rotated-trefoil.firmament b/fixtures/Canonical/WireForm/Knot/rotated-trefoil.firmamentnew file mode 100644index 00000000..cbcd2f8a--- /dev/null+++ b/fixtures/Canonical/WireForm/Knot/rotated-trefoil.firmament@@ -0,0 +1,9 @@+Model RotatedTrefoil {+ Units: mm+ WireForm RotatedTrefoil {+ Diameter: 6mm+ Material: Standard.Materials.StainlessSteel.304_Annealed+ StartFrame { Origin: [10mm,20mm,30mm]; Tangent: [0,1,0]; Up: [1,0,0] }+ Knot Sculpture { Family: Trefoil; Scale: 20mm }+ }+}diff --git a/fixtures/Canonical/WireForm/Knot/torus-knot-3-5.firmament b/fixtures/Canonical/WireForm/Knot/torus-knot-3-5.firmamentnew file mode 100644index 00000000..1898c959--- /dev/null+++ b/fixtures/Canonical/WireForm/Knot/torus-knot-3-5.firmament@@ -0,0 +1,9 @@+Model TorusKnot35 {+ Units: mm+ WireForm TorusKnotSculpture {+ Diameter: 5mm+ Material: Standard.Materials.StainlessSteel.304_Annealed+ StartFrame { Origin: [0mm,0mm,0mm]; Tangent: [1,0,0]; Up: [0,0,1] }+ Knot Sculpture { Family: TorusKnot; P: 3; Q: 5; MajorRadius: 42mm; MinorRadius: 14mm; Phase: 0deg }+ }+}diff --git a/fixtures/Canonical/WireForm/Knot/trefoil-near-limit.firmament b/fixtures/Canonical/WireForm/Knot/trefoil-near-limit.firmamentnew file mode 100644index 00000000..1ae22be8--- /dev/null+++ b/fixtures/Canonical/WireForm/Knot/trefoil-near-limit.firmament@@ -0,0 +1,9 @@+Model TrefoilNearLimit {+ Units: mm+ WireForm TrefoilNearLimit {+ Diameter: 22mm+ Material: Standard.Materials.StainlessSteel.304_Annealed+ StartFrame { Origin: [0mm,0mm,0mm]; Tangent: [1,0,0]; Up: [0,0,1] }+ Knot Sculpture { Family: Trefoil; Scale: 20mm }+ }+}diff --git a/fixtures/Canonical/WireForm/Knot/trefoil-thin.firmament b/fixtures/Canonical/WireForm/Knot/trefoil-thin.firmamentnew file mode 100644index 00000000..4e0c71ed--- /dev/null+++ b/fixtures/Canonical/WireForm/Knot/trefoil-thin.firmament@@ -0,0 +1,9 @@+Model TrefoilThin {+ Units: mm+ WireForm TrefoilThin {+ Diameter: 3mm+ Material: Standard.Materials.StainlessSteel.304_Annealed+ StartFrame { Origin: [0mm,0mm,0mm]; Tangent: [1,0,0]; Up: [0,0,1] }+ Knot Sculpture { Family: Trefoil; Scale: 20mm }+ }+}diff --git a/fixtures/Canonical/WireForm/Knot/trefoil.firmament b/fixtures/Canonical/WireForm/Knot/trefoil.firmamentnew file mode 100644index 00000000..b731bf3d--- /dev/null+++ b/fixtures/Canonical/WireForm/Knot/trefoil.firmament@@ -0,0 +1,9 @@+Model Knot1Trefoil {+ Units: mm+ WireForm Knot1 {+ Diameter: 6mm+ Material: Standard.Materials.StainlessSteel.304_Annealed+ StartFrame { Origin: [0mm,0mm,0mm]; Tangent: [1,0,0]; Up: [0,0,1] }+ Knot Sculpture { Family: Trefoil; Scale: 20mm; Handedness: RightHanded; Phase: 0deg }+ }+}diff --git a/fixtures/Invalid/FeatureComposition/compose-multiple-base.firmament b/fixtures/Invalid/FeatureComposition/compose-multiple-base.firmamentnew file mode 100644index 00000000..584a79aa--- /dev/null+++ b/fixtures/Invalid/FeatureComposition/compose-multiple-base.firmament@@ -0,0 +1,14 @@+Model ComposeMultipleBase {+ Units: mm+ Concept Struct Layout On XY { Rect2 StockRect { Center: [0mm, 0mm]; Size: [20mm, 20mm] } }+ Profile StockProfile Using Layout { Loop Outer {+ Segment B { Trace: StockRect.Bottom; From: StockRect.BottomLeft; To: StockRect.BottomRight }+ Segment R { Trace: StockRect.Right; From: StockRect.BottomRight; To: StockRect.TopRight }+ Segment T { Trace: StockRect.Top; From: StockRect.TopRight; To: StockRect.TopLeft }+ Segment L { Trace: StockRect.Left; From: StockRect.TopLeft; To: StockRect.BottomLeft }+ } }+ Struct Part { Compose Body {+ Base First { Profile: StockProfile; From: 0mm; To: 5mm }+ Base Second { Profile: StockProfile; From: 5mm; To: 10mm }+ } }+}diff --git a/fixtures/Invalid/FeatureComposition/feature-support-top-ambiguous.firmament b/fixtures/Invalid/FeatureComposition/feature-support-top-ambiguous.firmamentnew file mode 100644index 00000000..e45130f6--- /dev/null+++ b/fixtures/Invalid/FeatureComposition/feature-support-top-ambiguous.firmament@@ -0,0 +1,19 @@+Model FeatureSupportTopAmbiguous {+ Units: mm+ Concept Struct Layout On XY {+ Rect2 BaseRect { Center: [0mm, 0mm]; Size: [50mm, 24mm] }+ Rect2 LeftRect { Center: [-10mm, 0mm]; Size: [12mm, 10mm] }+ Rect2 RightRect { Center: [10mm, 0mm]; Size: [12mm, 10mm] }+ Rect2 BridgeRect { Center: [0mm, 0mm]; Size: [30mm, 8mm] }+ }+ Profile BaseProfile From BaseRect+ Profile LeftProfile From LeftRect+ Profile RightProfile From RightRect+ Profile BridgeProfile From BridgeRect+ Struct Part { Compose Body {+ Base Stock { Profile: BaseProfile; From: 0mm; To: 10mm }+ Boss Left { On: Base.Top; Profile: LeftProfile; Height: 5mm }+ Boss Right { On: Base.Top; Profile: RightProfile; Height: 5mm }+ Boss Bridge { On: Top; Profile: BridgeProfile; Height: 3mm }+ } }+}diff --git a/fixtures/Invalid/WireForm/Knot/degenerate-scale.firmament b/fixtures/Invalid/WireForm/Knot/degenerate-scale.firmamentnew file mode 100644index 00000000..e888b1dc--- /dev/null+++ b/fixtures/Invalid/WireForm/Knot/degenerate-scale.firmament@@ -0,0 +1,9 @@+Model DegenerateTrefoil {+ Units: mm+ WireForm DegenerateTrefoil {+ Diameter: 5mm+ Material: Standard.Materials.StainlessSteel.304_Annealed+ StartFrame { Origin: [0mm,0mm,0mm]; Tangent: [1,0,0]; Up: [0,0,1] }+ Knot Sculpture { Family: Trefoil; Scale: 0mm }+ }+}diff --git a/fixtures/Invalid/WireForm/Knot/invalid-pq.firmament b/fixtures/Invalid/WireForm/Knot/invalid-pq.firmamentnew file mode 100644index 00000000..14c02246--- /dev/null+++ b/fixtures/Invalid/WireForm/Knot/invalid-pq.firmament@@ -0,0 +1,9 @@+Model InvalidTorusParameters {+ Units: mm+ WireForm InvalidTorusParameters {+ Diameter: 5mm+ Material: Standard.Materials.StainlessSteel.304_Annealed+ StartFrame { Origin: [0mm,0mm,0mm]; Tangent: [1,0,0]; Up: [0,0,1] }+ Knot Sculpture { Family: TorusKnot; P: 1; Q: 5; MajorRadius: 42mm; MinorRadius: 14mm }+ }+}diff --git a/fixtures/Invalid/WireForm/Knot/torus-knot-non-coprime.firmament b/fixtures/Invalid/WireForm/Knot/torus-knot-non-coprime.firmamentnew file mode 100644index 00000000..c7cd5c34--- /dev/null+++ b/fixtures/Invalid/WireForm/Knot/torus-knot-non-coprime.firmament@@ -0,0 +1,9 @@+Model TorusLink24Rejected {+ Units: mm+ WireForm TorusLink24Rejected {+ Diameter: 5mm+ Material: Standard.Materials.StainlessSteel.304_Annealed+ StartFrame { Origin: [0mm,0mm,0mm]; Tangent: [1,0,0]; Up: [0,0,1] }+ Knot Sculpture { Family: TorusKnot; P: 2; Q: 4; MajorRadius: 42mm; MinorRadius: 14mm }+ }+}diff --git a/fixtures/Invalid/WireForm/Knot/trefoil-wire-too-thick.firmament b/fixtures/Invalid/WireForm/Knot/trefoil-wire-too-thick.firmamentnew file mode 100644index 00000000..73cae890--- /dev/null+++ b/fixtures/Invalid/WireForm/Knot/trefoil-wire-too-thick.firmament@@ -0,0 +1,9 @@+Model TrefoilTooThick {+ Units: mm+ WireForm TrefoilTooThick {+ Diameter: 100mm+ Material: Standard.Materials.StainlessSteel.304_Annealed+ StartFrame { Origin: [0mm,0mm,0mm]; Tangent: [1,0,0]; Up: [0,0,1] }+ Knot Sculpture { Family: Trefoil; Scale: 20mm }+ }+}