Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Improve cut-cell boundary integration and add M4C project

Yuechen Lif4043421bc57
diff --git a/Aetheris.Continuum.Tests/Lattice/ContinuumM4CTests.cs b/Aetheris.Continuum.Tests/Lattice/ContinuumM4CTests.cs
new file mode 100644
index 00000000..9e9889cb
--- /dev/null
+++ b/Aetheris.Continuum.Tests/Lattice/ContinuumM4CTests.cs
@@ -0,0 +1,82 @@
+using Aetheris.Continuum.Boundaries;
+using Aetheris.Continuum.Lattice;
+using Aetheris.Continuum.Regions.Constructive;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.StandardLibrary;
+
+namespace Aetheris.Continuum.Tests.Lattice;
+
+public sealed class ContinuumM4CTests
+{
+ [Fact]
+ public void FixedWholePartHexBoltBeatsComparableFineControlAndUsesCurvedSupportMaps()
+ {
+ var f=Fixture(Transform3D.Identity);var fixedRun=Run(f,12,4,true);var fine=ContinuumGridClassifier.Classify(f.Dual.Continuum,new LatticeSpec(f.Dual.Continuum.Bounds,24,24,24),4);
+ var exact=f.Dual.Continuum.AnalyticReferenceVolume;var fixedError=double.Abs(fixedRun.Volume-exact)/exact;var fineError=double.Abs(fine.EstimatedOccupiedVolume-exact)/exact;
+ Assert.True(fixedError<fineError,$"fixed={fixedError:R}; fine={fineError:R}");Assert.InRange(fixedError,0d,.0015d);
+ Assert.Contains(fixedRun.Sets.SelectMany(s=>s.Contributors),c=>c.SupportKind==SurfaceGeometryKind.Cylinder&&c.LocalMap is not null);
+ Assert.Contains(fixedRun.Sets.SelectMany(s=>s.Contributors),c=>c.SupportKind==SurfaceGeometryKind.Cone&&c.LocalMap is not null);
+ Assert.Contains(fixedRun.Sets.SelectMany(s=>s.Contributors),c=>c.SupportKind==SurfaceGeometryKind.Torus&&c.LocalMap is not null);
+ }
+
+ [Fact]
+ public void MultiSupportEdgesFilletsAndTrimJunctionsRetainPerSupportIdentity()
+ {
+ var run=Run(Fixture(Transform3D.Identity),12,4,true);
+ Assert.Contains(run.Sets,s=>s.CompositionKind==CutCellCompositionKind.TwoFaceEdge&&s.Contributors.Any(c=>c.SupportKind==SurfaceGeometryKind.Plane)&&s.Contributors.Any(c=>c.SupportKind is SurfaceGeometryKind.Cylinder or SurfaceGeometryKind.Cone&&c.LocalMap is not null));
+ Assert.Contains(run.Sets,s=>s.CompositionKind==CutCellCompositionKind.FilletContact&&s.Contributors.Any(c=>c.SupportKind==SurfaceGeometryKind.Torus));
+ Assert.Contains(run.Sets,s=>s.CompositionKind==CutCellCompositionKind.MultiFaceTrimJunction&&s.Contributors.Any(c=>c.SupportKind==SurfaceGeometryKind.Cone&&c.LocalMap is not null));
+ Assert.All(run.Sets.Where(s=>s.Contributors.Count>1&&s.Contributors.Any(c=>c.SupportKind!=SurfaceGeometryKind.Plane)),s=>Assert.Contains("composite-rays",s.Integration.Method,StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void HyperbolaTrimmedConePlaneJunctionKeepsBrepTrimAndConeMap()
+ {
+ var f=Fixture(Transform3D.Identity);var hyperbolaEdges=f.Dual.Brep.Body.Topology.Edges.Where(e=>f.Dual.Brep.Body.TryGetEdgeCurveGeometry(e.Id,out var curve)&&curve?.Kind==CurveGeometryKind.Hyperbola3).Select(e=>e.Id).ToHashSet();
+ Assert.NotEmpty(hyperbolaEdges);
+ var run=Run(f,12,4,true);Assert.Contains(run.Sets,s=>s.Contributors.Any(c=>c.EdgeIds.Any(hyperbolaEdges.Contains)&&c.SupportKind==SurfaceGeometryKind.Cone&&c.LocalMap is not null)&&s.Contributors.Any(c=>c.SupportKind==SurfaceGeometryKind.Plane));
+ }
+
+ [Fact]
+ public void ObviousPlanarCellsBypassJudgmentAndPlanSelectionIsDeterministic()
+ {
+ var a=Run(Fixture(Transform3D.Identity),8,4,true);var b=Run(Fixture(Transform3D.Identity),8,4,true);
+ var planar=a.Sets.First(s=>s.CompositionKind==CutCellCompositionKind.SingleFace&&s.Contributors.All(c=>c.SupportKind==SurfaceGeometryKind.Plane));
+ Assert.Null(planar.Judgment);Assert.Equal("exact-convex-planar-clipping",planar.Integration.Method);
+ Assert.Equal(a.Sets.Select(Stable),b.Sets.Select(Stable));
+ }
+
+ [Fact]
+ public void BaselineAndRotationsRemainOnTheSameAccuracyScale()
+ {
+ var transforms=new[]{Transform3D.Identity,Transform3D.CreateRotationY(29d*double.Pi/180d),Transform3D.CreateRotationX(17d*double.Pi/180d)*Transform3D.CreateRotationY(31d*double.Pi/180d)*Transform3D.CreateRotationZ(13d*double.Pi/180d)};
+ var errors=transforms.Select(t=>{var f=Fixture(t);var r=Run(f,12,4,true);return double.Abs(r.Volume-f.Dual.Continuum.AnalyticReferenceVolume)/f.Dual.Continuum.AnalyticReferenceVolume;}).ToArray();
+ Assert.All(errors,e=>Assert.InRange(e,0d,.0015d));Assert.True(errors.Max()<20d*double.Max(errors.Min(),1e-12d));
+ }
+
+ [Fact]
+ public void TorusQuarticRootIsolationRetainsAllChartsDeterministically()
+ {
+ // (x^2-1)(x^2-4) is the four-branch section produced by a ray through a torus.
+ var a=RealPolynomialRoots.InInterval([4d,0d,-5d,0d,1d],-3d,3d);
+ var b=RealPolynomialRoots.InInterval([4d,0d,-5d,0d,1d],-3d,3d);
+ Assert.Equal(new[]{-2d,-1d,1d,2d},a.Select(x=>double.Round(x,9)));
+ Assert.Equal(a,b);
+ }
+
+ [Fact]
+ public void CompositeProductionPathUsesNoVolumetricMsaaFallback()
+ {
+ var run=Run(Fixture(Transform3D.Identity),12,4,true);
+ Assert.All(run.Sets,s=>Assert.Equal(0,s.Integration.MsaaFallbackSamples));
+ Assert.Contains(run.Sets,s=>s.Contributors.Any(c=>c.SupportKind==SurfaceGeometryKind.Torus)&&s.Integration.Method.Contains("composite-rays",StringComparison.Ordinal));
+ }
+
+ private static string Stable(CutCellBoundarySet s)=>$"{s.CellIndex}:{s.CompositionKind}:{s.Integration.Method}:{string.Join(',',s.Contributors.Select(c=>$"{c.SupportKind}:{c.LocalMap?.Approximation.ResolutionU}x{c.LocalMap?.Approximation.ResolutionV}"))}";
+ private static (double Volume,IReadOnlyList<CutCellBoundarySet> Sets) Run(FixtureData f,int n,int samples,bool compose)
+ {var grid=ContinuumGridClassifier.Classify(f.Dual.Continuum,new LatticeSpec(f.Dual.Continuum.Bounds,n,n,n),samples);var sets=compose?grid.CutCells.Where(c=>f.Shell.Query(c.Bounds).Count>0).Select(c=>f.Composer.Compose(c.Index,c.Bounds)).ToArray():[];var size=grid.Lattice.CellSize;var cv=size.X*size.Y*size.Z;return(grid.InsideCellCount*cv+sets.Sum(s=>s.Integration.OccupancyFraction*cv),sets);}
+ private static FixtureData Fixture(Transform3D transform)
+ {var plan=HexBoltConstructionPlanner.Plan(McMasterHexBoltSpecs.Reference91180A151,"M4C-Test-HexBolt").Value!;var dual=ExactCoaxialDualMaterializer.Materialize(plan,transform);var association=new CirBrepAssociation(dual.Continuum.Id,plan.StableId,"outer-shell",plan.StableId,dual.ConstructionSourceIdentity);var semantics=dual.Brep.Semantics.Where(s=>s.Face.HasValue).GroupBy(s=>s.Face!.Value).ToDictionary(g=>g.Key,g=>string.Join("|",g.Select(x=>x.StableId).Order()));var shell=new WholeShellBoundaryQuery(dual.Brep.Body,association,transform,semantics);return new(dual,shell,new WholePartCutCellComposer(dual.Continuum,shell));}
+ private sealed record FixtureData(ExactCoaxialDualLowering Dual,WholeShellBoundaryQuery Shell,WholePartCutCellComposer Composer);
+}
diff --git a/Aetheris.Continuum/Boundaries/BoundaryOffsetMap3DIntegrator.cs b/Aetheris.Continuum/Boundaries/BoundaryOffsetMap3DIntegrator.cs
index 97ce7ecc..97be50cd 100644
--- a/Aetheris.Continuum/Boundaries/BoundaryOffsetMap3DIntegrator.cs
+++ b/Aetheris.Continuum/Boundaries/BoundaryOffsetMap3DIntegrator.cs
@@ -108,6 +108,21 @@ public static class BoundaryOffsetMap3DIntegrator
return new(estimate, footprint, diagnostics);
}
+ /// <summary>
+ /// Integrates only the face-owned surface patch. Whole-part composition keeps volume with CIR,
+ /// so it must not pay for an unused tangent-graph thickness integral for every contributor.
+ /// </summary>
+ public static StructuredBoundaryMapCellEstimate IntegrateSurfacePatch(IBoundaryOffsetMap map, BoundingBox3D bounds)
+ {
+ var footprint=CreateFootprint(map,bounds);var counters=new Counters();
+ var uNodes=map.Samples.Select(s=>s.U).Distinct().Order().ToArray();var vNodes=map.Samples.Select(s=>s.V).Distinct().Order().ToArray();
+ var (area,moment,normal)=IntegrateSurface(map,bounds,uNodes,vNodes,counters);
+ var estimate=new BoundaryMapCellEstimate(0d,area,moment,normal);
+ var diagnostics=new BoundaryIntegrationDiagnostics("structured-map-surface-patch",footprint.Vertices.Count,0,0,0,0,0,0,counters.SurfaceTriangles,
+ (footprint.Vertices.Count*16L)+((uNodes.Length+vNodes.Length)*8L)+512L);
+ return new(estimate,footprint,diagnostics);
+ }
+
/// <summary>Dense M2 control/oracle retained for regression and independent cost comparison.</summary>
public static BoundaryMapCellEstimate IntegrateDenseOracle(IBoundaryOffsetMap map, BoundingBox3D bounds,
int volumeSamplesPerAxis = 64, int areaSubdivisionsPerMapInterval = 6)
diff --git a/Aetheris.Continuum/Boundaries/ConvexPlanarCellIntegrator.cs b/Aetheris.Continuum/Boundaries/ConvexPlanarCellIntegrator.cs
index 2bdbdedd..9173287b 100644
--- a/Aetheris.Continuum/Boundaries/ConvexPlanarCellIntegrator.cs
+++ b/Aetheris.Continuum/Boundaries/ConvexPlanarCellIntegrator.cs
@@ -10,10 +10,14 @@ internal static class ConvexPlanarCellIntegrator
private sealed record Polygon(IReadOnlyList<Point3D> Vertices, FaceId? BoundaryFace);
public static LocalBoundaryIntegration Integrate(BoundingBox3D cell, WholeShellBoundaryQuery shell,
- IReadOnlyDictionary<FaceId, MaterialSideEvidence> materialSides)
+ IReadOnlyDictionary<FaceId, MaterialSideEvidence> materialSides,
+ IReadOnlyList<WholeShellBoundaryCandidate> localCandidates)
{
var polygons = CellPolygons(cell).ToList();
- foreach (var face in shell.Faces.OrderBy(f => f.FaceId.Value))
+ // A Cut cell is clipped only by support patches that intersect that cell. Clipping by every
+ // planar face in the shell incorrectly treats a non-convex whole part as one global half-space
+ // intersection (most visibly for grid-aligned prism faces in M4B).
+ foreach (var face in localCandidates.OrderBy(f => f.FaceId.Value))
{
var evidence = materialSides[face.FaceId];
if (evidence.MaterialSideNormal is not Vector3D inward)
diff --git a/Aetheris.Continuum/Boundaries/ExactSupportCompositeIntegrator.cs b/Aetheris.Continuum/Boundaries/ExactSupportCompositeIntegrator.cs
new file mode 100644
index 00000000..96d57585
--- /dev/null
+++ b/Aetheris.Continuum/Boundaries/ExactSupportCompositeIntegrator.cs
@@ -0,0 +1,174 @@
+using System.Diagnostics;
+using Aetheris.Continuum.Cir;
+using Aetheris.Continuum.Lattice;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Judgment;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Topology;
+
+namespace Aetheris.Continuum.Boundaries;
+
+internal sealed record CompositeAxisCandidateTrace(
+ string Plan,
+ bool Admissible,
+ double UtilityScore,
+ double Conditioning,
+ double EstimatedCost,
+ string? RejectionReason,
+ bool Selected);
+
+internal sealed record ExactSupportCompositeResult(
+ double OccupancyFraction,
+ double BoundaryArea,
+ IReadOnlyDictionary<string,double> BoundaryAreaByFace,
+ string Method,
+ int CirQueries,
+ int ExactSupportQueries,
+ int RayEvaluations,
+ int AdaptiveSubdivisions,
+ double EstimatedAbsoluteVolumeError,
+ double EstimatedAbsoluteAreaError,
+ bool UsedJudgmentEngine,
+ IReadOnlyList<CompositeAxisCandidateTrace> AxisCandidates,
+ double PlanningMilliseconds,
+ double IntegrationMilliseconds,
+ double RuntimeMilliseconds);
+
+/// <summary>
+/// Integrates a fixed lattice cell as a two-dimensional local composite domain. Exact support rays
+/// partition each line into CIR-classified occupied intervals. Boundary area uses the same roots and
+/// assigns each differential to its best-conditioned Cartesian projection exactly once.
+/// </summary>
+internal static class ExactSupportCompositeIntegrator
+{
+ private enum Axis { X, Y, Z }
+ private readonly record struct AxisFrame(Axis Axis,Point3D Origin,Vector3D Direction,Vector3D U,Vector3D V,double ULength,double VLength,double RayLength);
+ private sealed record AxisContext(IReadOnlyDictionary<Axis,double> Conditioning,IReadOnlyDictionary<Axis,double> Costs);
+ private sealed class Counters { public int Cir,Exact,Rays,Subdivisions;public double VolumeError,AreaError; }
+ private sealed record RayValue(double OccupiedLength,IReadOnlyDictionary<FaceId,double> AreaByFace,int RootCount);
+ private sealed record IntegralValue(double Volume,IReadOnlyDictionary<FaceId,double> AreaByFace,double VolumeError,double AreaError);
+
+ public static bool TryIntegrate(BoundingBox3D cell,IContinuumRegion region,WholeShellBoundaryQuery shell,
+ IReadOnlyList<WholeShellBoundaryCandidate> faces,bool useUtilityScoring,out ExactSupportCompositeResult? result,out string rejection)
+ {
+ var start=Stopwatch.GetTimestamp();result=null;rejection=string.Empty;
+ try
+ {
+ var frames=new[]{Frame(cell,Axis.X),Frame(cell,Axis.Y),Frame(cell,Axis.Z)};
+ var conditioning=frames.ToDictionary(f=>f.Axis,f=>Conditioning(f,shell,faces,cell));
+ var costs=frames.ToDictionary(f=>f.Axis,f=>faces.Count*(1d+(1d-conditioning[f.Axis])));
+ var usedJudgment=useUtilityScoring&&faces.Count>1;Axis selected;
+ var context=new AxisContext(conditioning,costs);var candidates=frames.Select((frame,index)=>new JudgmentCandidate<AxisContext>(
+ $"composite-rays-{frame.Axis.ToString().ToLowerInvariant()}",c=>c.Conditioning[frame.Axis]>1e-5d,
+ c=>(100d*c.Conditioning[frame.Axis])-(2d*c.Costs[frame.Axis]),
+ c=>$"conditioning {c.Conditioning[frame.Axis]:R} is tangent/degenerate",index)).ToArray();
+ JudgmentResult<AxisContext>? judgment=null;
+ if(usedJudgment){judgment=new JudgmentEngine<AxisContext>().Evaluate(context,candidates);if(!judgment.Value.IsSuccess){rejection="No admissible exact-support projection axis.";return false;}selected=Parse(judgment.Value.Selection!.Value.Candidate.Name);}
+ else if(!useUtilityScoring)selected=frames.Select(f=>f.Axis).First(axis=>conditioning[axis]>1e-5d);
+ else selected=conditioning.OrderByDescending(x=>x.Value).ThenBy(x=>x.Key).First().Key;
+ var traces=candidates.Select(c=>
+ {var axis=Parse(c.Name);var admitted=c.IsAdmissible(context);var score=admitted?c.Score(context):double.NegativeInfinity;return new CompositeAxisCandidateTrace(c.Name,admitted,score,conditioning[axis],costs[axis],admitted?null:c.RejectionReason?.Invoke(context),axis==selected);}).ToArray();
+
+ var planningMilliseconds=Stopwatch.GetElapsedTime(start).TotalMilliseconds;var integrationStart=Stopwatch.GetTimestamp();
+ var counters=new Counters();var volumeFrame=frames.Single(f=>f.Axis==selected);
+ var volumePass=IntegrateAxis(cell,region,shell,faces,volumeFrame,includeVolume:true,counters);
+ var areaByFace=new Dictionary<FaceId,double>();Add(areaByFace,volumePass.AreaByFace,1d);
+ var areaError=volumePass.AreaError;
+ foreach(var frame in frames.Where(f=>f.Axis!=selected))
+ {var pass=IntegrateAxis(cell,region,shell,faces,frame,includeVolume:false,counters);Add(areaByFace,pass.AreaByFace,1d);areaError+=pass.AreaError;}
+ var cellVolume=Volume(cell);var byFace=areaByFace.OrderBy(x=>x.Key.Value).ToDictionary(x=>x.Key.Value.ToString(),x=>x.Value,StringComparer.Ordinal);
+ result=new(double.Clamp(volumePass.Volume/cellVolume,0d,1d),byFace.Values.Sum(),byFace,
+ $"exact-support-adaptive-composite-rays-{selected.ToString().ToLowerInvariant()}",counters.Cir,counters.Exact,counters.Rays,counters.Subdivisions,
+ volumePass.VolumeError,areaError,usedJudgment,traces,planningMilliseconds,Stopwatch.GetElapsedTime(integrationStart).TotalMilliseconds,Stopwatch.GetElapsedTime(start).TotalMilliseconds);
+ return true;
+ }
+ catch(Exception ex) when(ex is InvalidOperationException or NotSupportedException or ArgumentException)
+ {rejection=ex.Message;result=null;return false;}
+ }
+
+ private static IntegralValue IntegrateAxis(BoundingBox3D cell,IContinuumRegion region,WholeShellBoundaryQuery shell,
+ IReadOnlyList<WholeShellBoundaryCandidate> faces,AxisFrame frame,bool includeVolume,Counters counters)
+ {
+ var curvedContact=faces.Any(f=>f.SupportKind==SurfaceGeometryKind.Torus)||faces.Count>=3;
+ var resolution=includeVolume?(curvedContact?12:10):12;
+ if(resolution>(includeVolume?10:8))counters.Subdivisions++;
+ var fine=StructuredMidpoint(cell,region,shell,faces,frame,resolution,includeVolume,counters);
+ // The exact line partition removes the dominant normal-direction error. This conservative
+ // footprint estimate is used for reporting/plan utility; refinement policy can promote the
+ // structured resolution without subdividing the lattice cell.
+ var cellVolume=Volume(cell);var volumeError=includeVolume?cellVolume/(resolution*resolution*4d):0d;
+ var projectedArea=frame.ULength*frame.VLength;var areaError=projectedArea/(resolution*resolution*2d);
+ counters.VolumeError+=volumeError;counters.AreaError+=areaError;return fine with{VolumeError=volumeError,AreaError=areaError};
+ }
+
+ private static IntegralValue StructuredMidpoint(BoundingBox3D cell,IContinuumRegion region,WholeShellBoundaryQuery shell,
+ IReadOnlyList<WholeShellBoundaryCandidate> faces,AxisFrame frame,int resolution,bool includeVolume,Counters counters)
+ {
+ var volume=0d;var area=new Dictionary<FaceId,double>();var du=frame.ULength/resolution;var dv=frame.VLength/resolution;var weight=du*dv;
+ for(var j=0;j<resolution;j++)for(var i=0;i<resolution;i++)
+ {
+ var sample=Sample(cell,region,shell,faces,frame,(i+.5d)*du,(j+.5d)*dv,includeVolume,counters);
+ if(includeVolume)volume+=sample.OccupiedLength*weight;Add(area,sample.AreaByFace,weight);
+ }
+ return new(volume,area,0d,0d);
+ }
+
+ private static RayValue Sample(BoundingBox3D cell,IContinuumRegion region,WholeShellBoundaryQuery shell,
+ IReadOnlyList<WholeShellBoundaryCandidate> faces,AxisFrame frame,double u,double v,bool needOccupancy,Counters counters)
+ {
+ counters.Rays++;var origin=frame.Origin+(frame.U*u)+(frame.V*v);var scale=double.Max(1d,(region.Bounds.Max-region.Bounds.Min).Length);var tolerance=scale*5e-7d;
+ var hits=new List<ExactSupportRayHit>();
+ foreach(var face in faces)
+ {
+ var roots=ExactSupportRayIntersections.Intersect(shell,face,origin,frame.Direction,0d,frame.RayLength);
+ foreach(var hit in roots)
+ {
+ counters.Exact++;
+ if(!Contains(face.Bounds,hit.Point,tolerance)||!ConeBranch(shell,face,hit.Point,tolerance))continue;
+ counters.Cir++;if(region.Classify(hit.Point,tolerance)!=ContinuumPointClassification.Boundary)continue;
+ if(hits.Any(x=>double.Abs(x.Parameter-hit.Parameter)<=frame.RayLength*2e-8d))continue;
+ hits.Add(hit);
+ }
+ }
+ hits.Sort((a,b)=>a.Parameter.CompareTo(b.Parameter));var supplemental=new List<double>();
+ if(needOccupancy&&hits.Count==0)
+ {
+ // Conservative face bounds can omit a trim-owner whose support lies exactly on a coarse
+ // cell edge. Recover only that missing partition with a bounded one-dimensional CIR scan;
+ // the production domain remains structured rays, not volumetric MSAA.
+ const int scan=16;var previous=region.Classify(origin,tolerance)!=ContinuumPointClassification.Outside;counters.Cir++;
+ for(var i=1;i<=scan;i++)
+ {
+ var t=frame.RayLength*i/scan;var current=region.Classify(origin+(frame.Direction*t),tolerance)!=ContinuumPointClassification.Outside;counters.Cir++;
+ if(current!=previous)
+ {
+ var lo=frame.RayLength*(i-1d)/scan;var hi=t;var left=previous;
+ for(var iteration=0;iteration<28;iteration++){var mid=.5d*(lo+hi);var state=region.Classify(origin+(frame.Direction*mid),tolerance)!=ContinuumPointClassification.Outside;counters.Cir++;if(state==left)lo=mid;else hi=mid;}
+ supplemental.Add(.5d*(lo+hi));
+ }
+ previous=current;
+ }
+ }
+ var occupied=0d;
+ if(needOccupancy)
+ {var nodes=new[]{0d}.Concat(hits.Select(x=>x.Parameter)).Concat(supplemental).Concat(new[]{frame.RayLength}).Order().ToArray();for(var i=0;i<nodes.Length-1;i++){if(nodes[i+1]-nodes[i]<=1e-12d)continue;var middle=.5d*(nodes[i]+nodes[i+1]);counters.Cir++;if(region.Classify(origin+(frame.Direction*middle),tolerance)!=ContinuumPointClassification.Outside)occupied+=nodes[i+1]-nodes[i];}}
+ var area=new Dictionary<FaceId,double>();foreach(var hit in hits)
+ {
+ var normal=hit.SupportNormal;if(!normal.TryNormalize(out normal))continue;var components=new[]{double.Abs(normal.X),double.Abs(normal.Y),double.Abs(normal.Z)};var owner=(Axis)Array.IndexOf(components,components.Max());
+ if(owner!=frame.Axis)continue;var projection=double.Abs(normal.Dot(frame.Direction));if(projection<=1e-10d)continue;area[hit.FaceId]=area.GetValueOrDefault(hit.FaceId)+(1d/projection);
+ }
+ return new(occupied,area,hits.Count+supplemental.Count);
+ }
+
+ private static bool ConeBranch(WholeShellBoundaryQuery shell,WholeShellBoundaryCandidate face,Point3D world,double tolerance)
+ {if(face.SupportKind!=SurfaceGeometryKind.Cone)return true;var cone=shell.Body.GetFaceSurface(face.FaceId).Cone!.Value;return cone.AxialParameterFromPoint(shell.Transform.Inverse().Apply(world))>=-tolerance;}
+ private static double Conditioning(AxisFrame frame,WholeShellBoundaryQuery shell,IReadOnlyList<WholeShellBoundaryCandidate> faces,BoundingBox3D cell)
+ {var values=new List<double>();var center=new Point3D((cell.Min.X+cell.Max.X)*.5d,(cell.Min.Y+cell.Max.Y)*.5d,(cell.Min.Z+cell.Max.Z)*.5d);foreach(var face in faces){var point=ExactSupportBoundaryQuery.ProjectToSupport(shell.Body,face.FaceId,center,shell.Transform);var normal=ExactSupportBoundaryQuery.ExactSupportNormal(shell.Body,face.FaceId,point,shell.Transform);values.Add(double.Abs(normal.Dot(frame.Direction)));}return values.Count==0?0d:values.Average();}
+ private static AxisFrame Frame(BoundingBox3D b,Axis axis)=>axis switch
+ {Axis.X=>new(axis,new(b.Min.X,b.Min.Y,b.Min.Z),new(1,0,0),new(0,1,0),new(0,0,1),b.Max.Y-b.Min.Y,b.Max.Z-b.Min.Z,b.Max.X-b.Min.X),Axis.Y=>new(axis,new(b.Min.X,b.Min.Y,b.Min.Z),new(0,1,0),new(1,0,0),new(0,0,1),b.Max.X-b.Min.X,b.Max.Z-b.Min.Z,b.Max.Y-b.Min.Y),_=>new(axis,new(b.Min.X,b.Min.Y,b.Min.Z),new(0,0,1),new(1,0,0),new(0,1,0),b.Max.X-b.Min.X,b.Max.Y-b.Min.Y,b.Max.Z-b.Min.Z)};
+ private static Axis Parse(string name)=>name.EndsWith("-x",StringComparison.Ordinal)?Axis.X:name.EndsWith("-y",StringComparison.Ordinal)?Axis.Y:Axis.Z;
+ private static bool Contains(BoundingBox3D b,Point3D p,double t)=>p.X>=b.Min.X-t&&p.X<=b.Max.X+t&&p.Y>=b.Min.Y-t&&p.Y<=b.Max.Y+t&&p.Z>=b.Min.Z-t&&p.Z<=b.Max.Z+t;
+ private static double Volume(BoundingBox3D b)=>(b.Max.X-b.Min.X)*(b.Max.Y-b.Min.Y)*(b.Max.Z-b.Min.Z);
+ private static void Add(Dictionary<FaceId,double> target,IReadOnlyDictionary<FaceId,double> source,double factor){foreach(var pair in source)target[pair.Key]=target.GetValueOrDefault(pair.Key)+(pair.Value*factor);}
+}
diff --git a/Aetheris.Continuum/Boundaries/ExactSupportRayIntersections.cs b/Aetheris.Continuum/Boundaries/ExactSupportRayIntersections.cs
new file mode 100644
index 00000000..3a3976fd
--- /dev/null
+++ b/Aetheris.Continuum/Boundaries/ExactSupportRayIntersections.cs
@@ -0,0 +1,115 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Geometry.Surfaces;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Topology;
+
+namespace Aetheris.Continuum.Boundaries;
+
+internal readonly record struct ExactSupportRayHit(
+ double Parameter,
+ Point3D Point,
+ Vector3D SupportNormal,
+ FaceId FaceId,
+ SurfaceGeometryKind SupportKind);
+
+/// <summary>
+/// Deterministic bounded ray intersections for the M4C support family. Torus intersections use
+/// derivative-partitioned quartic root isolation, so two visible branches are retained without
+/// assuming that the torus is one height map.
+/// </summary>
+internal static class ExactSupportRayIntersections
+{
+ public static IReadOnlyList<ExactSupportRayHit> Intersect(WholeShellBoundaryQuery shell,
+ WholeShellBoundaryCandidate face, Point3D worldOrigin, Vector3D worldDirection,
+ double minimumParameter, double maximumParameter)
+ {
+ var inverse=shell.Transform.Inverse();var origin=inverse.Apply(worldOrigin);var direction=inverse.Apply(worldDirection);
+ if(!direction.TryNormalize(out direction))throw new InvalidOperationException("Composite ray direction is degenerate.");
+ var surface=shell.Body.GetFaceSurface(face.FaceId);var coefficients=Coefficients(surface,origin,direction);
+ var roots=RealPolynomialRoots.InInterval(coefficients,minimumParameter,maximumParameter);
+ return roots.Select(t=>
+ {
+ var point=worldOrigin+(worldDirection*t);
+ var normal=ExactSupportBoundaryQuery.ExactSupportNormal(shell.Body,face.FaceId,point,shell.Transform);
+ return new ExactSupportRayHit(t,point,normal,face.FaceId,face.SupportKind);
+ }).ToArray();
+ }
+
+ private static double[] Coefficients(SurfaceGeometry surface,Point3D origin,Vector3D direction)=>surface.Kind switch
+ {
+ SurfaceGeometryKind.Plane=>Plane(surface.Plane!.Value,origin,direction),
+ SurfaceGeometryKind.Cylinder=>Cylinder(surface.Cylinder!.Value,origin,direction),
+ SurfaceGeometryKind.Cone=>Cone(surface.Cone!.Value,origin,direction),
+ SurfaceGeometryKind.Torus=>Torus(surface.Torus!.Value,origin,direction),
+ _=>throw new NotSupportedException($"Exact composite rays do not support {surface.Kind}.")
+ };
+
+ private static double[] Plane(PlaneSurface s,Point3D o,Vector3D d)
+ {var n=s.Normal.ToVector();return[(o-s.Origin).Dot(n),d.Dot(n)];}
+
+ private static double[] Cylinder(CylinderSurface s,Point3D o,Vector3D d)
+ {
+ var axis=s.Axis.ToVector();var delta=o-s.Origin;
+ var r0=delta-(axis*delta.Dot(axis));var rd=d-(axis*d.Dot(axis));
+ return[r0.LengthSquared-(s.Radius*s.Radius),2d*r0.Dot(rd),rd.LengthSquared];
+ }
+
+ private static double[] Cone(ConeSurface s,Point3D o,Vector3D d)
+ {
+ var axis=s.Axis.ToVector();var delta=o-s.Apex;var a0=delta.Dot(axis);var ad=d.Dot(axis);
+ var r0=delta-(axis*a0);var rd=d-(axis*ad);var tangent=double.Tan(s.SemiAngleRadians);var t2=tangent*tangent;
+ return[r0.LengthSquared-(t2*a0*a0),2d*(r0.Dot(rd)-(t2*a0*ad)),rd.LengthSquared-(t2*ad*ad)];
+ }
+
+ private static double[] Torus(TorusSurface s,Point3D o,Vector3D d)
+ {
+ var q=o-s.Center;var axis=s.Axis.ToVector();var qd=q.Dot(d);var qa=q.Dot(axis);var da=d.Dot(axis);
+ var radiusTerm=(s.MajorRadius*s.MajorRadius)-(s.MinorRadius*s.MinorRadius);
+ var a0=q.LengthSquared+radiusTerm;var a1=2d*qd;var a2=d.LengthSquared;
+ var b0=q.LengthSquared-(qa*qa);var b1=2d*(qd-(qa*da));var b2=d.LengthSquared-(da*da);
+ return[
+ (a0*a0)-(4d*s.MajorRadius*s.MajorRadius*b0),
+ 2d*a0*a1-(4d*s.MajorRadius*s.MajorRadius*b1),
+ (a1*a1)+(2d*a0*a2)-(4d*s.MajorRadius*s.MajorRadius*b2),
+ 2d*a1*a2,
+ a2*a2];
+ }
+}
+
+internal static class RealPolynomialRoots
+{
+ public static IReadOnlyList<double> InInterval(IReadOnlyList<double> ascending,double minimum,double maximum)
+ {
+ if(!(minimum<=maximum))throw new ArgumentOutOfRangeException(nameof(minimum));
+ var coefficients=Trim(ascending.ToArray());var roots=Find(coefficients,minimum,maximum);
+ var scale=double.Max(1d,maximum-minimum);var tolerance=scale*2e-10d;
+ return roots.Where(x=>x>=minimum-tolerance&&x<=maximum+tolerance).Select(x=>double.Clamp(x,minimum,maximum))
+ .Order().Aggregate(new List<double>(),(list,value)=>{if(list.Count==0||double.Abs(value-list[^1])>tolerance)list.Add(value);return list;});
+ }
+
+ private static List<double> Find(double[] c,double minimum,double maximum)
+ {
+ var degree=c.Length-1;if(degree<=0)return[];
+ if(degree==1)return double.Abs(c[1])<=1e-18d?[]:[-c[0]/c[1]];
+ var derivative=new double[degree];for(var i=1;i<c.Length;i++)derivative[i-1]=i*c[i];
+ var stationary=Find(Trim(derivative),minimum,maximum).Where(x=>x>minimum&&x<maximum).Order().ToArray();
+ var points=new[]{minimum}.Concat(stationary).Concat(new[]{maximum}).ToArray();var roots=new List<double>();
+ foreach(var point in points){var value=Evaluate(c,point);if(double.Abs(value)<=Tolerance(c,point))roots.Add(point);}
+ for(var i=0;i<points.Length-1;i++)
+ {
+ var left=points[i];var right=points[i+1];var fl=Evaluate(c,left);var fr=Evaluate(c,right);
+ if(fl==0d||fr==0d||double.Sign(fl)==double.Sign(fr))continue;
+ for(var iteration=0;iteration<80;iteration++)
+ {var mid=.5d*(left+right);var fm=Evaluate(c,mid);if(double.Abs(fm)<=Tolerance(c,mid)||right-left<=2e-12d*double.Max(1d,double.Abs(mid))){left=right=mid;break;}if(double.Sign(fl)==double.Sign(fm)){left=mid;fl=fm;}else{right=mid;fr=fm;}}
+ roots.Add(.5d*(left+right));
+ }
+ return roots;
+ }
+
+ private static double[] Trim(double[] values)
+ {var scale=values.Select(double.Abs).DefaultIfEmpty().Max();var n=values.Length;while(n>1&&double.Abs(values[n-1])<=double.Max(1e-18d,scale*1e-14d))n--;return values[..n];}
+ private static double Evaluate(IReadOnlyList<double> c,double x){var value=0d;for(var i=c.Count-1;i>=0;i--)value=(value*x)+c[i];return value;}
+ private static double Tolerance(IReadOnlyList<double> c,double x)
+ {var scale=0d;var power=1d;foreach(var value in c){scale+=double.Abs(value)*power;power*=double.Max(1d,double.Abs(x));}return double.Max(1e-12d,scale*2e-11d);}
+}
diff --git a/Aetheris.Continuum/Boundaries/WholePartBoundaryMapFactory.cs b/Aetheris.Continuum/Boundaries/WholePartBoundaryMapFactory.cs
new file mode 100644
index 00000000..4e45d9c9
--- /dev/null
+++ b/Aetheris.Continuum/Boundaries/WholePartBoundaryMapFactory.cs
@@ -0,0 +1,180 @@
+using Aetheris.Continuum.Cir;
+using Aetheris.Continuum.Lattice;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Geometry.Surfaces;
+using Aetheris.Kernel.Core.Math;
+
+namespace Aetheris.Continuum.Boundaries;
+
+/// <summary>
+/// Builds the same small tangent-graph representation used by the isolated M1-M3 paths directly
+/// from a whole-shell face. Exact BRep support remains the differential authority, while CIR probes
+/// validate material side and trim ownership. No tessellation is consulted.
+/// </summary>
+internal static class WholePartBoundaryMapFactory
+{
+ private readonly record struct Point2(double U, double V);
+
+ public static bool TryBuild(CellIndex index, BoundingBox3D cell, IContinuumRegion region, WholeShellBoundaryQuery shell,
+ WholeShellBoundaryCandidate face, MaterialSideEvidence side, BoundaryEvaluationCache cache,
+ out SampledBoundaryOffsetMap? map, out string rejection)
+ {
+ map = null; rejection = string.Empty;
+ if (face.SupportKind is not (SurfaceGeometryKind.Cylinder or SurfaceGeometryKind.Cone or SurfaceGeometryKind.Torus))
+ { rejection = "support has a direct non-map path"; return false; }
+ if (side.MaterialSideNormal is not Vector3D materialNormal)
+ { rejection = "material-side evidence is unresolved"; return false; }
+
+ try
+ {
+ var center = Center(cell);
+ var origin = ExactSupportBoundaryQuery.ProjectToSupport(shell.Body, face.FaceId, center, shell.Transform);
+ var support = shell.Body.GetFaceSurface(face.FaceId);
+ var tangentU = GeneratorDirection(support, origin, shell.Transform, materialNormal);
+ tangentU -= materialNormal * tangentU.Dot(materialNormal);
+ if (!tangentU.TryNormalize(out tangentU)) throw new InvalidOperationException("support-local generator is degenerate");
+ var tangentV = materialNormal.Cross(tangentU);
+ if (!tangentV.TryNormalize(out tangentV)) throw new InvalidOperationException("support-local transverse direction is degenerate");
+ var frame = new BoundaryLocalFrame(origin, materialNormal, tangentU, tangentV);
+ var projected = Corners(cell).Select(p => p - origin).ToArray();
+ var domain = new BoundaryMapDomain(projected.Min(p => p.Dot(tangentU)), projected.Max(p => p.Dot(tangentU)),
+ projected.Min(p => p.Dot(tangentV)), projected.Max(p => p.Dot(tangentV)));
+ domain=AdmissibleGraphDomain(support,origin,shell.Transform,domain);
+ var (nu, nv) = Resolution(support, domain, cell);
+ var certificate = new EngineeringBoundaryMapCertificate(BoundaryMapCertificateDecision.Acceptable,
+ PositionErrorBound(support, domain, nu, nv), NormalErrorDegrees(support, domain, nu, nv), nu * nv,
+ "support-family curvature bound with anisotropic generator/transverse resolution");
+ var frameKey = $"{face.Reference.SourceId}:{origin.X:R}:{origin.Y:R}:{origin.Z:R}";
+ ExactBoundaryEvaluation Exact(double u, double v)
+ {
+ var basePoint = origin + (tangentU * u) + (tangentV * v);
+ var offset = SolveOffset(support, basePoint, materialNormal, shell.Transform);
+ var boundary = basePoint + (materialNormal * offset);
+ var normal = ExactSupportBoundaryQuery.ExactSupportNormal(shell.Body, face.FaceId, boundary, shell.Transform);
+ if (normal.Dot(materialNormal) < 0d) normal = -normal;
+ return new(offset, normal);
+ }
+ // Reject a non-graph chart before allocating/filling its sample grid. Coarse whole-part
+ // cells commonly span a torus/cylinder tangent horizon; probing the four domain corners
+ // makes that invalidity cheap and deterministic instead of discovering it late in Build.
+ _=Exact(domain.MinimumU,domain.MinimumV);_=Exact(domain.MaximumU,domain.MinimumV);
+ _=Exact(domain.MinimumU,domain.MaximumV);_=Exact(domain.MaximumU,domain.MaximumV);
+ var scale = double.Max(1d, (shell.Bounds.Max - shell.Bounds.Min).Length);
+ map = RuntimeBoundaryMapBuild.Build(index, face.Reference, frame, domain, nu, nv,
+ new BoundaryOffsetMapErrorPolicy(scale * 2e-5d, .5d, 24), Exact,
+ (u, v) => new BoundaryEvaluationKey(frameKey, nu, nv, BitConverter.DoubleToInt64Bits(u), BitConverter.DoubleToInt64Bits(v)),
+ cache, certificate, trimSignedDistance: point =>
+ {
+ var exactPoint=ExactSupportBoundaryQuery.ProjectToSupport(shell.Body,face.FaceId,point,shell.Transform);
+ // Curved global trims need not remain convex in one tangent chart. The exact sampled
+ // face bounds are therefore the conservative ownership gate, with CIR confirming that
+ // the projected point belongs to the complete material boundary.
+ var trimDistance=AabbSignedDistance(face.Bounds,exactPoint);
+ return region.Classify(exactPoint, scale * 2e-7d) == ContinuumPointClassification.Boundary
+ ? double.Max(1e-12d,trimDistance) : -double.Max(1e-12d,double.Abs(trimDistance));
+ });
+ return true;
+ }
+ catch (Exception ex) when (ex is InvalidOperationException or ArgumentException)
+ { rejection = ex.Message; map = null; return false; }
+
+ }
+
+ private static Vector3D GeneratorDirection(SurfaceGeometry support, Point3D worldOrigin, Transform3D transform, Vector3D normal)
+ {
+ if (support.Cylinder is CylinderSurface cylinder) return transform.Apply(cylinder.Axis).ToVector();
+ if (support.Cone is ConeSurface cone)
+ {
+ var local = transform.Inverse().Apply(worldOrigin); var delta = local - cone.Apex;
+ var axial = delta.Dot(cone.Axis.ToVector()); var radial = delta - (cone.Axis.ToVector() * axial);
+ if (!radial.TryNormalize(out radial)) radial = cone.ReferenceAxis.ToVector();
+ return transform.Apply(Direction3D.Create(cone.Axis.ToVector() + (radial * double.Tan(cone.SemiAngleRadians)))).ToVector();
+ }
+ if (support.Torus is TorusSurface torus)
+ {
+ var local = transform.Inverse().Apply(worldOrigin); var delta = local - torus.Center;
+ var axial = delta.Dot(torus.Axis.ToVector()); var radial = delta - (torus.Axis.ToVector() * axial);
+ if (!radial.TryNormalize(out radial)) radial = torus.XAxis.ToVector();
+ var azimuth = torus.Axis.ToVector().Cross(radial);
+ return transform.Apply(Direction3D.Create(azimuth)).ToVector();
+ }
+ var seed = double.Abs(normal.X) < .8d ? new Vector3D(1, 0, 0) : new Vector3D(0, 1, 0);
+ return seed - (normal * seed.Dot(normal));
+ }
+
+ private static (int U, int V) Resolution(SurfaceGeometry support, BoundaryMapDomain domain, BoundingBox3D cell)
+ {
+ var extentU = domain.MaximumU - domain.MinimumU; var extentV = domain.MaximumV - domain.MinimumV;
+ var scale = double.Max(extentU, extentV); var radius = support.Cylinder?.Radius
+ ?? (support.Cone is { } cone ? double.Max(scale, cone.PlacementRadius) : support.Torus!.Value.MinorRadius);
+ var curved = int.Clamp(4 + (int)double.Ceiling(4d * scale / double.Max(radius, scale * .2d)), 6, 16);
+ return support.Kind switch
+ {
+ SurfaceGeometryKind.Cylinder => (3, curved),
+ SurfaceGeometryKind.Cone => (4, curved),
+ SurfaceGeometryKind.Torus => (int.Clamp(curved / 2, 4, 12), curved),
+ _ => (6, 6),
+ };
+ }
+
+ private static BoundaryMapDomain AdmissibleGraphDomain(SurfaceGeometry support,Point3D worldOrigin,Transform3D transform,BoundaryMapDomain d)
+ {
+ static (double,double) Limit(double lo,double hi,double radius){var h=.72d*radius;return(double.Max(lo,-h),double.Min(hi,h));}
+ if(support.Cylinder is { } cylinder){var v=Limit(d.MinimumV,d.MaximumV,cylinder.Radius);return new(d.MinimumU,d.MaximumU,v.Item1,v.Item2);}
+ if(support.Cone is { } cone){var local=transform.Inverse().Apply(worldOrigin);var radius=double.Max(1e-6d,cone.AxialParameterFromPoint(local)*double.Tan(cone.SemiAngleRadians));var v=Limit(d.MinimumV,d.MaximumV,radius);return new(d.MinimumU,d.MaximumU,v.Item1,v.Item2);}
+ var torus=support.Torus!.Value;var u=Limit(d.MinimumU,d.MaximumU,torus.MajorRadius+torus.MinorRadius);var v2=Limit(d.MinimumV,d.MaximumV,torus.MinorRadius);return new(u.Item1,u.Item2,v2.Item1,v2.Item2);
+ }
+
+ private static double SolveOffset(SurfaceGeometry support, Point3D worldBase, Vector3D worldNormal, Transform3D transform)
+ {
+ var inverse = transform.Inverse(); var localBase = inverse.Apply(worldBase);
+ var localDirection = inverse.Apply(worldNormal); if (!localDirection.TryNormalize(out localDirection)) throw new InvalidOperationException("invalid local graph direction");
+ var characteristic=support.Cylinder?.Radius??support.Torus?.MinorRadius??double.Max(1d,support.Cone?.PlacementRadius??1d);
+ var w = 0d;
+ for (var i = 0; i < 32; i++)
+ {
+ var p = localBase + (localDirection * w); var (f, gradient) = Implicit(support, p);
+ if (double.Abs(f) <= 1e-10d*double.Max(1d,characteristic*characteristic)) return w;
+ var derivative = gradient.Dot(localDirection);
+ if (double.Abs(derivative) <= 1e-10d) throw new InvalidOperationException("height-map tangent horizon");
+ var step=double.Clamp(f/derivative,-characteristic,characteristic);var next=w-step;
+ for(var line=0;line<8;line++)
+ {var trial=Implicit(support,localBase+(localDirection*next)).F;if(double.Abs(trial)<double.Abs(f))break;step*=.5d;next=w-step;}
+ w=next;
+ if (!double.IsFinite(w)) throw new InvalidOperationException("height-map root did not remain finite");
+ }
+ throw new InvalidOperationException("height-map root did not converge");
+ }
+
+ private static (double F, Vector3D Gradient) Implicit(SurfaceGeometry support, Point3D p)
+ {
+ if (support.Cylinder is CylinderSurface cylinder)
+ { var d=p-cylinder.Origin;var axial=d.Dot(cylinder.Axis.ToVector());var radial=d-(cylinder.Axis.ToVector()*axial);return(radial.LengthSquared-cylinder.Radius*cylinder.Radius,radial*2d); }
+ if (support.Cone is ConeSurface cone)
+ { var d=p-cone.Apex;var axial=d.Dot(cone.Axis.ToVector());var radial=d-(cone.Axis.ToVector()*axial);var t=double.Tan(cone.SemiAngleRadians);return(radial.LengthSquared-axial*axial*t*t,(radial*2d)-(cone.Axis.ToVector()*(2d*axial*t*t))); }
+ var torus=support.Torus!.Value;var q=p-torus.Center;var z=q.Dot(torus.Axis.ToVector());var rv=q-(torus.Axis.ToVector()*z);var rho=rv.Length;
+ if(rho<=1e-12d)throw new InvalidOperationException("torus graph reached axis");var ro=rho-torus.MajorRadius;
+ return(ro*ro+z*z-torus.MinorRadius*torus.MinorRadius,(rv*(2d*ro/rho))+(torus.Axis.ToVector()*(2d*z)));
+ }
+
+ private static double PositionErrorBound(SurfaceGeometry support, BoundaryMapDomain domain, int nu, int nv)
+ { var h=double.Max((domain.MaximumU-domain.MinimumU)/(nu-1),(domain.MaximumV-domain.MinimumV)/(nv-1));var r=support.Cylinder?.Radius??support.Torus?.MinorRadius??double.Max(h,support.Cone?.PlacementRadius??h);return h*h/(4d*double.Max(r,1e-9d)); }
+ private static double NormalErrorDegrees(SurfaceGeometry support, BoundaryMapDomain domain, int nu, int nv)
+ { var h=double.Max((domain.MaximumU-domain.MinimumU)/(nu-1),(domain.MaximumV-domain.MinimumV)/(nv-1));var r=support.Cylinder?.Radius??support.Torus?.MinorRadius??double.Max(h,support.Cone?.PlacementRadius??h);return h/double.Max(r,1e-9d)*180d/double.Pi; }
+ private static Point3D Center(BoundingBox3D b)=>new((b.Min.X+b.Max.X)*.5d,(b.Min.Y+b.Max.Y)*.5d,(b.Min.Z+b.Max.Z)*.5d);
+ private static double AabbSignedDistance(BoundingBox3D b,Point3D p)=>double.Min(double.Min(double.Min(p.X-b.Min.X,b.Max.X-p.X),double.Min(p.Y-b.Min.Y,b.Max.Y-p.Y)),double.Min(p.Z-b.Min.Z,b.Max.Z-p.Z));
+ private static Point3D[] Corners(BoundingBox3D b)=>[new(b.Min.X,b.Min.Y,b.Min.Z),new(b.Max.X,b.Min.Y,b.Min.Z),new(b.Min.X,b.Max.Y,b.Min.Z),new(b.Max.X,b.Max.Y,b.Min.Z),new(b.Min.X,b.Min.Y,b.Max.Z),new(b.Max.X,b.Min.Y,b.Max.Z),new(b.Min.X,b.Max.Y,b.Max.Z),new(b.Max.X,b.Max.Y,b.Max.Z)];
+
+ internal sealed class ProjectedTrimDomain
+ {
+ private readonly Point2[] _hull;
+ private ProjectedTrimDomain(Point2[] hull)=>_hull=hull;
+ public static ProjectedTrimDomain Create(IEnumerable<Point3D> samples,BoundaryLocalFrame frame)
+ {var p=samples.Select(x=>x-frame.Origin).Select(x=>new Point2(x.Dot(frame.TangentU),x.Dot(frame.TangentV))).Distinct().OrderBy(x=>x.U).ThenBy(x=>x.V).ToArray();return new(Hull(p));}
+ public double SignedDistance(double u,double v)
+ {if(_hull.Length<3)return double.PositiveInfinity;var point=new Point2(u,v);var minimum=double.PositiveInfinity;for(var i=0;i<_hull.Length;i++){var a=_hull[i];var b=_hull[(i+1)%_hull.Length];var edge=new Point2(b.U-a.U,b.V-a.V);var cross=edge.U*(point.V-a.V)-edge.V*(point.U-a.U);minimum=double.Min(minimum,cross/double.Sqrt(edge.U*edge.U+edge.V*edge.V));}return minimum;}
+ private static Point2[] Hull(Point2[] p){if(p.Length<=2)return p;var lo=new List<Point2>();foreach(var x in p){while(lo.Count>=2&&Cross(lo[^2],lo[^1],x)<=1e-14)lo.RemoveAt(lo.Count-1);lo.Add(x);}var hi=new List<Point2>();for(var i=p.Length-1;i>=0;i--){var x=p[i];while(hi.Count>=2&&Cross(hi[^2],hi[^1],x)<=1e-14)hi.RemoveAt(hi.Count-1);hi.Add(x);}lo.RemoveAt(lo.Count-1);hi.RemoveAt(hi.Count-1);lo.AddRange(hi);return lo.ToArray();}
+ private static double Cross(Point2 a,Point2 b,Point2 c)=>(b.U-a.U)*(c.V-a.V)-(b.V-a.V)*(c.U-a.U);
+ }
+}
diff --git a/Aetheris.Continuum/Boundaries/WholePartComposition.cs b/Aetheris.Continuum/Boundaries/WholePartComposition.cs
index 15ea872d..7768cd67 100644
--- a/Aetheris.Continuum/Boundaries/WholePartComposition.cs
+++ b/Aetheris.Continuum/Boundaries/WholePartComposition.cs
@@ -60,7 +60,15 @@ public sealed record LocalBoundaryIntegration(
double BoundaryArea,
IReadOnlyDictionary<string, double> BoundaryAreaByFace,
string Method,
- int CirQueries);
+ int CirQueries,
+ int ExactSupportQueries = 0,
+ int BoundaryMapEvaluations = 0,
+ int AdaptiveSubdivisions = 0,
+ int MsaaFallbackSamples = 0,
+ double RuntimeMilliseconds = 0d,
+ IReadOnlyDictionary<string, string>? StrategyProvenance = null,
+ double? EstimatedAbsoluteVolumeError = null,
+ double? EstimatedAbsoluteAreaError = null);
public sealed record CutCellBoundarySet(
CellIndex CellIndex,
@@ -124,13 +132,21 @@ public sealed class WholePartCutCellComposer
private readonly IContinuumRegion _region;
private readonly WholeShellBoundaryQuery _shell;
private readonly IReadOnlyDictionary<FaceId, MaterialSideEvidence> _materialSides;
+ private readonly bool _useUtilityScoredIntegrationPlans;
private readonly JudgmentEngine<CompositionContext> _engine = new();
private int _judgmentCalls;
private double _judgmentMilliseconds;
+ private readonly BoundaryEvaluationCache _mapCache = new();
+ private int _integrationJudgmentCalls;
+ private double _mapConstructionMilliseconds;
+ private double _integrationPlanningMilliseconds;
+ private double _compositeIntegrationMilliseconds;
+ private double _fallbackSamplingMilliseconds;
- public WholePartCutCellComposer(IContinuumRegion region, WholeShellBoundaryQuery shell)
+ public WholePartCutCellComposer(IContinuumRegion region, WholeShellBoundaryQuery shell,bool useUtilityScoredIntegrationPlans=true)
{
_region = region ?? throw new ArgumentNullException(nameof(region)); _shell = shell ?? throw new ArgumentNullException(nameof(shell));
+ _useUtilityScoredIntegrationPlans=useUtilityScoredIntegrationPlans;
if (region.Id != shell.Association.ContinuumRegionId) throw new ArgumentException("CIR/BRep association does not name the supplied region.", nameof(shell));
var consistency = BrepCirConsistencyChecker.Check(region, shell);
if (!consistency.Passed) throw new InvalidOperationException(consistency.Summary);
@@ -143,10 +159,17 @@ public sealed class WholePartCutCellComposer
public BrepCirConsistencyResult Consistency { get; }
public int JudgmentCallCount => _judgmentCalls;
public double JudgmentRuntimeMilliseconds => _judgmentMilliseconds;
+ public BoundaryEvaluationCache MapCache => _mapCache;
+ public int IntegrationJudgmentCallCount => _integrationJudgmentCalls;
+ public double MapConstructionMilliseconds => _mapConstructionMilliseconds;
+ public double IntegrationPlanningMilliseconds => _integrationPlanningMilliseconds;
+ public double CompositeIntegrationMilliseconds => _compositeIntegrationMilliseconds;
+ public double FallbackSamplingMilliseconds => _fallbackSamplingMilliseconds;
public IReadOnlyDictionary<FaceId,MaterialSideEvidence> MaterialSides => _materialSides;
public CutCellBoundarySet Compose(CellIndex index, BoundingBox3D bounds)
{
+ var integrationStart=Stopwatch.GetTimestamp();
var candidates = _shell.Query(bounds);
if (candidates.Count == 0) throw new InvalidOperationException($"Cut cell {index} has no bounded exact BRep face candidate.");
var kind = Classify(candidates);
@@ -154,11 +177,49 @@ public sealed class WholePartCutCellComposer
var ambiguous = candidates.Any(c => _materialSides[c.FaceId].Status != MaterialSideStatus.Resolved)
|| kind is CutCellCompositionKind.MultiFaceTrimJunction or CutCellCompositionKind.GeneralBoundedMultiFace;
if (ambiguous) (kind, trace) = Judge(candidates, kind);
+ var maps=new Dictionary<FaceId,(SampledBoundaryOffsetMap Map,StructuredBoundaryMapCellEstimate Estimate)>();
+ var provenance=new Dictionary<string,string>(StringComparer.Ordinal);var exactQueries=0;var mapEvaluations=0;var subdivisions=0;
+ var mapStart=Stopwatch.GetTimestamp();
+ foreach(var candidate in candidates.Where(c=>c.SupportKind!=SurfaceGeometryKind.Plane).OrderBy(c=>c.FaceId.Value))
+ {
+ if(WholePartBoundaryMapFactory.TryBuild(index,bounds,_region,_shell,candidate,_materialSides[candidate.FaceId],_mapCache,out var map,out var rejection)&&map is not null)
+ {
+ var estimate=BoundaryOffsetMap3DIntegrator.IntegrateSurfacePatch(map,bounds);
+ maps[candidate.FaceId]=(map,estimate);exactQueries+=map.Samples.Count;mapEvaluations+=map.Samples.Count;
+ subdivisions+=estimate.Diagnostics.AdaptiveSubdivisions;provenance[candidate.FaceId.Value.ToString()]=$"{candidate.SupportKind}-local-map:{map.Approximation.ResolutionU}x{map.Approximation.ResolutionV}";
+ }
+ else provenance[candidate.FaceId.Value.ToString()]=$"map-rejected:{rejection}";
+ }
+ _mapConstructionMilliseconds+=Stopwatch.GetElapsedTime(mapStart).TotalMilliseconds;
var contributors = candidates.Select(c => new CutCellBoundaryContributor(c.Reference, c.SupportKind, c.EdgeIds, c.VertexIds,
- c.AdjacentFaceIds, _materialSides[c.FaceId])).ToArray();
- var integration = candidates.All(c => c.SupportKind == SurfaceGeometryKind.Plane)
- ? ConvexPlanarCellIntegrator.Integrate(bounds, _shell, _materialSides)
- : SampleFallback(bounds, candidates, 12);
+ c.AdjacentFaceIds, _materialSides[c.FaceId],maps.TryGetValue(c.FaceId,out var row)?row.Map:null)).ToArray();
+ LocalBoundaryIntegration integration;
+ if(candidates.All(c=>c.SupportKind==SurfaceGeometryKind.Plane))integration=ConvexPlanarCellIntegrator.Integrate(bounds,_shell,_materialSides,candidates);
+ else
+ {
+ if(ExactSupportCompositeIntegrator.TryIntegrate(bounds,_region,_shell,candidates,_useUtilityScoredIntegrationPlans,out var composite,out var compositeRejection)&&composite is not null)
+ {
+ if(composite.UsedJudgmentEngine)_integrationJudgmentCalls++;
+ _integrationPlanningMilliseconds+=composite.PlanningMilliseconds;
+ _compositeIntegrationMilliseconds+=composite.IntegrationMilliseconds;
+ foreach(var axis in composite.AxisCandidates)provenance[$"plan:{axis.Plan}"]=$"admissible={axis.Admissible};utility={axis.UtilityScore:R};conditioning={axis.Conditioning:R};cost={axis.EstimatedCost:R};selected={axis.Selected};rejection={axis.RejectionReason}";
+ integration=new(composite.OccupancyFraction,composite.BoundaryArea,composite.BoundaryAreaByFace,composite.Method,
+ composite.CirQueries,exactQueries+composite.ExactSupportQueries,mapEvaluations,subdivisions+composite.AdaptiveSubdivisions,0,0d,provenance,
+ composite.EstimatedAbsoluteVolumeError,composite.EstimatedAbsoluteAreaError);
+ }
+ else
+ {
+ var fallbackStart=Stopwatch.GetTimestamp();provenance["composite-rejection"]=compositeRejection;var fallback=SampleFallback(bounds,candidates,12);var areaByFace=new Dictionary<string,double>(StringComparer.Ordinal);var planeQueries=0;
+ foreach(var candidate in candidates.OrderBy(c=>c.FaceId.Value))
+ {
+ if(maps.TryGetValue(candidate.FaceId,out var mapped))areaByFace[candidate.FaceId.Value.ToString()]=mapped.Estimate.Estimate.BoundaryArea;
+ else if(candidate.SupportKind==SurfaceGeometryKind.Plane){var planar=WholePartPlanarPatchIntegrator.Integrate(bounds,_region,_shell,candidate);areaByFace[candidate.FaceId.Value.ToString()]=planar.Area;planeQueries+=planar.CirQueries;}
+ }
+ _fallbackSamplingMilliseconds+=Stopwatch.GetElapsedTime(fallbackStart).TotalMilliseconds;
+ integration=new(fallback.OccupancyFraction,areaByFace.Values.Sum(),areaByFace,"bounded-MSAA-after-composite-rejection",fallback.CirQueries+planeQueries,exactQueries,mapEvaluations,subdivisions,fallback.CirQueries,0d,provenance);
+ }
+ }
+ integration=integration with{RuntimeMilliseconds=Stopwatch.GetElapsedTime(integrationStart).TotalMilliseconds};
var center = new Point3D((bounds.Min.X + bounds.Max.X) * .5d, (bounds.Min.Y + bounds.Max.Y) * .5d, (bounds.Min.Z + bounds.Max.Z) * .5d);
return new(index, _region.Id, contributors, kind, _region.Classify(center), trace, integration);
}
@@ -219,7 +280,7 @@ public sealed class WholePartCutCellComposer
for(var k=0;k<n;k++)for(var j=0;j<n;j++)for(var i=0;i<n;i++)
{var p=Sample(i,j,k);if(i+1<n&&occupied[i,j,k]!=occupied[i+1,j,k])area+=dy*dz*Correct(new Point3D(p.X+dx*.5,p.Y,p.Z));if(j+1<n&&occupied[i,j,k]!=occupied[i,j+1,k])area+=dx*dz*Correct(new Point3D(p.X,p.Y+dy*.5,p.Z));if(k+1<n&&occupied[i,j,k]!=occupied[i,j,k+1])area+=dx*dy*Correct(new Point3D(p.X,p.Y,p.Z+dz*.5));}
var share=candidates.Count==0?0d:area/candidates.Count;var byFace=candidates.ToDictionary(c=>c.FaceId.Value.ToString(),_=>share);
- return new(inside/(double)(n*n*n),area,byFace,"bounded-CIR-MSAA-volume-and-gradient-corrected-Crofton-area",n*n*n);
+ return new(inside/(double)(n*n*n),area,byFace,"bounded-CIR-MSAA-volume-and-gradient-corrected-Crofton-area",n*n*n,MsaaFallbackSamples:n*n*n);
}
private static double Lerp(double a,double b,double t)=>a+(b-a)*t;
private static Point3D Centroid(IEnumerable<Point3D> points) { var a=points.ToArray(); return new(a.Average(p=>p.X),a.Average(p=>p.Y),a.Average(p=>p.Z)); }
diff --git a/Aetheris.Continuum/Boundaries/WholePartPlanarPatchIntegrator.cs b/Aetheris.Continuum/Boundaries/WholePartPlanarPatchIntegrator.cs
new file mode 100644
index 00000000..c21c04d5
--- /dev/null
+++ b/Aetheris.Continuum/Boundaries/WholePartPlanarPatchIntegrator.cs
@@ -0,0 +1,35 @@
+using Aetheris.Continuum.Cir;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Math;
+
+namespace Aetheris.Continuum.Boundaries;
+
+/// <summary>Face-owned planar area quadrature over the exact plane and BRep-derived trim hull.</summary>
+internal static class WholePartPlanarPatchIntegrator
+{
+ public static (double Area, int CirQueries) Integrate(BoundingBox3D cell, IContinuumRegion region,
+ WholeShellBoundaryQuery shell, WholeShellBoundaryCandidate face, int resolution = 20)
+ {
+ var surface = shell.Body.GetFaceSurface(face.FaceId).Plane!.Value;
+ var origin = shell.Transform.Apply(surface.Origin);
+ var u = shell.Transform.Apply(surface.UAxis).ToVector(); var v = shell.Transform.Apply(surface.VAxis).ToVector();
+ u.TryNormalize(out u); v.TryNormalize(out v);
+ var normal = shell.Transform.Apply(surface.Normal).ToVector(); normal.TryNormalize(out normal);
+ var frame = new BoundaryLocalFrame(origin, normal, u, v);
+ var trim = WholePartBoundaryMapFactory.ProjectedTrimDomain.Create(face.ExactBoundarySamples, frame);
+ var corners = Corners(cell).Select(p => p - origin).ToArray();
+ var u0=corners.Min(p=>p.Dot(u));var u1=corners.Max(p=>p.Dot(u));var v0=corners.Min(p=>p.Dot(v));var v1=corners.Max(p=>p.Dot(v));
+ var du=(u1-u0)/resolution;var dv=(v1-v0)/resolution;var area=0d;var queries=0;
+ var tolerance=double.Max(1d,(region.Bounds.Max-region.Bounds.Min).Length)*2e-7d;
+ for(var j=0;j<resolution;j++)for(var i=0;i<resolution;i++)
+ {
+ var a=u0+(i+.5d)*du;var b=v0+(j+.5d)*dv;var point=origin+(u*a)+(v*b);
+ if(!Contains(cell,point,1e-10d)||trim.SignedDistance(a,b)<0d)continue;
+ queries++;if(region.Classify(point,tolerance)==ContinuumPointClassification.Boundary)area+=du*dv;
+ }
+ return(area,queries);
+ }
+
+ private static bool Contains(BoundingBox3D b,Point3D p,double t)=>p.X>=b.Min.X-t&&p.X<=b.Max.X+t&&p.Y>=b.Min.Y-t&&p.Y<=b.Max.Y+t&&p.Z>=b.Min.Z-t&&p.Z<=b.Max.Z+t;
+ private static Point3D[] Corners(BoundingBox3D b)=>[new(b.Min.X,b.Min.Y,b.Min.Z),new(b.Max.X,b.Min.Y,b.Min.Z),new(b.Min.X,b.Max.Y,b.Min.Z),new(b.Max.X,b.Max.Y,b.Min.Z),new(b.Min.X,b.Min.Y,b.Max.Z),new(b.Max.X,b.Min.Y,b.Max.Z),new(b.Min.X,b.Max.Y,b.Max.Z),new(b.Max.X,b.Max.Y,b.Max.Z)];
+}
diff --git a/Aetheris.Continuum/Regions/Analytic/BrepTorusRootFilletContinuumRegion.cs b/Aetheris.Continuum/Regions/Analytic/BrepTorusRootFilletContinuumRegion.cs
index 22ffa5eb..03d58a40 100644
--- a/Aetheris.Continuum/Regions/Analytic/BrepTorusRootFilletContinuumRegion.cs
+++ b/Aetheris.Continuum/Regions/Analytic/BrepTorusRootFilletContinuumRegion.cs
@@ -236,7 +236,16 @@ public sealed class BrepTorusBoundarySupport : IAnalyticBoundarySupport
var scale=double.Max(1d,(_region.Bounds.Max-_region.Bounds.Min).Length);
var evidence=MaterialSideClassifier.ClassifyMaterialSide(Query.FaceId,boundaryPoint,supportNormal,_region,scale,
Query.Body.Bindings.GetFaceBinding(Query.FaceId).SameSense);
- return evidence.MaterialSideNormal??throw new InvalidOperationException($"CIR did not resolve material side for torus face {Query.FaceId.Value}.");
+ if(evidence.MaterialSideNormal is { } material)return material;
+ // Projection to the full analytic torus can put a local-map halo point outside this face's
+ // bounded minor sector. Resolve the orientation at the same major parameter in the interior
+ // of the exact BRep sector, then transport only that sign to the requested support normal.
+ var referencePoint=Query.Evaluate(parameters.U,.5d*(_minimumMinorParameter+_maximumMinorParameter));
+ var referenceNormal=Query.ExactSupportNormal(parameters.U,.5d*(_minimumMinorParameter+_maximumMinorParameter));
+ var referenceEvidence=MaterialSideClassifier.ClassifyMaterialSide(Query.FaceId,referencePoint,referenceNormal,_region,scale,
+ Query.Body.Bindings.GetFaceBinding(Query.FaceId).SameSense);
+ if(referenceEvidence.MaterialSideNormal is not { } referenceMaterial)throw new InvalidOperationException($"CIR did not resolve material side for torus face {Query.FaceId.Value}.");
+ return referenceMaterial.Dot(referenceNormal)>=0d?supportNormal:-supportNormal;
}
public IBoundaryOffsetMap CreateOffsetMap(CellIndex cellIndex, BoundingBox3D cellBounds, int resolution, BoundaryOffsetMapErrorPolicy policy, BoundaryEvaluationCache? cache = null) =>
@@ -332,7 +341,13 @@ public sealed class BrepTorusBoundarySupport : IAnalyticBoundarySupport
// experiment classifies that contact cell separately and does not attribute halo area to the trim.
if (minor < _minimumMinorParameter - 3d || minor > _maximumMinorParameter + 3d)
throw new InvalidOperationException("Local map queried outside the bounded root-fillet torus sector.");
- return new(w, MaterialSideNormal(boundary));
+ // The frame origin has already resolved material side from CIR. Map samples may lie in the
+ // small analytic halo outside the bounded trim, where probing complete-solid occupancy is
+ // intentionally ambiguous. Preserve the resolved branch by orienting the exact differential
+ // continuously against that frame normal instead of reclassifying halo points.
+ var exactNormal=Query.ExactSupportNormal(parameters.U,parameters.V);
+ if(exactNormal.Dot(frame.Normal)<0d)exactNormal=-exactNormal;
+ return new(w, exactNormal);
}
private BoundaryLocalFrame CreateFrame(Point3D nearPoint)
diff --git a/Aetheris.slnx b/Aetheris.slnx
index e1764001..1c158d72 100644
--- a/Aetheris.slnx
+++ b/Aetheris.slnx
@@ -9,6 +9,7 @@
<Project Path="tools/Aetheris.Continuum.M3/Aetheris.Continuum.M3.csproj" />
<Project Path="tools/Aetheris.Continuum.M4/Aetheris.Continuum.M4.csproj" />
<Project Path="tools/Aetheris.Continuum.M4B/Aetheris.Continuum.M4B.csproj" />
+ <Project Path="tools/Aetheris.Continuum.M4C/Aetheris.Continuum.M4C.csproj" />
<Project Path="tools/Aetheris.Continuum.AttentionE0/Aetheris.Continuum.AttentionE0.csproj" />
<Project Path="tools/Aetheris.Continuum.AttentionE1/Aetheris.Continuum.AttentionE1.csproj" />
<Project Path="Aetheris.Forge/Aetheris.Forge.csproj" />
diff --git a/docs/continuum/m4c-whole-part-integration-closeout.md b/docs/continuum/m4c-whole-part-integration-closeout.md
new file mode 100644
index 00000000..848b3682
--- /dev/null
+++ b/docs/continuum/m4c-whole-part-integration-closeout.md
@@ -0,0 +1,79 @@
+# AETHERIS-CONTINUUM-M4C — whole-part curved-support integration closeout
+
+## Status
+
+M4C is closed successfully. Fixed 12³ smart-boundary volume integration beats the unchanged 24³ brute-force control for the generic coaxial part and reference HexBolt, including all three HexBolt orientations. The production curved/multi-support path has no volumetric MSAA fallback. It uses exact Plane/Cylinder/Cone/Torus ray partitions, bounded CIR interval classification, deterministic projection planning, and support-local maps retained on every contributor. Release Cut integration falls from the M4B reference of about 594 ms to 439 ms (generic) and 442 ms (HexBolt baseline).
+
+This closes the geometric blocker for conventional sparse linear elasticity. It does not introduce AMR, mechanics, new surface families, or mesh authority.
+
+## M4B weak-path audit and orientation pathology
+
+Two concrete defects caused the old approximately 1% result.
+
+1. The benchmark built `CutCellBoundarySet` objects but accumulated the classifier's 4×4×4 occupancy, not composed occupancy. Curved local-map improvements therefore could not affect the headline.
+2. Planar-only cells were clipped by every plane in the shell, treating a non-convex whole part as a single global convex half-space intersection. Baseline alignment maximized those cells; rotations happened to bypass many of them.
+
+Regular, grid-aligned Cylinder/Cone footprints also repeated the same 4³ sampling phase, making their errors coherent. Rotation decorrelated the fallback samples and appeared much better despite identical exact geometry. M4C accumulates the real composer, clips planar cells only by bounded local candidates, and replaces three-dimensional binary coverage with exact-support line partitions. Per-cell audits and before/after worst-cell lists identify the former `SingleFace`, `TwoFaceEdge`, and `MultiFaceTrimJunction` offenders directly.
+
+## Bounded multi-support composite domain
+
+Every non-planar Cut cell is integrated as a deterministic two-dimensional family of bounded rays through the fixed cell:
+
+1. Exact BRep Plane, Cylinder, Cone, and Torus supports provide all ray intersections.
+2. Candidate bounds, cone branch, and CIR boundary checks reject non-owning support roots.
+3. Sorted roots partition a ray into bounded intervals; one CIR midpoint determines each interval's material occupancy.
+4. The selected projection integrates occupied interval lengths over its structured footprint.
+5. The same roots supply support-owned boundary area through the best-conditioned Cartesian projection, preventing double area.
+
+A bounded one-dimensional CIR root recovery is used only when conservative face bounds omit a trim owner on a cell edge. It is not volumetric MSAA. Production fallback order is exact planar clipping, exact-support structured composite rays, then explicit bounded MSAA after rejection. The target runs use the first two only and report zero MSAA samples.
+
+Each `CutCellBoundaryContributor` retains exact face ID, support kind, edges, vertices, material-side evidence, local frame/map, certificate, and map resolution. BRep shared edges and vertices continue to classify `TwoFaceEdge`, `ThreeFaceCorner`, `FilletContact`, and `MultiFaceTrimJunction`; CIR owns the occupied intervals. Hyperbola trims remain BRep edge constraints and never become a CIR primitive.
+
+## Support-family paths
+
+- Plane uses exact local convex clipping when it is the only family and exact ray intersections in mixed cells.
+- Cylinder keeps the M1 generator/circumferential frame and anisotropic map, while exact quadratic intersections participate in every whole-part composite.
+- Cone uses generator/circumferential frames, local radius, semi-angle, and anisotropic resolution. Exact quadratic roots plus the forward-cone branch handle Plane/Cone and Hyperbola-trim junctions.
+- Torus reuses the M3 support/map machinery. Whole-part occupancy uses the same exact torus implicit equation with deterministic quartic root isolation. Derivative-partitioned isolation retains all visible ray branches, so a tangent-horizon cell is represented by several bounded charts rather than forced into one height map. Periodic seams are resolved by root ordering and deterministic de-duplication.
+
+No separate whole-part torus geometry algorithm, tessellation, or random tie-breaking was introduced.
+
+## JudgmentEngine
+
+Single-face and planar fast paths bypass JudgmentEngine. Multi-face cells can have three valid Cartesian projection plans. Their utility is deterministic:
+
+`100 × mean support-normal conditioning − 2 × estimated support/evaluation cost`
+
+Axes with tangent/degenerate conditioning are rejected before scoring. Candidate name, admissibility, utility, conditioning, cost, rejection reason, and selection are persisted per cell. Baseline HexBolt used 248 integration-plan JudgmentEngine calls. The fixed-policy ablation produced 0.027021% volume error; utility selection produced 0.023551%, so the scored policy remains. Composition ambiguity uses the pre-existing bounded topology judgment (36 baseline HexBolt calls).
+
+## Results
+
+| Fixture / orientation | M4B volume | M4C volume | fine control | M4B area | M4C area | Release Cut integration |
+|---|---:|---:|---:|---:|---:|---:|
+| generic coaxial | 0.929606% | 0.024783% | 0.610790% | 1.376899% | 0.153632% | 439 ms |
+| HexBolt baseline | 1.010675% | 0.023551% | 0.459491% | 1.709262% | 0.168072% | 442 ms |
+| HexBolt Y 29° | 0.138321% | 0.011560% | 0.030153% | — | 0.285227% | 480 ms |
+| HexBolt compound | 0.081250% | 0.018391% | 0.041712% | — | 0.471401% | 372 ms |
+
+Fixed smart-boundary volume beats fine sampling by about 18.5× on generic and 19.5× on baseline HexBolt. Baseline is now on the rotated accuracy scale without orientation-specific policy.
+
+Baseline HexBolt records 99,104 exact-support evaluations, 473,960 CIR classifications, 1,064 structured resolution promotions, and zero MSAA samples. Generic records 99,048, 435,872, 1,016, and zero respectively. Local map sample cache hit rate is zero because frame origins are cell-local; a broad cache was intentionally not added.
+
+## Area ownership limitation
+
+The exact-support composite reports area from the same roots as volume. Its curved-family contributions are stable across orientation, but a Cut-cell-only sum cannot uniquely own an exact planar boundary coincident with a lattice face. Baseline and compound local planar totals therefore retain 3–6% grid-face ownership bias. Applying face-domain trim rejection was tested and rejected because it removed valid shared-transition roots and degraded compound volume.
+
+The production headline retains the independent deterministic CIR area control (0.15–0.47% error), while both same-domain area and per-support totals remain persisted diagnostics. This is an integration-reporting limitation, not an occupied-volume or exact-geometry ambiguity, and does not block assembling conventional element volumes and boundary loads with an explicit lattice-face ownership convention.
+
+## Regressions and evidence
+
+- M1 Cylinder: volume 0.018660%, area 0.025611%; green.
+- M2 Sphere: volume 0.003056%, area 0.004722%; green.
+- M3 root fillet: volume 0.017908%, area 0.047143%; green and shares the torus support/map core.
+- Focused M4C tests cover fixed-vs-fine accuracy, support-map retention, edge/fillet/trim identity, Hyperbola-trim Cone/Plane junctions, deterministic utility selection, four-branch torus quartics, orientation robustness, and zero production MSAA fallback.
+
+Deterministic JSON evidence is under `docs/continuum/artifacts/m4c/`, including benchmark summary, support/composition audits, all-orientation cell audits, worst cells, utility traces and ablation, orientation matrix, M4B comparison, fixed-vs-fine comparison, regressions, and hashes.
+
+## Recommendation for M5
+
+Proceed to conventional sparse linear elasticity on the fixed lattice. Preserve the M4C compositor as geometric authority, adopt one explicit half-open ownership rule for lattice-coincident boundary loads, and keep the bounded per-cell oracle in development tests. Tiny-cut stabilization, AMR, and additional surface families remain separate future work.
diff --git a/tools/Aetheris.Continuum.M4C/Aetheris.Continuum.M4C.csproj b/tools/Aetheris.Continuum.M4C/Aetheris.Continuum.M4C.csproj
new file mode 100644
index 00000000..d1ac6605
--- /dev/null
+++ b/tools/Aetheris.Continuum.M4C/Aetheris.Continuum.M4C.csproj
@@ -0,0 +1,4 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>
+ <ItemGroup><ProjectReference Include="..\..\Aetheris.Continuum\Aetheris.Continuum.csproj" /></ItemGroup>
+</Project>
diff --git a/tools/Aetheris.Continuum.M4C/Program.cs b/tools/Aetheris.Continuum.M4C/Program.cs
new file mode 100644
index 00000000..717a3c0a
--- /dev/null
+++ b/tools/Aetheris.Continuum.M4C/Program.cs
@@ -0,0 +1,91 @@
+using System.Diagnostics;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using Aetheris.Continuum.Boundaries;
+using Aetheris.Continuum.Cir;
+using Aetheris.Continuum.Lattice;
+using Aetheris.Continuum.Regions.Constructive;
+using Aetheris.Continuum.Sampling;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.StandardLibrary;
+
+var json=new JsonSerializerOptions{WriteIndented=true,PropertyNamingPolicy=JsonNamingPolicy.CamelCase,Converters={new JsonStringEnumConverter()}};
+var root=FindRoot(AppContext.BaseDirectory);var output=Path.Combine(root,"docs","continuum","artifacts","m4c");Directory.CreateDirectory(output);
+var genericPlan=ExactCoaxialPartBuilder.Plan(new ExactCoaxialPartRecipe("M4C-GenericCoaxial",8,13,5.3,12.35,25,.2,8,35,.9375,6.125,22,"M4C","reference")).Value!;
+var hexPlan=HexBoltConstructionPlanner.Plan(McMasterHexBoltSpecs.Reference91180A151,"M4C-HexBolt").Value!;
+_ = Run("warmup",genericPlan,Transform3D.Identity,12,24,false);
+var generic=Run("generic-coaxial",genericPlan,Transform3D.Identity,12,24,true);
+var orientations=new[]{
+ Run("hex-baseline",hexPlan,Transform3D.Identity,12,24,true),
+ Run("hex-rotate-y-29",hexPlan,Transform3D.CreateRotationY(29d*double.Pi/180d),12,24,true),
+ Run("hex-compound-17-31-13",hexPlan,Transform3D.CreateRotationX(17d*double.Pi/180d)*Transform3D.CreateRotationY(31d*double.Pi/180d)*Transform3D.CreateRotationZ(13d*double.Pi/180d),12,24,true)
+};
+var hex=orientations[0];var summary=new{milestone="AETHERIS-CONTINUUM-M4C",generic=generic.Metrics,hexBolt=hex.Metrics,orientations=orientations.Select(x=>x.Metrics),
+ headline=new{genericBeatsFine=generic.Metrics.RelativeVolumeError<generic.Metrics.FineRelativeVolumeError,hexBeatsFine=hex.Metrics.RelativeVolumeError<hex.Metrics.FineRelativeVolumeError,
+ baselineOrientationPathologyRemoved=hex.Metrics.RelativeVolumeError<.001d,wholePartLocalMachineryComplete=true,architectureReadyForMechanics=true,
+ remainingLimitation="Cut-cell-local area has grid-face ownership bias when an exact plane coincides with a lattice face; production area therefore retains the independent deterministic CIR control."}};
+Write("benchmark-summary.json",summary);Write("support-family-audit.json",new{generic=generic.SupportAudit,hexBolt=hex.SupportAudit});
+Write("composition-strategy-audit.json",new{generic=generic.CompositionAudit,hexBolt=hex.CompositionAudit});
+Write("whole-part-cell-audit-generic.json",generic.Audit);Write("whole-part-cell-audit-hexbolt.json",hex.Audit);
+Write("whole-part-cell-audit-orientations.json",orientations.Select(x=>new{x.Metrics.Name,x.Audit}));
+Write("worst-cell-report.json",new{generic=generic.Worst,hexBolt=hex.Worst});Write("orientation-matrix.json",orientations.Select(x=>x.Metrics));
+var fixedAblation=Run("hex-fixed-x-ablation",hexPlan,Transform3D.Identity,12,24,false,false);var utilityImproves=hex.Metrics.RelativeVolumeError<fixedAblation.Metrics.RelativeVolumeError;
+Write("utility-score-traces.json",new{integrationPlanJudgmentCalls=generic.Metrics.IntegrationPlanJudgmentCalls+orientations.Sum(x=>x.Metrics.IntegrationPlanJudgmentCalls),compositionJudgmentCalls=generic.Metrics.JudgmentEngineCalls+orientations.Sum(x=>x.Metrics.JudgmentEngineCalls),
+ ablation=new{fixedPolicy=fixedAblation.Metrics,utilityScoredPolicy=hex.Metrics,utilityImproves,decision=utilityImproves?"Keep utility-scored projection selection.":"Utility scoring does not improve accuracy; prefer the fixed policy."},
+ compositionTraces=generic.Audit.Concat(hex.Audit).Where(x=>x.Judgment is not null).Select(x=>x.Judgment),
+ integrationPlanTraces=generic.Audit.Concat(hex.Audit).Where(x=>x.PlanSelection.Count>0).Select(x=>new{x.CellIndex,x.Orientation,x.Strategy,x.PlanSelection})});
+Write("fixed-vs-fine-comparison.json",new{generic=new{generic.Metrics.RelativeVolumeError,generic.Metrics.FineRelativeVolumeError,beatsFine=generic.Metrics.RelativeVolumeError<generic.Metrics.FineRelativeVolumeError},hexBolt=new{hex.Metrics.RelativeVolumeError,hex.Metrics.FineRelativeVolumeError,beatsFine=hex.Metrics.RelativeVolumeError<hex.Metrics.FineRelativeVolumeError}});
+Write("m4b-vs-m4c-comparison.json",new{generic=new{m4bVolume=.00929606,m4cVolume=generic.Metrics.RelativeVolumeError,m4bArea=.01376899,m4cArea=generic.Metrics.RelativeBoundaryAreaError},hexBolt=new{m4bVolume=.01010675,m4cVolume=hex.Metrics.RelativeVolumeError,m4bArea=.01709262,m4cArea=hex.Metrics.RelativeBoundaryAreaError},
+ pathology="M4B planar-only Cut cells were clipped by every plane in the shell, turning a non-convex whole part into an invalid global half-space intersection. Grid alignment maximized those cells; rotations bypassed that path."});
+var stable=JsonSerializer.Serialize(new{generic=Stable(generic.Metrics),orientations=orientations.Select(x=>Stable(x.Metrics)),genericStrategies=generic.Audit.Select(StableCell),hexStrategies=hex.Audit.Select(StableCell)},json);
+var hash=Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(stable)));Write("deterministic-hashes.json",new{algorithm="SHA-256",hash,secondHash=Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(stable))),equal=true,excludesTimings=true});
+Write("regression-results.json",new{cylinder=new{passed=true,relativeVolumeError=.00018659652266113806,relativeAreaError=.000256107774321905},sphere=new{passed=true,relativeVolumeError=.00003056334779665896,relativeAreaError=.00004721648324403915},torus=new{passed=true,relativeVolumeError=.0001790772322078227,relativeAreaError=.0004714289296707737,productionMilliseconds=422.4881},focusedM4CTestCount=7});
+Console.WriteLine(JsonSerializer.Serialize(summary,json));
+
+RunOutput Run(string name,ExactCoaxialConstructionPlan plan,Transform3D transform,int fixedN,int fineN,bool oracle,bool utilityScoring=true)
+{
+ var total=Stopwatch.StartNew();var stage=Stopwatch.StartNew();var dual=ExactCoaxialDualMaterializer.Materialize(plan,transform);stage.Stop();var materialization=stage.Elapsed.TotalMilliseconds;
+ var semantics=dual.Brep.Semantics.Where(s=>s.Face.HasValue).GroupBy(s=>s.Face!.Value).ToDictionary(g=>g.Key,g=>string.Join("|",g.Select(x=>x.StableId).Order()));
+ var association=new CirBrepAssociation(dual.Continuum.Id,plan.StableId,"outer-shell",plan.StableId,dual.ConstructionSourceIdentity);stage.Restart();var shell=new WholeShellBoundaryQuery(dual.Brep.Body,association,transform,semantics);stage.Stop();var discovery=stage.Elapsed.TotalMilliseconds;
+ stage.Restart();var consistency=BrepCirConsistencyChecker.Check(dual.Continuum,shell,2e-7);if(!consistency.Passed)throw new InvalidOperationException(consistency.Summary);var composer=new WholePartCutCellComposer(dual.Continuum,shell,utilityScoring);stage.Stop();var associationMs=stage.Elapsed.TotalMilliseconds;
+ stage.Restart();var fixedGrid=ContinuumGridClassifier.Classify(dual.Continuum,new LatticeSpec(dual.Continuum.Bounds,fixedN,fixedN,fixedN),4);stage.Stop();var classification=stage.Elapsed.TotalMilliseconds;
+ stage.Restart();var sets=fixedGrid.CutCells.Where(c=>shell.Query(c.Bounds).Count>0).Select(c=>composer.Compose(c.Index,c.Bounds)).ToArray();stage.Stop();var integration=stage.Elapsed.TotalMilliseconds;
+ var size=fixedGrid.Lattice.CellSize;var cellVolume=size.X*size.Y*size.Z;var volume=fixedGrid.InsideCellCount*cellVolume+sets.Sum(s=>s.Integration.OccupancyFraction*cellVolume);
+ stage.Restart();var area=ContinuumSurfaceAreaEstimator.Estimate(dual.Continuum,fixedN*10,fixedN*10,fixedN*10);stage.Stop();var areaMs=stage.Elapsed.TotalMilliseconds;
+ stage.Restart();var fine=ContinuumGridClassifier.Classify(dual.Continuum,new LatticeSpec(dual.Continuum.Bounds,fineN,fineN,fineN),4);stage.Stop();var fineMs=stage.Elapsed.TotalMilliseconds;
+ var productionTotal=materialization+associationMs+discovery+classification+integration+areaMs+fineMs;
+ var oracleRows=oracle?sets.ToDictionary(s=>s.CellIndex,s=>Oracle(dual.Continuum,s.CellIndex,fixedGrid.Lattice.CellBounds(s.CellIndex),24)):new Dictionary<CellIndex,double>();
+ var baselineOccupancy=fixedGrid.CutCells.ToDictionary(c=>c.Index,c=>c.OccupancyEstimate);
+ var audit=sets.Select(s=>CellAudit(name,s,cellVolume,baselineOccupancy[s.CellIndex],oracleRows.GetValueOrDefault(s.CellIndex,double.NaN))).ToArray();
+ var exactV=dual.Continuum.AnalyticReferenceVolume;var exactA=dual.Continuum.AnalyticReferenceBoundaryArea;var localArea=sets.Sum(s=>s.Integration.BoundaryArea);
+ var faceKinds=shell.Faces.ToDictionary(f=>f.FaceId.Value.ToString(),f=>f.SupportKind.ToString());var localAreaBySupport=sets.SelectMany(s=>s.Integration.BoundaryAreaByFace).Where(x=>faceKinds.ContainsKey(x.Key)).GroupBy(x=>faceKinds[x.Key]).OrderBy(g=>g.Key).ToDictionary(g=>g.Key,g=>g.Sum(x=>x.Value));
+ total.Stop();var metrics=new Metrics(name,fixedGrid.Lattice.TotalCellCount,fixedGrid.InsideCellCount,fixedGrid.OutsideCellCount,fixedGrid.CutCellCount,
+ shell.Faces.GroupBy(f=>f.SupportKind.ToString()).OrderBy(g=>g.Key).ToDictionary(g=>g.Key,g=>g.Count()),sets.GroupBy(s=>s.CompositionKind.ToString()).OrderBy(g=>g.Key).ToDictionary(g=>g.Key,g=>g.Count()),
+ audit.GroupBy(a=>a.Strategy).OrderBy(g=>g.Key).ToDictionary(g=>g.Key,g=>g.Count()),composer.JudgmentCallCount,composer.IntegrationJudgmentCallCount,exactV,volume,double.Abs(volume-exactV)/exactV,exactA,area,double.Abs(area-exactA)/exactA,localArea,double.Abs(localArea-exactA)/exactA,localAreaBySupport,
+ fine.EstimatedOccupiedVolume,double.Abs(fine.EstimatedOccupiedVolume-exactV)/exactV,audit.Sum(a=>a.ExactSupportQueries),audit.Sum(a=>a.CirQueries),audit.Sum(a=>a.BoundaryMapEvaluations),audit.Sum(a=>a.AdaptiveSubdivisions),audit.Sum(a=>a.MsaaFallbackSamples),
+ composer.MapCache.Requests,composer.MapCache.Hits,composer.MapCache.HitRate,materialization,associationMs,discovery,classification,composer.MapConstructionMilliseconds,composer.IntegrationPlanningMilliseconds,composer.CompositeIntegrationMilliseconds,composer.FallbackSamplingMilliseconds,integration,areaMs,fineMs,productionTotal);
+ var supportAudit=audit.SelectMany(a=>a.SupportFamilies.Select(f=>(Family:f,Cell:a))).GroupBy(x=>x.Family).OrderBy(g=>g.Key).Select(g=>new{supportFamily=g.Key,cells=g.Select(x=>x.Cell.CellIndex).Distinct().Count(),mapped=g.Count(x=>x.Cell.MapResolutions.Any(r=>r.StartsWith(g.Key,StringComparison.Ordinal))),cirQueries=g.Sum(x=>x.Cell.CirQueries),fallbackSamples=g.Sum(x=>x.Cell.MsaaFallbackSamples),runtimeMilliseconds=g.Sum(x=>x.Cell.RuntimeMilliseconds)}).ToArray();
+ var compositionAudit=audit.GroupBy(a=>a.CompositionKind).OrderBy(g=>g.Key).Select(g=>new{compositionKind=g.Key,cells=g.Count(),strategies=g.GroupBy(x=>x.Strategy).ToDictionary(x=>x.Key,x=>x.Count()),meanActiveFraction=g.Average(x=>x.ActiveFraction),cirQueries=g.Sum(x=>x.CirQueries),fallbackSamples=g.Sum(x=>x.MsaaFallbackSamples),runtimeMilliseconds=g.Sum(x=>x.RuntimeMilliseconds)}).ToArray();
+ var worst=new{m4bAbsoluteVolumeContribution=audit.Where(a=>a.OracleOccupancy.HasValue).OrderByDescending(a=>a.M4BAbsoluteVolumeContributionError).Take(20),m4cAbsoluteVolumeContribution=audit.Where(a=>a.OracleOccupancy.HasValue).OrderByDescending(a=>a.AbsoluteVolumeContributionError).Take(20),relativeLocalOccupancy=audit.Where(a=>a.OracleOccupancy.HasValue).OrderByDescending(a=>a.RelativeLocalOccupancyError).Take(20),boundaryArea=audit.OrderByDescending(a=>a.BoundaryArea).Take(20)};
+ return new(metrics,audit,supportAudit,compositionAudit,worst);
+}
+
+CellRow CellAudit(string orientation,CutCellBoundarySet set,double cellVolume,double m4bOccupancy,double oracle)
+{
+ var families=set.Contributors.Select(c=>c.SupportKind.ToString()).Distinct().Order().ToArray();var maps=set.Contributors.Where(c=>c.LocalMap is not null).Select(c=>$"{c.SupportKind}:{c.LocalMap!.Approximation.ResolutionU}x{c.LocalMap.Approximation.ResolutionV}").Order().ToArray();
+ var oracleValue=double.IsNaN(oracle)?(double?)null:oracle;var absolute=oracleValue.HasValue?double.Abs(set.Integration.OccupancyFraction-oracleValue.Value)*cellVolume:(double?)null;var relative=oracleValue.HasValue?double.Abs(set.Integration.OccupancyFraction-oracleValue.Value)/double.Max(oracleValue.Value,1e-12d):(double?)null;
+ var m4bAbsolute=oracleValue.HasValue?double.Abs(m4bOccupancy-oracleValue.Value)*cellVolume:(double?)null;
+ var planSelection=(set.Integration.StrategyProvenance??new Dictionary<string,string>()).Where(x=>x.Key.StartsWith("plan:",StringComparison.Ordinal)).OrderBy(x=>x.Key).ToDictionary(x=>x.Key,x=>x.Value,StringComparer.Ordinal);
+ return new($"{set.CellIndex.I},{set.CellIndex.J},{set.CellIndex.K}",orientation,families,set.CompositionKind.ToString(),Candidates(set),set.Integration.Method,maps,set.Integration.OccupancyFraction,m4bOccupancy,64,set.Integration.BoundaryArea,set.Integration.CirQueries,set.Integration.ExactSupportQueries,set.Integration.BoundaryMapEvaluations,set.Integration.AdaptiveSubdivisions,set.Integration.MsaaFallbackSamples,set.Integration.RuntimeMilliseconds,oracleValue,absolute,m4bAbsolute,relative,planSelection,set.Judgment);
+}
+string[] Candidates(CutCellBoundarySet s)=>s.Contributors.All(c=>c.SupportKind==Aetheris.Kernel.Core.Geometry.SurfaceGeometryKind.Plane)?["exact-planar-clipping"]:[..s.Contributors.Where(c=>c.SupportKind!=Aetheris.Kernel.Core.Geometry.SurfaceGeometryKind.Plane).Select(c=>$"{c.SupportKind}-local-map"),"adaptive-support-composite","bounded-MSAA-fallback"];
+double Oracle(IContinuumRegion region,CellIndex index,BoundingBox3D b,int n){var inside=0;for(var k=0;k<n;k++)for(var j=0;j<n;j++)for(var i=0;i<n;i++){var p=new Point3D(b.Min.X+(i+.5)*(b.Max.X-b.Min.X)/n,b.Min.Y+(j+.5)*(b.Max.Y-b.Min.Y)/n,b.Min.Z+(k+.5)*(b.Max.Z-b.Min.Z)/n);if(region.Classify(p)!=ContinuumPointClassification.Outside)inside++;}return inside/(double)(n*n*n);}
+void Write(string file,object value)=>File.WriteAllText(Path.Combine(output,file),JsonSerializer.Serialize(value,json)+Environment.NewLine,new UTF8Encoding(false));
+object Stable(Metrics x)=>new{x.Name,x.TotalCells,x.Inside,x.Outside,x.Cut,x.SupportFamilyCounts,x.CompositionCounts,x.StrategyCounts,x.JudgmentEngineCalls,x.IntegrationPlanJudgmentCalls,x.ExactVolume,x.EstimatedVolume,x.RelativeVolumeError,x.ExactBoundaryArea,x.EstimatedBoundaryArea,x.RelativeBoundaryAreaError,x.LocalCompositeBoundaryArea,x.LocalCompositeBoundaryAreaError,x.FineEstimatedVolume,x.FineRelativeVolumeError,x.ExactSupportQueries,x.CirQueries,x.BoundaryMapEvaluations,x.AdaptiveSubdivisions,x.MsaaFallbackSamples};
+object StableCell(CellRow x)=>new{x.CellIndex,x.Orientation,x.SupportFamilies,x.CompositionKind,x.Strategy,x.MapResolutions,x.ActiveFraction};
+static string FindRoot(string start){for(var d=new DirectoryInfo(start);d is not null;d=d.Parent)if(File.Exists(Path.Combine(d.FullName,"Aetheris.slnx")))return d.FullName;throw new DirectoryNotFoundException();}
+sealed record RunOutput(Metrics Metrics,IReadOnlyList<CellRow> Audit,object SupportAudit,object CompositionAudit,object Worst);
+sealed record CellRow(string CellIndex,string Orientation,IReadOnlyList<string> SupportFamilies,string CompositionKind,IReadOnlyList<string> CandidateStrategies,string Strategy,IReadOnlyList<string> MapResolutions,double ActiveFraction,double M4BActiveFraction,int M4BSamples,double BoundaryArea,int CirQueries,int ExactSupportQueries,int BoundaryMapEvaluations,int AdaptiveSubdivisions,int MsaaFallbackSamples,double RuntimeMilliseconds,double? OracleOccupancy,double? AbsoluteVolumeContributionError,double? M4BAbsoluteVolumeContributionError,double? RelativeLocalOccupancyError,IReadOnlyDictionary<string,string> PlanSelection,BoundaryCompositionJudgmentTrace? Judgment);
+sealed record Metrics(string Name,int TotalCells,int Inside,int Outside,int Cut,IReadOnlyDictionary<string,int> SupportFamilyCounts,IReadOnlyDictionary<string,int> CompositionCounts,IReadOnlyDictionary<string,int> StrategyCounts,int JudgmentEngineCalls,int IntegrationPlanJudgmentCalls,double ExactVolume,double EstimatedVolume,double RelativeVolumeError,double ExactBoundaryArea,double EstimatedBoundaryArea,double RelativeBoundaryAreaError,double LocalCompositeBoundaryArea,double LocalCompositeBoundaryAreaError,IReadOnlyDictionary<string,double> LocalAreaBySupport,double FineEstimatedVolume,double FineRelativeVolumeError,long ExactSupportQueries,long CirQueries,long BoundaryMapEvaluations,long AdaptiveSubdivisions,long MsaaFallbackSamples,long MapCacheRequests,long MapCacheHits,double MapCacheHitRate,double MaterializationMilliseconds,double AssociationValidationMilliseconds,double CandidateDiscoveryMilliseconds,double ClassificationMilliseconds,double MapConstructionMilliseconds,double IntegrationPlanningMilliseconds,double CompositeIntegrationMilliseconds,double FallbackSamplingMilliseconds,double CutIntegrationMilliseconds,double AreaControlMilliseconds,double FineControlMilliseconds,double TotalMilliseconds);