Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add pcurve bindings and STEP surface-curve export

Yuechen Lie00f30998668
diff --git a/Aetheris.Kernel.Core/Brep/BrepBindings.cs b/Aetheris.Kernel.Core/Brep/BrepBindings.cs
index 303c029c..a1d0b495 100644
--- a/Aetheris.Kernel.Core/Brep/BrepBindings.cs
+++ b/Aetheris.Kernel.Core/Brep/BrepBindings.cs
@@ -15,6 +15,73 @@ public readonly record struct FaceGeometryBinding(
bool SameSense = true,
int? SourceStepEntityId = null);
+public readonly record struct SurfaceParameterPoint(double U, double V);
+
+public enum PcurveGeometryKind { Line, Circle, Ellipse, Polyline }
+
+/// <summary>A face-local parameter-space curve with the same parameter as its bound 3D edge.</summary>
+public sealed record PcurveGeometry
+{
+ private PcurveGeometry(PcurveGeometryKind kind, ParameterInterval domain, IReadOnlyList<SurfaceParameterPoint> points)
+ {
+ Kind = kind;
+ Domain = domain;
+ Points = points;
+ }
+
+ public PcurveGeometryKind Kind { get; }
+ public ParameterInterval Domain { get; }
+ public IReadOnlyList<SurfaceParameterPoint> Points { get; }
+
+ public static PcurveGeometry Line(ParameterInterval domain, SurfaceParameterPoint start, SurfaceParameterPoint end)
+ => new(PcurveGeometryKind.Line, domain, [start, end]);
+
+ public static PcurveGeometry Circle(ParameterInterval domain, SurfaceParameterPoint center, double radiusU, double radiusV)
+ => new(PcurveGeometryKind.Circle, domain, [center, new(radiusU, radiusV)]);
+
+ public static PcurveGeometry Ellipse(ParameterInterval domain, SurfaceParameterPoint center,
+ SurfaceParameterPoint cosineCoefficient, SurfaceParameterPoint sineCoefficient)
+ => new(PcurveGeometryKind.Ellipse, domain, [center, cosineCoefficient, sineCoefficient]);
+
+ public static PcurveGeometry Polyline(ParameterInterval domain, IReadOnlyList<SurfaceParameterPoint> points)
+ => new(PcurveGeometryKind.Polyline, domain, points.ToArray());
+
+ public SurfaceParameterPoint Evaluate(double parameter)
+ {
+ var span = Domain.End - Domain.Start;
+ var fraction = double.Abs(span) <= 1e-15d ? 0d : System.Math.Clamp((parameter - Domain.Start) / span, 0d, 1d);
+ if (Kind == PcurveGeometryKind.Circle)
+ {
+ var angle = Domain.Start + (span * fraction);
+ return new(Points[0].U + (Points[1].U * double.Cos(angle)), Points[0].V + (Points[1].V * double.Sin(angle)));
+ }
+ if (Kind == PcurveGeometryKind.Ellipse)
+ {
+ var angle = Domain.Start + (span * fraction);
+ return new(Points[0].U + (Points[1].U * double.Cos(angle)) + (Points[2].U * double.Sin(angle)),
+ Points[0].V + (Points[1].V * double.Cos(angle)) + (Points[2].V * double.Sin(angle)));
+ }
+ if (Kind == PcurveGeometryKind.Line)
+ return Lerp(Points[0], Points[1], fraction);
+ if (Points.Count == 0) return default;
+ if (Points.Count == 1) return Points[0];
+ var scaled = fraction * (Points.Count - 1);
+ var index = System.Math.Min((int)double.Floor(scaled), Points.Count - 2);
+ return Lerp(Points[index], Points[index + 1], scaled - index);
+ }
+
+ private static SurfaceParameterPoint Lerp(SurfaceParameterPoint a, SurfaceParameterPoint b, double t)
+ => new(a.U + ((b.U - a.U) * t), a.V + ((b.V - a.V) * t));
+}
+
+/// <summary>Associates one coedge use with its curve in the owning face's UV space.</summary>
+public readonly record struct CoedgePcurveBinding(
+ CoedgeId CoedgeId,
+ FaceId FaceId,
+ SurfaceGeometryId SurfaceGeometryId,
+ PcurveGeometry Pcurve,
+ bool SameSense = true);
+
/// <summary>
/// Explicit topology-to-geometry binding container.
/// </summary>
@@ -22,20 +89,25 @@ public sealed class BrepBindingModel
{
private readonly Dictionary<EdgeId, EdgeGeometryBinding> _edgeBindings = [];
private readonly Dictionary<FaceId, FaceGeometryBinding> _faceBindings = [];
+ private readonly Dictionary<CoedgeId, CoedgePcurveBinding> _pcurveBindings = [];
public IEnumerable<EdgeGeometryBinding> EdgeBindings => _edgeBindings.Values;
public IEnumerable<FaceGeometryBinding> FaceBindings => _faceBindings.Values;
+ public IEnumerable<CoedgePcurveBinding> PcurveBindings => _pcurveBindings.Values;
public void AddEdgeBinding(EdgeGeometryBinding binding) => _edgeBindings.Add(binding.EdgeId, binding);
public void AddFaceBinding(FaceGeometryBinding binding) => _faceBindings.Add(binding.FaceId, binding);
+ public void AddPcurveBinding(CoedgePcurveBinding binding) => _pcurveBindings.Add(binding.CoedgeId, binding);
public bool TryGetEdgeBinding(EdgeId edgeId, out EdgeGeometryBinding binding) => _edgeBindings.TryGetValue(edgeId, out binding);
public bool TryGetFaceBinding(FaceId faceId, out FaceGeometryBinding binding) => _faceBindings.TryGetValue(faceId, out binding);
+ public bool TryGetPcurveBinding(CoedgeId coedgeId, out CoedgePcurveBinding binding) => _pcurveBindings.TryGetValue(coedgeId, out binding);
public EdgeGeometryBinding GetEdgeBinding(EdgeId edgeId) => _edgeBindings[edgeId];
public FaceGeometryBinding GetFaceBinding(FaceId faceId) => _faceBindings[faceId];
+ public CoedgePcurveBinding GetPcurveBinding(CoedgeId coedgeId) => _pcurveBindings[coedgeId];
}
diff --git a/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.cs b/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.cs
new file mode 100644
index 00000000..b2865738
--- /dev/null
+++ b/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.cs
@@ -0,0 +1,113 @@
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Math;
+
+namespace Aetheris.Kernel.Core.Brep;
+
+public sealed record BrepPcurveEvidence(
+ bool IsValid,
+ int EdgeCount,
+ int PcurveCount,
+ double MaximumReconstructionDeviation,
+ bool DomainValid,
+ bool OrientationConsistent,
+ IReadOnlyList<string> Diagnostics);
+
+/// <summary>Independently samples face-local pcurves against their shared 3D edge geometry.</summary>
+public static class BrepPcurveValidator
+{
+ public static BrepPcurveEvidence Validate(BrepBody body, double tolerance = 1e-6, bool requireEveryCoedge = false, int samples = 67)
+ {
+ ArgumentNullException.ThrowIfNull(body);
+ if (!double.IsFinite(tolerance) || tolerance <= 0d) throw new ArgumentOutOfRangeException(nameof(tolerance));
+ if (samples < 3) throw new ArgumentOutOfRangeException(nameof(samples));
+ var diagnostics = new List<string>();
+ var maximum = 0d;
+ var domainValid = true;
+ var orientationValid = true;
+
+ foreach (var coedge in body.Topology.Coedges.OrderBy(item => item.Id.Value))
+ {
+ var coedgeMaximum = 0d;
+ if (!body.Bindings.TryGetPcurveBinding(coedge.Id, out var binding))
+ {
+ if (requireEveryCoedge) diagnostics.Add($"surf-pcurve-missing:coedge={coedge.Id.Value}");
+ continue;
+ }
+ var face = body.Topology.Faces.SingleOrDefault(candidate => candidate.LoopIds.Contains(coedge.LoopId));
+ if (face is null || face.Id != binding.FaceId)
+ {
+ diagnostics.Add($"surf-pcurve-invalid:coedge={coedge.Id.Value}:owning-face-mismatch");
+ continue;
+ }
+ if (!body.Bindings.TryGetFaceBinding(face.Id, out var faceBinding) || faceBinding.SurfaceGeometryId != binding.SurfaceGeometryId
+ || !body.Geometry.TryGetSurface(binding.SurfaceGeometryId, out var surface) || surface is null
+ || !body.Bindings.TryGetEdgeBinding(coedge.EdgeId, out var edgeBinding)
+ || !body.Geometry.TryGetCurve(edgeBinding.CurveGeometryId, out var curve) || curve is null)
+ {
+ diagnostics.Add($"surf-pcurve-invalid:coedge={coedge.Id.Value}:binding-reference");
+ continue;
+ }
+ var interval = edgeBinding.TrimInterval ?? binding.Pcurve.Domain;
+ if (!FiniteOrdered(binding.Pcurve.Domain) || binding.Pcurve.Points.Count == 0)
+ {
+ domainValid = false;
+ diagnostics.Add($"surf-pcurve-invalid:coedge={coedge.Id.Value}:domain");
+ continue;
+ }
+ for (var index = 0; index < samples; index++)
+ {
+ var fraction = index / (double)(samples - 1);
+ var parameter = interval.Start + ((interval.End - interval.Start) * fraction);
+ var curveParameter = binding.SameSense ? parameter : interval.End - ((parameter - interval.Start));
+ var uv = binding.Pcurve.Evaluate(curveParameter);
+ var onSurface = Evaluate(surface, uv);
+ var onCurve = Evaluate(curve, parameter);
+ if (onSurface is null || onCurve is null)
+ {
+ diagnostics.Add($"surf-pcurve-invalid:coedge={coedge.Id.Value}:unsupported-evaluator");
+ break;
+ }
+ coedgeMaximum = double.Max(coedgeMaximum, (onSurface.Value - onCurve.Value).Length);
+ }
+ maximum = double.Max(maximum, coedgeMaximum);
+ if (coedgeMaximum > tolerance)
+ diagnostics.Add($"surf-pcurve-invalid:coedge={coedge.Id.Value}:face={face.Id.Value}:surface={surface.Kind}:curve={curve.Kind}:pcurve={binding.Pcurve.Kind}:deviation={coedgeMaximum:R}:tolerance={tolerance:R}");
+
+ if (body.TryGetVertexPoint(coedge.IsReversed ? body.Topology.GetEdge(coedge.EdgeId).EndVertexId : body.Topology.GetEdge(coedge.EdgeId).StartVertexId, out var start))
+ {
+ var parameter = coedge.IsReversed ? interval.End : interval.Start;
+ var uv = binding.Pcurve.Evaluate(binding.SameSense ? parameter : interval.End - (parameter - interval.Start));
+ var reconstructed = Evaluate(surface, uv);
+ if (reconstructed is null || (reconstructed.Value - start).Length > tolerance)
+ {
+ orientationValid = false;
+ diagnostics.Add($"surf-pcurve-invalid:coedge={coedge.Id.Value}:orientation");
+ }
+ }
+ }
+
+ var count = body.Bindings.PcurveBindings.Count();
+ var valid = diagnostics.Count == 0 && maximum <= tolerance && domainValid && orientationValid;
+ return new(valid, body.Topology.Edges.Count(), count, maximum, domainValid, orientationValid, diagnostics);
+ }
+
+ private static bool FiniteOrdered(ParameterInterval interval) => double.IsFinite(interval.Start) && double.IsFinite(interval.End) && interval.End >= interval.Start;
+
+ private static Point3D? Evaluate(SurfaceGeometry surface, SurfaceParameterPoint uv) => surface.Kind switch
+ {
+ SurfaceGeometryKind.Plane => surface.Plane!.Value.Evaluate(uv.U, uv.V),
+ SurfaceGeometryKind.Cylinder => surface.Cylinder!.Value.Evaluate(uv.U, uv.V),
+ SurfaceGeometryKind.BSplineSurfaceWithKnots => surface.BSplineSurfaceWithKnots!.Evaluate(uv.U, uv.V),
+ _ => null
+ };
+
+ private static Point3D? Evaluate(CurveGeometry curve, double parameter) => curve.Kind switch
+ {
+ CurveGeometryKind.Line3 => curve.Line3!.Value.Evaluate(parameter),
+ CurveGeometryKind.Circle3 => curve.Circle3!.Value.Evaluate(parameter),
+ CurveGeometryKind.BSpline3 => curve.BSpline3!.Value.Evaluate(parameter),
+ CurveGeometryKind.Ellipse3 => curve.Ellipse3!.Value.Evaluate(parameter),
+ CurveGeometryKind.Hyperbola3 => curve.Hyperbola3!.Value.Evaluate(parameter),
+ _ => null
+ };
+}
diff --git a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs b/Aetheris.Kernel.Core/Step242/Step242Exporter.cs
index 650e3114..171bef74 100644
--- a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242Exporter.cs
@@ -67,8 +67,11 @@ public static class Step242Exporter
var hyperbolaIds = new Dictionary<EdgeId, string>();
var surfaceIds = new Dictionary<SurfaceGeometryId, string>();
var advancedFaceIds = new Dictionary<FaceId, string>();
+ var pcurveContextId = body.Bindings.PcurveBindings.Any()
+ ? writer.AddEntity("REPRESENTATION_CONTEXT", Step242TextWriter.String("2D"), Step242TextWriter.String("parameter space"))
+ : null;
- var outerClosedShellId = BuildClosedShell(writer, body, model, shellRepresentation.OuterShellId, vertexPoints, cartesianPointIds, vertexPointIds, edgeCurveIds, orientedEdgeIds, lineIds, circleIds, bsplineIds, ellipseIds, hyperbolaIds, surfaceIds, advancedFaceIds, options.EmitFullCircleTrimmedCurves);
+ var outerClosedShellId = BuildClosedShell(writer, body, model, shellRepresentation.OuterShellId, vertexPoints, cartesianPointIds, vertexPointIds, edgeCurveIds, orientedEdgeIds, lineIds, circleIds, bsplineIds, ellipseIds, hyperbolaIds, surfaceIds, advancedFaceIds, pcurveContextId, options.EmitFullCircleTrimmedCurves);
EmitAuxiliaryVertexPointForVertexlessAnalyticBody(writer, body, model);
if (outerClosedShellId is null)
{
@@ -85,7 +88,7 @@ public static class Step242Exporter
var orientedVoidShellIds = new List<string>();
foreach (var innerShellId in shellRepresentation.InnerShellIds.OrderBy(id => id.Value))
{
- var innerClosedShellId = BuildClosedShell(writer, body, model, innerShellId, vertexPoints, cartesianPointIds, vertexPointIds, edgeCurveIds, orientedEdgeIds, lineIds, circleIds, bsplineIds, ellipseIds, hyperbolaIds, surfaceIds, advancedFaceIds, options.EmitFullCircleTrimmedCurves);
+ var innerClosedShellId = BuildClosedShell(writer, body, model, innerShellId, vertexPoints, cartesianPointIds, vertexPointIds, edgeCurveIds, orientedEdgeIds, lineIds, circleIds, bsplineIds, ellipseIds, hyperbolaIds, surfaceIds, advancedFaceIds, pcurveContextId, options.EmitFullCircleTrimmedCurves);
if (innerClosedShellId is null)
{
return Failure($"Shell {innerShellId.Value} could not be exported.", $"Shell:{innerShellId.Value}");
@@ -164,6 +167,7 @@ public static class Step242Exporter
Dictionary<EdgeId, string> hyperbolaIds,
Dictionary<SurfaceGeometryId, string> surfaceIds,
Dictionary<FaceId, string> advancedFaceIds,
+ string? pcurveContextId,
bool emitFullCircleTrimmedCurves)
{
if (!model.TryGetShell(shellId, out var shell) || shell is null)
@@ -171,6 +175,22 @@ public static class Step242Exporter
return null;
}
+ // Pcurves for an edge may reference both adjacent supports, including a face
+ // visited later in shell order, so materialize every support first. Retain
+ // the legacy lazy ordering when no pcurves exist so canonical exports stay
+ // byte-for-byte stable.
+ foreach (var face in pcurveContextId is null
+ ? []
+ : shell.FaceIds.OrderBy(id => id.Value).Select(model.GetFace))
+ {
+ if (!body.Bindings.TryGetFaceBinding(face.Id, out var binding)
+ || !body.Geometry.TryGetSurface(binding.SurfaceGeometryId, out var support) || support is null) return null;
+ if (surfaceIds.ContainsKey(binding.SurfaceGeometryId)) continue;
+ var built = BuildSurface(writer, support, face.Id);
+ if (!built.IsSuccess) return null;
+ surfaceIds[binding.SurfaceGeometryId] = built.Value;
+ }
+
var faceIds = new List<string>();
foreach (var face in shell.FaceIds.OrderBy(id => id.Value).Select(model.GetFace))
{
@@ -211,7 +231,7 @@ public static class Step242Exporter
if (!edgeCurveIds.TryGetValue(coedge.EdgeId, out var edgeCurveId))
{
- var edgeResult = BuildEdgeCurve(body, model, writer, coedge.EdgeId, vertexPoints, cartesianPointIds, vertexPointIds, lineIds, circleIds, bsplineIds, ellipseIds, hyperbolaIds, emitFullCircleTrimmedCurves);
+ var edgeResult = BuildEdgeCurve(body, model, writer, coedge.EdgeId, vertexPoints, cartesianPointIds, vertexPointIds, lineIds, circleIds, bsplineIds, ellipseIds, hyperbolaIds, surfaceIds, pcurveContextId, emitFullCircleTrimmedCurves);
if (!edgeResult.IsSuccess)
{
return null;
@@ -815,6 +835,8 @@ public static class Step242Exporter
IDictionary<EdgeId, string> bsplineIds,
IDictionary<EdgeId, string> ellipseIds,
IDictionary<EdgeId, string> hyperbolaIds,
+ IReadOnlyDictionary<SurfaceGeometryId, string> surfaceIds,
+ string? pcurveContextId,
bool emitFullCircleTrimmedCurves)
{
var edge = model.GetEdge(edgeId);
@@ -981,6 +1003,19 @@ public static class Step242Exporter
return Failure($"Unsupported curve kind '{curve.Kind}'.", $"Edge:{edgeId.Value}");
}
+ var pcurveIds = pcurveContextId is null
+ ? []
+ : body.Bindings.PcurveBindings
+ .Where(binding => model.GetCoedge(binding.CoedgeId).EdgeId == edgeId)
+ .OrderBy(binding => binding.FaceId.Value)
+ .ThenBy(binding => binding.CoedgeId.Value)
+ .Select(binding => BuildStepPcurve(writer, binding, surfaceIds, pcurveContextId))
+ .Where(id => id is not null)
+ .Select(id => id!)
+ .ToArray();
+ if (pcurveIds.Length > 0)
+ geometryCurveId = writer.AddEntity("SURFACE_CURVE", "$", Step242TextWriter.Ref(geometryCurveId), Step242TextWriter.List(pcurveIds), Step242TextWriter.Enum("PCURVE_S1"));
+
// EDGE_CURVE.same_sense is the binding between the parametric curve and
// the topology edge, not a blanket export constant. In particular, a
// clockwise Profile arc has an increasing trim interval whose geometric
@@ -991,6 +1026,30 @@ public static class Step242Exporter
return KernelResult<string>.Success(edgeCurveId);
}
+ private static string? BuildStepPcurve(
+ Step242TextWriter writer,
+ CoedgePcurveBinding binding,
+ IReadOnlyDictionary<SurfaceGeometryId, string> surfaceIds,
+ string contextId)
+ {
+ if (!surfaceIds.TryGetValue(binding.SurfaceGeometryId, out var surfaceId)) return null;
+ var samples = binding.Pcurve.Kind switch
+ {
+ PcurveGeometryKind.Line => 2,
+ PcurveGeometryKind.Polyline => binding.Pcurve.Points.Count,
+ _ => 1025
+ };
+ var points = Enumerable.Range(0, samples).Select(index =>
+ {
+ var parameter = binding.Pcurve.Domain.Start + ((binding.Pcurve.Domain.End - binding.Pcurve.Domain.Start) * index / (samples - 1d));
+ return binding.Pcurve.Evaluate(parameter);
+ }).Select(point => writer.AddEntity("CARTESIAN_POINT", "$", Step242TextWriter.List(Step242TextWriter.Number(point.U), Step242TextWriter.Number(point.V))))
+ .ToArray();
+ var curve2dId = writer.AddEntity("POLYLINE", "$", Step242TextWriter.List(points));
+ var representationId = writer.AddEntity("DEFINITIONAL_REPRESENTATION", Step242TextWriter.String("pcurve"), Step242TextWriter.List(curve2dId), Step242TextWriter.Ref(contextId));
+ return writer.AddEntity("PCURVE", "$", Step242TextWriter.Ref(surfaceId), Step242TextWriter.Ref(representationId));
+ }
+
private static string EnsureVertex(
Step242TextWriter writer,
VertexId vertexId,
diff --git a/Aetheris.Kernel.Core/Step242/Step242Importer.cs b/Aetheris.Kernel.Core/Step242/Step242Importer.cs
index 86449194..baceb477 100644
--- a/Aetheris.Kernel.Core/Step242/Step242Importer.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242Importer.cs
@@ -778,6 +778,16 @@ public static class Step242Importer
int edgeCurveEntityId)
{
ParameterInterval? explicitTrim = null;
+ var surfaceCurveConstructor = Step242SubsetDecoder.TryGetConstructor(curveEntity.Instance, "SURFACE_CURVE");
+ if (surfaceCurveConstructor is not null)
+ {
+ if (surfaceCurveConstructor.Arguments.ElementAtOrDefault(1) is not Step242EntityReference curve3dReference)
+ return FailureCurveBinding("SURFACE_CURVE must reference its authoritative 3D curve.", SourceFor(edgeCurveEntityId, "Importer.Geometry.SurfaceCurve"));
+ var curve3dResult = document.TryGetEntity(curve3dReference.TargetId);
+ if (!curve3dResult.IsSuccess)
+ return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Failure(curve3dResult.Diagnostics);
+ curveEntity = curve3dResult.Value;
+ }
var trimmedConstructor = Step242SubsetDecoder.TryGetConstructor(curveEntity.Instance, "TRIMMED_CURVE");
if (trimmedConstructor is not null)
{
@@ -1709,6 +1719,10 @@ public static class Step242Importer
SurfaceGeometryKind.Cylinder => ClassifyAndNormalizeCylindricalLoops(faceEntityId, loops, surface.Cylinder!.Value),
SurfaceGeometryKind.Torus => ClassifyAndNormalizeToroidalLoops(faceEntityId, loops, surface.Torus!.Value),
SurfaceGeometryKind.Cone => ClassifyAndNormalizeConicalLoops(faceEntityId, loops, surface.Cone!.Value),
+ // A non-rational B-spline has no universal planar containment projection.
+ // Preserve the explicit FACE_OUTER_BOUND/FACE_BOUND contract; pcurve and
+ // curve-on-surface qualification is handled independently by the BRep layer.
+ SurfaceGeometryKind.BSplineSurfaceWithKnots => KernelResult<IReadOnlyList<LoopBuildData>>.Success(loops),
_ => LoopRoleFailure<IReadOnlyList<LoopBuildData>>(
$"Multi-loop hole classification is unsupported for surface type '{surface.Kind}'.",
$"Importer.LoopRole.UnsupportedSurfaceForHoles.{surface.Kind}")
diff --git a/Aetheris.Modules.Tests/SurfX1aTrimIntersectionClosureTests.cs b/Aetheris.Modules.Tests/SurfX1aTrimIntersectionClosureTests.cs
new file mode 100644
index 00000000..0652ac52
--- /dev/null
+++ b/Aetheris.Modules.Tests/SurfX1aTrimIntersectionClosureTests.cs
@@ -0,0 +1,180 @@
+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.Step242;
+using Aetheris.Surfacing;
+using Xunit;
+
+namespace Aetheris.Modules.Tests;
+
+public sealed class SurfX1aTrimIntersectionClosureTests
+{
+ [Fact]
+ public void FlagshipOwnsFourInnerLoopsAndQualifiedFaceLocalPcurves()
+ {
+ var state = CompileFlagship().OutputState!;
+ var splineFace = Assert.Single(state.Body.Topology.Faces, face => state.Body.TryGetFaceSurfaceGeometry(face.Id, out var support)
+ && support?.Kind == SurfaceGeometryKind.BSplineSurfaceWithKnots);
+ Assert.Equal(5, splineFace.LoopIds.Count);
+ Assert.Equal(5, Assert.Single(state.SurfacePatches).BoundaryLoops);
+ var evidence = BrepPcurveValidator.Validate(state.Body, 1e-5, requireEveryCoedge: true);
+ Assert.True(evidence.IsValid, string.Join(" | ", evidence.Diagnostics));
+ Assert.Equal(state.Body.Topology.Coedges.Count(), evidence.PcurveCount);
+ Assert.True(evidence.MaximumReconstructionDeviation <= 1e-5);
+ Assert.Contains(state.ValidationEvidence, item => item.Check == "DerivedTrimIntersections" && item.Satisfied);
+ foreach (var innerLoop in splineFace.LoopIds.Skip(1))
+ {
+ var coedge = Assert.Single(state.Body.Topology.GetLoop(innerLoop).CoedgeIds.Select(state.Body.Topology.GetCoedge));
+ Assert.Equal(2, state.Body.Topology.Coedges.Count(candidate => candidate.EdgeId == coedge.EdgeId));
+ Assert.Equal(2, state.Body.Bindings.PcurveBindings.Count(binding => state.Body.Topology.GetCoedge(binding.CoedgeId).EdgeId == coedge.EdgeId));
+ }
+ }
+
+ [Fact]
+ public void IntersectionClassificationAndBranchSelectionAreExplicitAndDeterministic()
+ {
+ var z0 = SurfaceGeometry.FromPlane(Plane(0));
+ var z1 = SurfaceGeometry.FromPlane(Plane(1));
+ var domain = new SurfaceParameterDomain(-10, 10, -10, 10);
+ var none = BoundedSurfaceIntersector.Intersect(new("z0", z0, domain, "z1", z1, domain));
+ Assert.Equal(SurfaceIntersectionClassification.NoIntersection, none.Classification);
+ var coincident = BoundedSurfaceIntersector.Intersect(new("z0a", z0, domain, "z0b", z0, domain));
+ Assert.Equal(SurfaceIntersectionClassification.CoincidentRegion, coincident.Classification);
+
+ var patch = Assert.IsType<BSplineSurfacePatch>(CompileFlagship().OutputState!.Construction.ReplacementPatch);
+ var supportPlane = SurfaceGeometry.FromPlane(new PlaneSurface(new(0, -40, 20), Dir(0, -1, 0), Dir(1, 0, 0)));
+ var first = BoundedSurfaceIntersector.Intersect(new("south", supportPlane, domain, patch.PatchId, patch.Support, patch.ParameterDomain, SeedOnA: new(0, 0)));
+ var second = BoundedSurfaceIntersector.Intersect(new("south", supportPlane, domain, patch.PatchId, patch.Support, patch.ParameterDomain, SeedOnA: new(0, 0)));
+ Assert.True(first.IsSuccess); Assert.Equal(SurfaceIntersectionClassification.SingleCurve, first.Classification);
+ Assert.Equal(first.Classification, second.Classification); Assert.Equal(first.SelectedBranch, second.SelectedBranch);
+ Assert.Equal(first.Branches.Select(branch => branch.StableId), second.Branches.Select(branch => branch.StableId)); Assert.NotNull(first.SelectedBranch);
+ Assert.Equal(CurveGeometryKind.BSpline3, Assert.Single(first.Branches).Curve3D.Kind);
+
+ var coplanarBoundary = BoundedSurfaceIntersector.Intersect(new("base-plane", SurfaceGeometry.FromPlane(Plane(20)), domain,
+ patch.PatchId, patch.Support, patch.ParameterDomain));
+ Assert.Equal(SurfaceIntersectionClassification.MultipleCurves, coplanarBoundary.Classification);
+ Assert.Null(coplanarBoundary.SelectedBranch); Assert.Contains("surf-intersection-ambiguous", coplanarBoundary.Diagnostics);
+ }
+
+ [Fact]
+ public void AnalyticAndSplineExtensionsAreBoundedAndReportTheirLaw()
+ {
+ var plane = SurfaceGeometry.FromPlane(Plane(0));
+ var analytic = SurfaceSupportExtension.Extend(plane, new(0, 1, 0, 1), new(-.1, 1.1, -.1, 1.1));
+ Assert.True(analytic.IsSuccess); Assert.Equal(SurfaceExtensionMethod.AnalyticIdentity, analytic.Support!.Method);
+ Assert.Equal(new Point3D(-.1, -.1, 0), analytic.Support.Evaluate(-.1, -.1));
+
+ var patch = Assert.IsType<BSplineSurfacePatch>(CompileFlagship().OutputState!.Construction.ReplacementPatch);
+ var extended = SurfaceSupportExtension.Extend(patch.Support, patch.ParameterDomain, new(-.1, 1.1, -.1, 1.1));
+ Assert.True(extended.IsSuccess); Assert.Equal(SurfaceExtensionMethod.EndpointTangentContinuation, extended.Support!.Method);
+ Assert.Contains("C1", extended.Support.ContinuityAtOriginalBoundary, StringComparison.Ordinal);
+ var rejected = SurfaceSupportExtension.Extend(patch.Support, patch.ParameterDomain, new(-1, 2, 0, 1));
+ Assert.False(rejected.IsSuccess); Assert.Contains(rejected.Diagnostics, item => item.Code == "surf-extension-unsupported");
+ }
+
+ [Fact]
+ public void StepCarriesSurfaceCurvesPcurvesAndReimportsWithoutRationalSurfaces()
+ {
+ var export = SculptStepExporter.Export(CompileFlagship().OutputState!, "SURF-X1a");
+ Assert.True(export.IsSuccess, string.Join(" | ", export.Diagnostics.Select(item => item.Message)));
+ Assert.Contains("=PCURVE(", export.Step!, StringComparison.Ordinal);
+ Assert.Contains("=SURFACE_CURVE(", export.Step!, StringComparison.Ordinal);
+ Assert.DoesNotContain("RATIONAL_B_SPLINE_SURFACE", export.Step!, StringComparison.Ordinal);
+ Assert.Equal(0, export.Inventory.RationalNurbs); Assert.Equal(1, export.Inventory.NonRationalBSpline);
+ var imported = Step242Importer.ImportBody(export.Step!);
+ Assert.True(imported.IsSuccess, string.Join(" | ", imported.Diagnostics.Select(item => item.Message)));
+ Assert.True(BrepExportPreflight.Validate(imported.Value!).IsValid);
+ }
+
+ [Fact]
+ public void PmiAndBottomInterfaceRemainGeometricallyAssociatedAfterReinspection()
+ {
+ var state = CompileFlagship().OutputState!;
+ Assert.All(state.GeometryAssociations!, association => Assert.Equal(PersistentAssociationState.Preserved, association.State));
+ Assert.All(state.GeometryAssociations!, association => Assert.NotEmpty(association.FaceIds));
+ var export = SculptStepExporter.Export(state, "SURF-X1a associations");
+ Assert.True(export.IsSuccess);
+ var inspection = Step242SemanticPmiInspector.Inspect(export.Step!);
+ Assert.True(inspection.Success, string.Join(" | ", inspection.Diagnostics));
+ Assert.Equal(1, inspection.DatumCount); Assert.Equal(1, inspection.DimensionCount); Assert.Equal(1, inspection.GeometricToleranceCount);
+ Assert.All(inspection.Items.Where(item => item.Kind is "Datum" or "Diameter" or "Position"), item => Assert.NotEmpty(item.GeometricFaceEntityIds));
+ var assembly = Assert.Single(inspection.Items, item => item.Kind == "Annotation" && item.Name.Contains("assembly-interface", StringComparison.Ordinal));
+ Assert.Equal(SculptedHousingFactory.BottomMountingInterface, assembly.Target);
+ Assert.NotEmpty(assembly.GeometricFaceEntityIds);
+ }
+
+ [Fact]
+ public void ImportedAdvancedFaceIsReplacedBySupportGraftWithoutRebuildingNeighbors()
+ {
+ var compile = CompileFlagship();
+ var nativeBase = compile.States["Base"];
+ var sourceStep = SculptStepExporter.Export(nativeBase, "SURF-X1a imported source");
+ Assert.True(sourceStep.IsSuccess);
+ var imported = Step242Importer.ImportBody(sourceStep.Step!);
+ Assert.True(imported.IsSuccess, string.Join(" | ", imported.Diagnostics.Select(item => item.Message)));
+ var topBinding = Assert.Single(imported.Value!.Bindings.FaceBindings, binding =>
+ imported.Value.Geometry.GetSurface(binding.SurfaceGeometryId).Plane is { } plane && Math.Abs(plane.Origin.Z - 20d) < 1e-8d && plane.Normal.ToVector().Z > 0d);
+ Assert.True(topBinding.SourceStepEntityId.HasValue);
+ var adopted = ImportedFaceRegionReplacer.AdoptImportedBody(nativeBase, imported.Value, "ImportedBaseStep");
+ var patch = Assert.IsType<BSplineSurfacePatch>(compile.OutputState!.Construction.ReplacementPatch);
+ var replaced = ImportedFaceRegionReplacer.Apply(adopted, topBinding.SourceStepEntityId!.Value, patch, "ImportedTrimmedCrown");
+ Assert.True(replaced.IsSuccess, string.Join(" | ", replaced.Diagnostics.Select(item => item.Message)));
+ Assert.Same(imported.Value.Topology, replaced.OutputState!.Body.Topology);
+ Assert.Equal(4, replaced.Evidence!.InnerLoopCount);
+ Assert.NotEmpty(replaced.Evidence.PreservedNeighborSourceStepEntityIds);
+ Assert.True(replaced.Evidence.Pcurves.IsValid);
+ Assert.Equal(adopted.GeometryAssociations!.Select(item => item.FaceIds), replaced.OutputState.GeometryAssociations!.Select(item => item.FaceIds));
+ Assert.All(replaced.OutputState.GeometryAssociations!, association => Assert.Contains("Explicit GeometricDelta Preserved", association.Evidence, StringComparison.Ordinal));
+ Assert.Contains(replaced.OutputState.Body.Bindings.FaceBindings, binding => binding.FaceId == topBinding.FaceId
+ && binding.SourceStepEntityId == topBinding.SourceStepEntityId
+ && replaced.OutputState.Body.Geometry.GetSurface(binding.SurfaceGeometryId).Kind == SurfaceGeometryKind.BSplineSurfaceWithKnots);
+ var stale = ImportedFaceRegionReplacer.Apply(replaced.OutputState, topBinding.SourceStepEntityId.Value, patch, "StaleImportedTarget");
+ Assert.False(stale.IsSuccess); Assert.Contains(stale.Diagnostics, item => item.Code == "surf-selector-target-replaced");
+ }
+
+ [Fact]
+ public void BrokenPcurveIsRejectedIndependentlyOfTopologyValidity()
+ {
+ var body = CompileFlagship().OutputState!.Body;
+ var bindings = new BrepBindingModel();
+ foreach (var edge in body.Bindings.EdgeBindings) bindings.AddEdgeBinding(edge);
+ foreach (var face in body.Bindings.FaceBindings) bindings.AddFaceBinding(face);
+ var first = body.Bindings.PcurveBindings.OrderBy(item => item.CoedgeId.Value).First();
+ foreach (var pcurve in body.Bindings.PcurveBindings)
+ bindings.AddPcurveBinding(pcurve.CoedgeId == first.CoedgeId
+ ? pcurve with { Pcurve = PcurveGeometry.Line(pcurve.Pcurve.Domain, new(0, 0), new(0, 0)) }
+ : pcurve);
+ var points = body.Topology.Vertices.Where(vertex => body.TryGetVertexPoint(vertex.Id, out _)).ToDictionary(vertex => vertex.Id,
+ vertex => { body.TryGetVertexPoint(vertex.Id, out var point); return point; });
+ var corrupted = new BrepBody(body.Topology, body.Geometry, bindings, points, body.SafeBooleanComposition, body.ShellRepresentation);
+ Assert.True(BrepExportPreflight.Validate(corrupted).IsValid);
+ var evidence = BrepPcurveValidator.Validate(corrupted, 1e-5, requireEveryCoedge: true);
+ Assert.False(evidence.IsValid); Assert.Contains(evidence.Diagnostics, message => message.StartsWith("surf-pcurve-invalid", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void RemovedPmiOrInterfaceTargetIsNotReboundByGeometryOrName()
+ {
+ var state = CompileFlagship().OutputState!;
+ var removed = state.Delta! with
+ {
+ OutputState = new("state-association-removal-witness"),
+ Correspondence = [new(SculptedHousingFactory.BottomMountingInterface, GeometricChangeKind.Removed, [], "Deliberate invalid witness.")]
+ };
+ var remap = SculptedHousingFactory.RemapPersistentAssociations(state, state.Body, removed);
+ Assert.False(remap.IsSuccess);
+ Assert.Contains(remap.Diagnostics, item => item.Code == "surf-association-target-removed"
+ && item.Entity == SculptedHousingFactory.BottomMountingInterface);
+ }
+
+ private static SculptingCompileResult CompileFlagship() => SculptingAuthoring.CompileFile(Path.Combine(RepositoryRoot(), "fixtures", "Canonical", "Sculpting", "surf-x1a-trimmed-freeform-housing.firmament"));
+ private static PlaneSurface Plane(double z) => new(new(0, 0, z), Dir(0, 0, 1), Dir(1, 0, 0));
+ private static Direction3D Dir(double x, double y, double z) => Direction3D.Create(new Vector3D(x, y, z));
+ private static string RepositoryRoot()
+ {
+ var current = new DirectoryInfo(AppContext.BaseDirectory);
+ while (current is not null && !File.Exists(Path.Combine(current.FullName, "Aetheris.slnx"))) current = current.Parent;
+ return current?.FullName ?? throw new DirectoryNotFoundException("Repository root not found.");
+ }
+}
diff --git a/Aetheris.Surfacing/BoundedPcurveBuilder.cs b/Aetheris.Surfacing/BoundedPcurveBuilder.cs
new file mode 100644
index 00000000..ad61b080
--- /dev/null
+++ b/Aetheris.Surfacing/BoundedPcurveBuilder.cs
@@ -0,0 +1,227 @@
+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.Surfacing;
+
+public sealed record PcurveBuildResult(bool IsSuccess, int Count, double MaximumResidual, IReadOnlyList<SculptDiagnostic> Diagnostics);
+
+/// <summary>Builds deterministic face-local pcurves for the qualified Plane/Cylinder/non-rational B-spline matrix.</summary>
+public static class BoundedPcurveBuilder
+{
+ public static PcurveBuildResult Populate(TopologyModel topology, BrepGeometryStore geometry, BrepBindingModel bindings,
+ double tolerance = 1e-5, int sampleCount = 129)
+ {
+ var diagnostics = new List<SculptDiagnostic>();
+ var count = 0;
+ var maximum = 0d;
+ foreach (var face in topology.Faces.OrderBy(item => item.Id.Value))
+ {
+ if (!bindings.TryGetFaceBinding(face.Id, out var faceBinding) || !geometry.TryGetSurface(faceBinding.SurfaceGeometryId, out var surface) || surface is null)
+ continue;
+ foreach (var coedge in face.LoopIds.Select(topology.GetLoop).SelectMany(loop => loop.CoedgeIds.Select(topology.GetCoedge)))
+ {
+ if (!bindings.TryGetEdgeBinding(coedge.EdgeId, out var edgeBinding) || !geometry.TryGetCurve(edgeBinding.CurveGeometryId, out var curve) || curve is null
+ || edgeBinding.TrimInterval is not { } interval)
+ {
+ diagnostics.Add(new("surf-pcurve-invalid", $"Coedge {coedge.Id.Value} has no bounded 3D edge curve.", coedge.Id.Value.ToString()));
+ continue;
+ }
+ var built = Build(surface, curve, interval, tolerance, sampleCount);
+ if (built.Pcurve is null)
+ {
+ diagnostics.Add(new("surf-pcurve-invalid", built.Diagnostic ?? "Pcurve construction failed.", coedge.Id.Value.ToString()));
+ continue;
+ }
+ bindings.AddPcurveBinding(new(coedge.Id, face.Id, faceBinding.SurfaceGeometryId, built.Pcurve));
+ maximum = double.Max(maximum, built.MaximumResidual);
+ count++;
+ }
+ }
+ return new(diagnostics.Count == 0 && maximum <= tolerance, count, maximum, diagnostics);
+ }
+
+ private static (PcurveGeometry? Pcurve, double MaximumResidual, string? Diagnostic) Build(
+ SurfaceGeometry surface, CurveGeometry curve, ParameterInterval interval, double tolerance, int samples)
+ {
+ if (surface.Plane is { } plane)
+ {
+ var start = PlaneUv(plane, EvaluateCurve(curve, interval.Start));
+ var end = PlaneUv(plane, EvaluateCurve(curve, interval.End));
+ if (curve.Kind == CurveGeometryKind.Line3) return (PcurveGeometry.Line(interval, start, end), 0d, null);
+ if (curve.Kind == CurveGeometryKind.Circle3 && curve.Circle3 is { } circle)
+ {
+ var center = PlaneUv(plane, circle.Center);
+ var cosinePoint = PlaneUv(plane, circle.Evaluate(0d));
+ var sinePoint = PlaneUv(plane, circle.Evaluate(double.Pi / 2d));
+ return (PcurveGeometry.Ellipse(interval, center,
+ new(cosinePoint.U - center.U, cosinePoint.V - center.V),
+ new(sinePoint.U - center.U, sinePoint.V - center.V)), 0d, null);
+ }
+ var lineCandidate = PcurveGeometry.Line(interval, start, end);
+ var lineResidual = MaximumResidual(surface, curve, lineCandidate, interval, 67);
+ if (lineResidual <= tolerance) return (lineCandidate, lineResidual, null);
+ const int denseSamples = 4097;
+ return (PcurveGeometry.Polyline(interval, Sample(interval, denseSamples, t => PlaneUv(plane, EvaluateCurve(curve, t)))), 0d, null);
+ }
+ if (surface.Cylinder is { } cylinder)
+ {
+ var points = Sample(interval, samples, t => CylinderUv(cylinder, EvaluateCurve(curve, t))).ToArray();
+ UnwrapAngles(points);
+ return (PcurveGeometry.Polyline(interval, points), 0d, null);
+ }
+ if (surface.BSplineSurfaceWithKnots is not { } spline)
+ return (null, double.PositiveInfinity, $"Surface family {surface.Kind} is outside the qualified pcurve matrix.");
+
+ var startInverse = Invert(spline, EvaluateCurve(curve, interval.Start), null);
+ var endInverse = Invert(spline, EvaluateCurve(curve, interval.End), startInverse.Success ? startInverse.Uv : null);
+ if (startInverse.Success && endInverse.Success)
+ {
+ var lineCandidate = PcurveGeometry.Line(interval, startInverse.Uv, endInverse.Uv);
+ var lineResidual = MaximumResidual(surface, curve, lineCandidate, interval, 67);
+ if (lineResidual <= tolerance) return (lineCandidate, lineResidual, null);
+ }
+
+ const int inverseSamples = 4097;
+ var uv = new List<SurfaceParameterPoint>(inverseSamples);
+ SurfaceParameterPoint? seed = null;
+ var maximum = 0d;
+ for (var index = 0; index < inverseSamples; index++)
+ {
+ var t = interval.Start + ((interval.End - interval.Start) * index / (inverseSamples - 1d));
+ var point = EvaluateCurve(curve, t);
+ var inverse = Invert(spline, point, seed);
+ if (!inverse.Success || inverse.Residual > tolerance)
+ return (null, inverse.Residual, $"Non-rational B-spline inverse failed at sample {index}; residual={inverse.Residual:R}, tolerance={tolerance:R}.");
+ seed = inverse.Uv;
+ uv.Add(inverse.Uv);
+ maximum = double.Max(maximum, inverse.Residual);
+ }
+ return (PcurveGeometry.Polyline(interval, uv), maximum, null);
+ }
+
+ private static (bool Success, SurfaceParameterPoint Uv, double Residual) Invert(BSplineSurfaceWithKnots spline, Point3D target, SurfaceParameterPoint? prior)
+ {
+ // Intersection traces are parameter-continuous, so the preceding inverse is
+ // the deterministic seed after the first sample. Avoiding a fresh global grid
+ // search at every dense qualification point keeps high-accuracy pcurves bounded.
+ var best = prior ?? GridSeed(spline, target);
+ for (var iteration = 0; iteration < 32; iteration++)
+ {
+ var point = spline.Evaluate(best.U, best.V);
+ var residual = point - target;
+ if (residual.Length <= 1e-8d) return (true, best, residual.Length);
+ var hu = double.Max((spline.DomainEndU - spline.DomainStartU) * 1e-4d, 1e-7d);
+ var hv = double.Max((spline.DomainEndV - spline.DomainStartV) * 1e-4d, 1e-7d);
+ var du = (spline.Evaluate(double.Min(best.U + hu, spline.DomainEndU), best.V) - spline.Evaluate(double.Max(best.U - hu, spline.DomainStartU), best.V))
+ / (double.Min(best.U + hu, spline.DomainEndU) - double.Max(best.U - hu, spline.DomainStartU));
+ var dv = (spline.Evaluate(best.U, double.Min(best.V + hv, spline.DomainEndV)) - spline.Evaluate(best.U, double.Max(best.V - hv, spline.DomainStartV)))
+ / (double.Min(best.V + hv, spline.DomainEndV) - double.Max(best.V - hv, spline.DomainStartV));
+ var a = du.Dot(du); var b = du.Dot(dv); var c = dv.Dot(dv);
+ var r1 = du.Dot(residual); var r2 = dv.Dot(residual);
+ var determinant = (a * c) - (b * b);
+ if (double.Abs(determinant) <= 1e-18d) break;
+ var deltaU = ((c * r1) - (b * r2)) / determinant;
+ var deltaV = ((a * r2) - (b * r1)) / determinant;
+ var accepted = false;
+ for (var damping = 1d; damping >= 1d / 64d; damping *= .5d)
+ {
+ var candidate = new SurfaceParameterPoint(
+ System.Math.Clamp(best.U - (deltaU * damping), spline.DomainStartU, spline.DomainEndU),
+ System.Math.Clamp(best.V - (deltaV * damping), spline.DomainStartV, spline.DomainEndV));
+ if ((spline.Evaluate(candidate.U, candidate.V) - target).LengthSquared >= residual.LengthSquared) continue;
+ best = candidate; accepted = true; break;
+ }
+ if (!accepted) break;
+ }
+ // Deterministic bounded pattern refinement handles domain-boundary minima where
+ // the two-column normal equation can become poorly conditioned.
+ var stepU = (spline.DomainEndU - spline.DomainStartU) / 32d;
+ var stepV = (spline.DomainEndV - spline.DomainStartV) / 32d;
+ var bestDistance = (spline.Evaluate(best.U, best.V) - target).LengthSquared;
+ for (var iteration = 0; iteration < 64 && (stepU > 1e-13d || stepV > 1e-13d); iteration++)
+ {
+ var improved = false;
+ foreach (var offsetU in new[] { -stepU, 0d, stepU }) foreach (var offsetV in new[] { -stepV, 0d, stepV })
+ {
+ if (offsetU == 0d && offsetV == 0d) continue;
+ var candidate = new SurfaceParameterPoint(
+ System.Math.Clamp(best.U + offsetU, spline.DomainStartU, spline.DomainEndU),
+ System.Math.Clamp(best.V + offsetV, spline.DomainStartV, spline.DomainEndV));
+ var distance = (spline.Evaluate(candidate.U, candidate.V) - target).LengthSquared;
+ if (distance >= bestDistance) continue;
+ best = candidate; bestDistance = distance; improved = true;
+ }
+ if (!improved) { stepU *= .5d; stepV *= .5d; }
+ }
+ var finalResidual = (spline.Evaluate(best.U, best.V) - target).Length;
+ return (finalResidual <= 1e-5d, best, finalResidual);
+ }
+
+ private static SurfaceParameterPoint GridSeed(BSplineSurfaceWithKnots spline, Point3D target)
+ {
+ var best = new SurfaceParameterPoint(spline.DomainStartU, spline.DomainStartV);
+ var distance = double.PositiveInfinity;
+ const int divisions = 32;
+ for (var i = 0; i <= divisions; i++) for (var j = 0; j <= divisions; j++)
+ {
+ var u = spline.DomainStartU + ((spline.DomainEndU - spline.DomainStartU) * i / divisions);
+ var v = spline.DomainStartV + ((spline.DomainEndV - spline.DomainStartV) * j / divisions);
+ var d = (spline.Evaluate(u, v) - target).LengthSquared;
+ if (d < distance) { distance = d; best = new(u, v); }
+ }
+ return best;
+ }
+
+ private static Point3D EvaluateCurve(CurveGeometry curve, double parameter) => curve.Kind switch
+ {
+ CurveGeometryKind.Line3 => curve.Line3!.Value.Evaluate(parameter),
+ CurveGeometryKind.Circle3 => curve.Circle3!.Value.Evaluate(parameter),
+ CurveGeometryKind.BSpline3 => curve.BSpline3!.Value.Evaluate(parameter),
+ CurveGeometryKind.Ellipse3 => curve.Ellipse3!.Value.Evaluate(parameter),
+ CurveGeometryKind.Hyperbola3 => curve.Hyperbola3!.Value.Evaluate(parameter),
+ _ => throw new NotSupportedException($"Curve family {curve.Kind} is outside the qualified pcurve matrix.")
+ };
+ private static SurfaceParameterPoint PlaneUv(PlaneSurface plane, Point3D point)
+ {
+ var d = point - plane.Origin;
+ return new(d.Dot(plane.UAxis.ToVector()), d.Dot(plane.VAxis.ToVector()));
+ }
+ private static SurfaceParameterPoint CylinderUv(CylinderSurface cylinder, Point3D point)
+ {
+ var d = point - cylinder.Origin;
+ return new(double.Atan2(d.Dot(cylinder.YAxis.ToVector()), d.Dot(cylinder.XAxis.ToVector())), d.Dot(cylinder.Axis.ToVector()));
+ }
+ private static void UnwrapAngles(SurfaceParameterPoint[] points)
+ {
+ for (var index = 1; index < points.Length; index++)
+ {
+ var u = points[index].U;
+ while (u - points[index - 1].U > double.Pi) u -= 2d * double.Pi;
+ while (u - points[index - 1].U < -double.Pi) u += 2d * double.Pi;
+ points[index] = points[index] with { U = u };
+ }
+ }
+ private static IReadOnlyList<SurfaceParameterPoint> Sample(ParameterInterval interval, int count, Func<double, SurfaceParameterPoint> evaluator)
+ => Enumerable.Range(0, count).Select(index => evaluator(interval.Start + ((interval.End - interval.Start) * index / (count - 1d)))).ToArray();
+
+ private static double MaximumResidual(SurfaceGeometry surface, CurveGeometry curve, PcurveGeometry pcurve, ParameterInterval interval, int count)
+ {
+ var maximum = 0d;
+ for (var index = 0; index < count; index++)
+ {
+ var parameter = interval.Start + ((interval.End - interval.Start) * index / (count - 1d));
+ var uv = pcurve.Evaluate(parameter);
+ var onSurface = surface.Kind switch
+ {
+ SurfaceGeometryKind.Plane => surface.Plane!.Value.Evaluate(uv.U, uv.V),
+ SurfaceGeometryKind.BSplineSurfaceWithKnots => surface.BSplineSurfaceWithKnots!.Evaluate(uv.U, uv.V),
+ _ => throw new InvalidOperationException()
+ };
+ maximum = double.Max(maximum, (onSurface - EvaluateCurve(curve, parameter)).Length);
+ }
+ return maximum;
+ }
+}
diff --git a/Aetheris.Surfacing/ImportedFaceRegionReplacer.cs b/Aetheris.Surfacing/ImportedFaceRegionReplacer.cs
new file mode 100644
index 00000000..14af6342
--- /dev/null
+++ b/Aetheris.Surfacing/ImportedFaceRegionReplacer.cs
@@ -0,0 +1,122 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.Surfacing;
+
+public sealed record ImportedFaceReplacementEvidence(
+ int SourceStepFaceEntityId,
+ int CurrentFaceId,
+ IReadOnlyList<int> PreservedNeighborSourceStepEntityIds,
+ int InnerLoopCount,
+ BrepPcurveEvidence Pcurves);
+
+public sealed record ImportedFaceReplacementResult(
+ bool IsSuccess,
+ BodyState? OutputState,
+ ImportedFaceReplacementEvidence? Evidence,
+ IReadOnlyList<SculptDiagnostic> Diagnostics);
+
+/// <summary>
+/// Bounded imported-face graft: topology, edge curves, vertices, and neighboring face bindings are
+/// retained from the imported BRep; only the selected ADVANCED_FACE support binding is succeeded.
+/// </summary>
+public static class ImportedFaceRegionReplacer
+{
+ public static BodyState AdoptImportedBody(BodyState semanticSource, BrepBody importedBody, string authoredName)
+ {
+ ArgumentNullException.ThrowIfNull(semanticSource); ArgumentNullException.ThrowIfNull(importedBody);
+ var associations = SculptedHousingFactory.PersistentAssociations(importedBody, semanticSource.Construction);
+ return semanticSource with
+ {
+ StateId = BodyStateId.Derive($"{semanticSource.StateId.Value}|ImportedStep|{importedBody.Topology.Faces.Count()}"),
+ PredecessorStateId = semanticSource.StateId,
+ AuthoredName = authoredName,
+ Body = importedBody,
+ GeometryAssociations = associations,
+ SemanticPmi = SculptedHousingFactory.SemanticPmi(associations, semanticSource.Construction),
+ AssemblyInterfaces = SculptedHousingFactory.AssemblyInterfaces(associations)
+ };
+ }
+
+ public static ImportedFaceReplacementResult Apply(
+ BodyState importedState,
+ int sourceStepFaceEntityId,
+ BSplineSurfacePatch replacementPatch,
+ string outputName,
+ double tolerance = 1e-5)
+ {
+ var historical = importedState.Delta?.Correspondence.FirstOrDefault(item => item.Change == GeometricChangeKind.Replaced
+ && item.InputEntity == $"ADVANCED_FACE:{sourceStepFaceEntityId}");
+ if (historical is not null)
+ return Failure("surf-selector-target-replaced", $"Imported ADVANCED_FACE #{sourceStepFaceEntityId} was replaced by {string.Join(", ", historical.OutputEntities)} in state {importedState.StateId.Value}; select current geometry.");
+ var selectedBindings = importedState.Body.Bindings.FaceBindings.Where(binding => binding.SourceStepEntityId == sourceStepFaceEntityId).ToArray();
+ if (selectedBindings.Length != 1)
+ return Failure("surf-imported-selector-unresolved", $"Imported ADVANCED_FACE #{sourceStepFaceEntityId} resolved to {selectedBindings.Length} current faces.");
+ var selected = selectedBindings[0];
+ var face = importedState.Body.Topology.GetFace(selected.FaceId);
+ if (face.LoopIds.Count == 0) return Failure("surf-inner-loop-invalid", "Selected imported face has no outer loop.");
+
+ var geometry = new BrepGeometryStore();
+ foreach (var curve in importedState.Body.Geometry.Curves) geometry.AddCurve(curve.Key, curve.Value);
+ foreach (var surface in importedState.Body.Geometry.Surfaces) geometry.AddSurface(surface.Key, surface.Value);
+ var newSurfaceId = new Aetheris.Kernel.Core.Geometry.SurfaceGeometryId(importedState.Body.Geometry.Surfaces.Select(item => item.Key.Value).DefaultIfEmpty().Max() + 1);
+ geometry.AddSurface(newSurfaceId, replacementPatch.Support);
+
+ var bindings = new BrepBindingModel();
+ foreach (var edge in importedState.Body.Bindings.EdgeBindings) bindings.AddEdgeBinding(edge);
+ foreach (var binding in importedState.Body.Bindings.FaceBindings)
+ bindings.AddFaceBinding(binding.FaceId == selected.FaceId
+ ? new FaceGeometryBinding(binding.FaceId, newSurfaceId, replacementPatch.ReversedOrientation, binding.SourceStepEntityId)
+ : binding);
+ var vertexPoints = importedState.Body.Topology.Vertices.Where(vertex => importedState.Body.TryGetVertexPoint(vertex.Id, out _))
+ .ToDictionary(vertex => vertex.Id, vertex => { importedState.Body.TryGetVertexPoint(vertex.Id, out var point); return point; });
+ var body = new BrepBody(importedState.Body.Topology, geometry, bindings, vertexPoints,
+ importedState.Body.SafeBooleanComposition, importedState.Body.ShellRepresentation);
+ var pcurveBuild = BoundedPcurveBuilder.Populate(body.Topology, geometry, bindings, tolerance);
+ if (!pcurveBuild.IsSuccess) return new(false, null, null, pcurveBuild.Diagnostics);
+ var pcurveEvidence = BrepPcurveValidator.Validate(body, tolerance, requireEveryCoedge: true);
+ if (!pcurveEvidence.IsValid) return Failure("surf-pcurve-invalid", string.Join(" | ", pcurveEvidence.Diagnostics));
+ var preflight = BrepExportPreflight.Validate(body);
+ if (!preflight.IsValid) return Failure("surf-imported-replacement-invalid", string.Join(" | ", preflight.Diagnostics.Where(item => item.Severity == BrepExportPreflightSeverity.Error).Select(item => item.Message)));
+
+ var construction = importedState.Construction with
+ {
+ ReplacementPatch = replacementPatch,
+ CrownWidth = importedState.Construction.Width,
+ CrownDepth = importedState.Construction.Depth,
+ CrownOffset = SampleMaximumZ(replacementPatch) - importedState.Construction.BaseHeight
+ };
+ var inventory = importedState.SemanticInventory.ToDictionary(item => item.Key, item => item.Value, StringComparer.Ordinal);
+ inventory.Remove(SculptedHousingFactory.CrownRegion);
+ inventory[replacementPatch.PatchId] = new(replacementPatch.PatchId, SculptEntityKind.Surface,
+ $"{replacementPatch.ExportClass}:{replacementPatch.DegreeU}x{replacementPatch.DegreeV}:{replacementPatch.ControlCountU}x{replacementPatch.ControlCountV}",
+ "Imported ADVANCED_FACE semantic successor.");
+ var outputId = BodyStateId.Derive($"{importedState.StateId.Value}|ImportedReplaceRegion|{sourceStepFaceEntityId}|{replacementPatch.PatchId}");
+ var delta = new GeometricDelta(importedState.StateId, outputId, [$"ADVANCED_FACE:{sourceStepFaceEntityId}"],
+ [SculptedHousingFactory.BottomMountingInterface, SculptedHousingFactory.MountingHolePattern], [SculptedHousingFactory.CrownRegion], [], [replacementPatch.PatchId],
+ [SculptedHousingFactory.CrownRegion], new(-construction.Width / 2d, -construction.Depth / 2d, construction.BaseHeight, construction.Width / 2d, construction.Depth / 2d, construction.FinalHeight),
+ [new(SculptedHousingFactory.BottomMountingInterface, GeometricChangeKind.Preserved, [SculptedHousingFactory.BottomMountingInterface], "Explicit imported bottom-interface face association retained."),
+ new(SculptedHousingFactory.MountingHolePattern, GeometricChangeKind.Preserved, [SculptedHousingFactory.MountingHolePattern], "Explicit imported cylindrical-face associations retained."),
+ new(SculptedHousingFactory.CrownRegion, GeometricChangeKind.Replaced, [replacementPatch.PatchId], $"Explicit imported provenance ADVANCED_FACE #{sourceStepFaceEntityId}."),
+ new($"ADVANCED_FACE:{sourceStepFaceEntityId}", GeometricChangeKind.Replaced, [replacementPatch.PatchId], "Imported selector succession is explicit and stale-safe.")]);
+ var associationRemap = SculptedHousingFactory.RemapPersistentAssociations(importedState, body, delta);
+ if (!associationRemap.IsSuccess) return new(false, null, null, associationRemap.Diagnostics);
+ var associations = associationRemap.Associations;
+ var evidence = new ImportedFaceReplacementEvidence(sourceStepFaceEntityId, selected.FaceId.Value,
+ bindings.FaceBindings.Where(binding => binding.FaceId != selected.FaceId && binding.SourceStepEntityId.HasValue).Select(binding => binding.SourceStepEntityId!.Value).Order().ToArray(),
+ face.LoopIds.Count - 1, pcurveEvidence);
+ var validations = SculptedHousingFactory.ValidateBody(body, tolerance).Append(new SculptValidationEvidence("ImportedFaceReplacement", true,
+ LocalityEvidenceLevel.CertifiedBounded, 0d, tolerance, $"Retained topology and {evidence.PreservedNeighborSourceStepEntityIds.Count} neighboring imported face provenances; replaced support on current face {selected.FaceId.Value}.")).ToArray();
+ var output = new BodyState(outputId, importedState.StateId, importedState.BodyStableId, outputName, body, construction, inventory, delta, validations,
+ associations, SculptedHousingFactory.SemanticPmi(associations, construction), SculptedHousingFactory.AssemblyInterfaces(associations));
+ return new(true, output, evidence, []);
+ }
+
+ private static double SampleMaximumZ(BSplineSurfacePatch patch)
+ {
+ var d = patch.ParameterDomain;
+ return Enumerable.Range(0, 17).SelectMany(i => Enumerable.Range(0, 17).Select(j => patch.Evaluate(
+ d.UMin + ((d.UMax - d.UMin) * i / 16d), d.VMin + ((d.VMax - d.VMin) * j / 16d)).Z)).Max();
+ }
+ private static ImportedFaceReplacementResult Failure(string code, string message) => new(false, null, null, [new(code, message)]);
+}
diff --git a/Aetheris.Surfacing/SculptedHousingBrepBuilder.cs b/Aetheris.Surfacing/SculptedHousingBrepBuilder.cs
index 26039bce..a03ad15a 100644
--- a/Aetheris.Surfacing/SculptedHousingBrepBuilder.cs
+++ b/Aetheris.Surfacing/SculptedHousingBrepBuilder.cs
@@ -94,8 +94,12 @@ internal static class SculptedHousingBrepBuilder
var surfaceId = 1;
foreach (var (face, surface) in faces) { var id = new SurfaceGeometryId(surfaceId++); geometry.AddSurface(id, surface); bindings.AddFaceBinding(new(face, id)); }
var body = new BrepBody(b.Model, geometry, bindings, points);
+ var pcurves = BoundedPcurveBuilder.Populate(b.Model, geometry, bindings);
+ if (!pcurves.IsSuccess) return new(null, pcurves.Diagnostics);
var binding = BrepBindingValidator.Validate(body, true);
if (!binding.IsSuccess) return new(null, binding.Diagnostics.Select(x => new SculptDiagnostic("sculpt-brep-binding-invalid", x.Message)).ToArray());
+ var pcurveEvidence = BrepPcurveValidator.Validate(body, 1e-5, requireEveryCoedge: true);
+ if (!pcurveEvidence.IsValid) return new(null, pcurveEvidence.Diagnostics.Select(message => new SculptDiagnostic("surf-pcurve-invalid", message)).ToArray());
return new(body, []);
}
@@ -124,8 +128,11 @@ internal static class SculptedHousingBrepBuilder
patch.Evaluate(patch.ParameterDomain.UMax, patch.ParameterDomain.VMax),
patch.Evaluate(patch.ParameterDomain.UMin, patch.ParameterDomain.VMax),
};
- var vi = corners.Select(p => { var id = builder.AddVertex(); points[id] = p; return id; }).ToArray();
- var ei = Enumerable.Range(0, 4).Select(i => AddLine(builder, curves, vi[i], vi[(i + 1) % 4], points)).ToArray();
+ var coversWholeTop = corners.Zip(top).All(pair => (pair.First - pair.Second).Length <= 1e-6d);
+ var vi = coversWholeTop ? vt : corners.Select(p => { var id = builder.AddVertex(); points[id] = p; return id; }).ToArray();
+ var ei = coversWholeTop ? et : Enumerable.Range(0, 4).Select(i => AddLine(builder, curves, vi[i], vi[(i + 1) % 4], points)).ToArray();
+ if (coversWholeTop && patch is BSplineSurfacePatch wholeSpline)
+ BindExactSplineBoundaryCurves(curves, et, wholeSpline.Spline);
var bhv = new VertexId[c.Holes.Count]; var thv = new VertexId[c.Holes.Count];
var bhe = new EdgeId[c.Holes.Count]; var the = new EdgeId[c.Holes.Count]; var seams = new EdgeId[c.Holes.Count];
@@ -142,13 +149,16 @@ internal static class SculptedHousingBrepBuilder
for (var i = 0; i < c.Holes.Count; i++) bottomLoops.Add(AddLoop(builder, [new(bhe[i], true)]));
faces.Add((builder.AddFace(bottomLoops), SurfaceGeometry.FromPlane(new PlaneSurface(Point3D.Origin, Dir(0, 0, -1), Dir(1, 0, 0))), false));
- var frameLoops = new List<LoopId>
+ if (!coversWholeTop)
{
- AddLoop(builder, et.Select(x => new Use(x, true)).Reverse().ToArray()),
- AddLoop(builder, ei.Select(x => new Use(x, false)).ToArray()),
- };
- for (var i = 0; i < c.Holes.Count; i++) frameLoops.Add(AddLoop(builder, [new(the[i], false)]));
- faces.Add((builder.AddFace(frameLoops), SurfaceGeometry.FromPlane(new PlaneSurface(new(0, 0, c.BaseHeight), Dir(0, 0, 1), Dir(1, 0, 0))), false));
+ var frameLoops = new List<LoopId>
+ {
+ AddLoop(builder, et.Select(x => new Use(x, true)).Reverse().ToArray()),
+ AddLoop(builder, ei.Select(x => new Use(x, false)).ToArray()),
+ };
+ for (var i = 0; i < c.Holes.Count; i++) frameLoops.Add(AddLoop(builder, [new(the[i], false)]));
+ faces.Add((builder.AddFace(frameLoops), SurfaceGeometry.FromPlane(new PlaneSurface(new(0, 0, c.BaseHeight), Dir(0, 0, 1), Dir(1, 0, 0))), false));
+ }
for (var i = 0; i < 4; i++)
{
@@ -158,8 +168,10 @@ internal static class SculptedHousingBrepBuilder
faces.Add((builder.AddFace([loop]), SurfaceGeometry.FromPlane(new PlaneSurface(bottom[i], Direction3D.Create(edge.Cross(rise)), Direction3D.Create(edge))), false));
}
- var patchLoop = AddLoop(builder, ei.Select(x => new Use(x, true)).Reverse().ToArray());
- faces.Add((builder.AddFace([patchLoop]), patch.Support, patch.ReversedOrientation));
+ var patchLoops = new List<LoopId> { AddLoop(builder, ei.Select(x => new Use(x, true)).Reverse().ToArray()) };
+ if (coversWholeTop)
+ for (var i = 0; i < c.Holes.Count; i++) patchLoops.Add(AddLoop(builder, [new(the[i], false)]));
+ faces.Add((builder.AddFace(patchLoops), patch.Support, patch.ReversedOrientation));
for (var i = 0; i < c.Holes.Count; i++)
{
var loop = AddLoop(builder, [new(bhe[i], false), new(seams[i], false), new(the[i], true), new(seams[i], true)]);
@@ -179,8 +191,12 @@ internal static class SculptedHousingBrepBuilder
var id = new SurfaceGeometryId(surfaceId++); geometry.AddSurface(id, face.Surface); bindings.AddFaceBinding(new(face.Face, id, face.Reversed));
}
var body = new BrepBody(builder.Model, geometry, bindings, points);
+ var pcurves = BoundedPcurveBuilder.Populate(builder.Model, geometry, bindings);
+ if (!pcurves.IsSuccess) return new(null, pcurves.Diagnostics);
var validation = BrepBindingValidator.Validate(body, true);
- return validation.IsSuccess ? new(body, []) : new(null, validation.Diagnostics.Select(x => new SculptDiagnostic("sculpt-brep-binding-invalid", x.Message)).ToArray());
+ if (!validation.IsSuccess) return new(null, validation.Diagnostics.Select(x => new SculptDiagnostic("sculpt-brep-binding-invalid", x.Message)).ToArray());
+ var pcurveEvidence = BrepPcurveValidator.Validate(body, 1e-5, requireEveryCoedge: true);
+ return pcurveEvidence.IsValid ? new(body, []) : new(null, pcurveEvidence.Diagnostics.Select(message => new SculptDiagnostic("surf-pcurve-invalid", message)).ToArray());
}
private static EdgeId AddLine(TopologyBuilder builder, IDictionary<EdgeId, (CurveGeometry, ParameterInterval)> curves, VertexId start, VertexId end, IReadOnlyDictionary<VertexId, Point3D> points)
@@ -197,6 +213,24 @@ internal static class SculptedHousingBrepBuilder
return edge;
}
+ private static void BindExactSplineBoundaryCurves(IDictionary<EdgeId, (CurveGeometry, ParameterInterval)> curves, IReadOnlyList<EdgeId> edges, BSplineSurfaceWithKnots spline)
+ {
+ var south = spline.ControlPoints.Select(row => row[0]).ToArray();
+ var east = spline.ControlPoints[^1].ToArray();
+ var north = spline.ControlPoints.Select(row => row[^1]).Reverse().ToArray();
+ var west = spline.ControlPoints[0].Reverse().ToArray();
+ curves[edges[0]] = (CurveGeometry.FromBSpline(new BSpline3Curve(spline.DegreeU, south, spline.KnotMultiplicitiesU, spline.KnotValuesU, "UNSPECIFIED", false, false, spline.KnotSpec)), new(spline.DomainStartU, spline.DomainEndU));
+ curves[edges[1]] = (CurveGeometry.FromBSpline(new BSpline3Curve(spline.DegreeV, east, spline.KnotMultiplicitiesV, spline.KnotValuesV, "UNSPECIFIED", false, false, spline.KnotSpec)), new(spline.DomainStartV, spline.DomainEndV));
+ curves[edges[2]] = (CurveGeometry.FromBSpline(new BSpline3Curve(spline.DegreeU, north, spline.KnotMultiplicitiesU.Reverse().ToArray(), ReverseKnots(spline.KnotValuesU), "UNSPECIFIED", false, false, spline.KnotSpec)), new(spline.DomainStartU, spline.DomainEndU));
+ curves[edges[3]] = (CurveGeometry.FromBSpline(new BSpline3Curve(spline.DegreeV, west, spline.KnotMultiplicitiesV.Reverse().ToArray(), ReverseKnots(spline.KnotValuesV), "UNSPECIFIED", false, false, spline.KnotSpec)), new(spline.DomainStartV, spline.DomainEndV));
+ }
+
+ private static IReadOnlyList<double> ReverseKnots(IReadOnlyList<double> knots)
+ {
+ var sum = knots[0] + knots[^1];
+ return knots.Reverse().Select(value => sum - value).ToArray();
+ }
+
private static List<SculptDiagnostic> Validate(HousingConstruction c)
{
var d = new List<SculptDiagnostic>();
@@ -210,7 +244,8 @@ internal static class SculptedHousingBrepBuilder
d.Add(new("sculpt-hole-pattern-outside-body", $"Mounting hole '{h.StableId}' must remain inside the housing footprint.", h.StableId));
if (c.ReplacementPatch is null && (Math.Abs(h.CenterX) + r >= c.CrownWidth / 2d || Math.Abs(h.CenterY) + r >= c.CrownDepth / 2d))
d.Add(new("sculpt-hole-pattern-outside-crown", $"Mounting hole '{h.StableId}' must remain inside the bounded crown support.", h.StableId));
- if (c.ReplacementPatch is not null && Math.Abs(h.CenterX) - r < c.CrownWidth / 2d && Math.Abs(h.CenterY) - r < c.CrownDepth / 2d)
+ if (c.ReplacementPatch is not null && (c.CrownWidth < c.Width - 1e-9d || c.CrownDepth < c.Depth - 1e-9d)
+ && Math.Abs(h.CenterX) - r < c.CrownWidth / 2d && Math.Abs(h.CenterY) - r < c.CrownDepth / 2d)
d.Add(new("surf-patch-intersects-protected-hole", $"Replacement patch intersects protected mounting hole '{h.StableId}'. Move the hole or reduce the patch boundary.", h.StableId));
}
for (var i = 0; i < c.Holes.Count; i++) for (var j = i + 1; j < c.Holes.Count; j++)
diff --git a/Aetheris.Surfacing/SculptingExecution.cs b/Aetheris.Surfacing/SculptingExecution.cs
index 24729d1d..57b76008 100644
--- a/Aetheris.Surfacing/SculptingExecution.cs
+++ b/Aetheris.Surfacing/SculptingExecution.cs
@@ -33,7 +33,9 @@ public static class SculptedHousingFactory
var evidence = ValidateBody(built.Body, height);
if (evidence.Any(x => !x.Satisfied)) return SculptResult.Failure(
[new("sculpt-base-invalid", "Initial body did not satisfy the body-state validity contract: " + string.Join("; ", evidence.Where(x => !x.Satisfied).Select(x => $"{x.Check}: {x.Detail}")))], evidence);
- return new(true, new(stateId, null, "housing-body", stateName, built.Body, construction, inventory, null, evidence), null, evidence, []);
+ var associations = PersistentAssociations(built.Body, construction);
+ return new(true, new(stateId, null, "housing-body", stateName, built.Body, construction, inventory, null, evidence,
+ associations, SemanticPmi(associations, construction), AssemblyInterfaces(associations)), null, evidence, []);
}
internal static IReadOnlyDictionary<string, SculptSemanticEntity> Inventory(HousingConstruction c)
@@ -59,14 +61,78 @@ public static class SculptedHousingFactory
{
var preflight = BrepExportPreflight.Validate(body);
var mass = BrepMassProperties.Evaluate(body);
+ var pcurves = BrepPcurveValidator.Validate(body, 1e-5d, requireEveryCoedge: true);
return
[
- new("ClosedManifold", preflight.IsValid && mass.IsEnclosed, LocalityEvidenceLevel.CertifiedBounded, null, 1e-6, $"BRep preflight errors={preflight.ErrorCount}; independent edge-incidence enclosure={mass.IsEnclosed}."),
+ new("ClosedManifold", preflight.IsValid && mass.IsEnclosed, LocalityEvidenceLevel.CertifiedBounded, null, 1e-6, $"BRep preflight errors={preflight.ErrorCount}; independent edge-incidence enclosure={mass.IsEnclosed}. {string.Join(" | ", preflight.Diagnostics.Where(item => item.Severity == BrepExportPreflightSeverity.Error).Select(item => $"{item.Code}[edge={item.EdgeId}]:{item.Message}"))}"),
new("OrientationConsistency", mass.IsOrientationConsistent, LocalityEvidenceLevel.CertifiedBounded, null, 1e-9, $"Independent boundary verifier orientationConsistent={mass.IsOrientationConsistent}."),
new("NoSelfIntersection", preflight.IsValid, LocalityEvidenceLevel.CertifiedBounded, null, 1e-6, "Bounded analytic construction validation plus BRep export preflight; this is not a general-purpose global intersection proof."),
+ new("PcurveConsistency", pcurves.IsValid, LocalityEvidenceLevel.CertifiedBounded, pcurves.MaximumReconstructionDeviation, 1e-5d,
+ $"Independent reconstruction: edges={pcurves.EdgeCount}, pcurves={pcurves.PcurveCount}, domainValid={pcurves.DomainValid}, orientationConsistent={pcurves.OrientationConsistent}. {string.Join(" | ", pcurves.Diagnostics)}"),
];
}
+ internal static IReadOnlyList<PersistentGeometryAssociation> PersistentAssociations(BrepBody body, HousingConstruction construction)
+ {
+ var bottom = body.Topology.Faces.Where(face => body.TryGetFaceSurfaceGeometry(face.Id, out var support)
+ && support?.Plane is { } plane && Math.Abs(plane.Origin.Z) <= 1e-8d && plane.Normal.ToVector().Z < 0d).Select(face => face.Id.Value).ToArray();
+ var cylinders = body.Topology.Faces.Where(face => body.TryGetFaceSurfaceGeometry(face.Id, out var support) && support?.Cylinder is not null)
+ .Select(face => face.Id.Value).Order().ToArray();
+ return
+ [
+ new(BottomMountingInterface, PersistentAssociationState.Preserved, bottom, "Explicit protected bottom-plane association."),
+ new(MountingHolePattern, PersistentAssociationState.Preserved, cylinders, "Explicit protected cylindrical-face association."),
+ ];
+ }
+
+ public static PersistentAssociationRemapResult RemapPersistentAssociations(BodyState input, BrepBody outputBody, GeometricDelta delta)
+ {
+ var remapped = new List<PersistentGeometryAssociation>();
+ var diagnostics = new List<SculptDiagnostic>();
+ foreach (var association in input.GeometryAssociations ?? [])
+ {
+ var correspondence = delta.Correspondence.SingleOrDefault(item => item.InputEntity == association.SemanticTarget);
+ if (correspondence is null || correspondence.Change != GeometricChangeKind.Preserved)
+ {
+ diagnostics.Add(new("surf-association-target-removed",
+ $"Association target '{association.SemanticTarget}' has no explicit Preserved correspondence in {delta.OutputState.Value}; semantic rebinding was not guessed.", association.SemanticTarget));
+ continue;
+ }
+ var missing = association.FaceIds.Where(id => !outputBody.Topology.TryGetFace(new(id), out _)).ToArray();
+ if (missing.Length > 0)
+ {
+ diagnostics.Add(new("surf-association-current-geometry-missing",
+ $"Preserved target '{association.SemanticTarget}' references absent current faces: {string.Join(", ", missing)}.", association.SemanticTarget));
+ continue;
+ }
+ remapped.Add(association with
+ {
+ State = PersistentAssociationState.Preserved,
+ Evidence = $"Explicit GeometricDelta Preserved correspondence into {delta.OutputState.Value}; retained current face IDs {string.Join(", ", association.FaceIds)}."
+ });
+ }
+ return new(diagnostics.Count == 0, remapped, diagnostics);
+ }
+
+ internal static IReadOnlyList<Step242SemanticPmi> SemanticPmi(IReadOnlyList<PersistentGeometryAssociation> associations, HousingConstruction construction)
+ {
+ var bottom = associations.Single(item => item.SemanticTarget == BottomMountingInterface).FaceIds;
+ var holes = associations.Single(item => item.SemanticTarget == MountingHolePattern).FaceIds;
+ var diameter = construction.Holes[0].Diameter;
+ return
+ [
+ new Step242SemanticPmiDatum("DatumA", "plane", "A", BottomMountingInterface) { GeometricFaceIds = bottom },
+ new Step242SemanticPmiHole(MountingHolePattern, diameter, construction.BaseHeight, "through", .05d, -.05d, construction.Holes.Count) { GeometricFaceIds = holes },
+ new Step242SemanticPmiGeometricTolerance(MountingHolePattern, "HolePatternPosition", "position", .1d, ["A"], construction.Holes.Count) { GeometricFaceIds = holes },
+ ];
+ }
+
+ internal static IReadOnlyList<SculptAssemblyInterface> AssemblyInterfaces(IReadOnlyList<PersistentGeometryAssociation> associations)
+ {
+ var bottom = associations.Single(item => item.SemanticTarget == BottomMountingInterface);
+ return [new(BottomMountingInterface, bottom.SemanticTarget, bottom.FaceIds, "Protected assembly mounting interface on the bottom planar face.")];
+ }
+
private static string HolePattern(IEnumerable<HousingHole> holes) => string.Join(';', holes.OrderBy(x => x.StableId, StringComparer.Ordinal).Select(HoleFingerprint));
private static string HoleFingerprint(HousingHole h) => $"{h.StableId}@{h.CenterX:R},{h.CenterY:R}:d={h.Diameter:R}";
}
@@ -132,7 +198,11 @@ public static class OffsetRegionSculptor
};
var delta = new GeometricDelta(input.StateId, outputId, [operation.TargetRegion, .. operation.Preserves.Select(x => x.EntityId)], operation.Preserves.Select(x => x.EntityId).ToArray(),
[SculptedHousingFactory.CrownRegion], [], [SculptedHousingFactory.TransitionZone], operation.MayModify, operation.InfluenceEnvelope, correspondence);
- var output = new BodyState(outputId, input.StateId, input.BodyStableId, outputName, built.Body, outputConstruction, inventory, delta, evidence);
+ var associationRemap = SculptedHousingFactory.RemapPersistentAssociations(input, built.Body, delta);
+ if (!associationRemap.IsSuccess) return SculptResult.Failure(associationRemap.Diagnostics, evidence);
+ var outputAssociations = associationRemap.Associations;
+ var output = new BodyState(outputId, input.StateId, input.BodyStableId, outputName, built.Body, outputConstruction, inventory, delta, evidence,
+ outputAssociations, SculptedHousingFactory.SemanticPmi(outputAssociations, outputConstruction), SculptedHousingFactory.AssemblyInterfaces(outputAssociations));
return new(true, output, delta, evidence, []);
}
}
@@ -186,6 +256,19 @@ public static class ReplaceRegionSculptor
if (!rectangular) diagnostics.Add(new("surf-boundary-mismatch", "Patch corners must form the declared axis-aligned rectangular boundary on the existing crown plane."));
if (width > input.Construction.Width || depth > input.Construction.Depth) diagnostics.Add(new("surf-patch-outside-target", "Replacement patch boundary exceeds the housing top region."));
+ if (operation.ReplacementPatch is BSplineSurfacePatch trimSplinePatch
+ && Math.Abs(width - input.Construction.Width) <= operation.GeometricTolerance
+ && Math.Abs(depth - input.Construction.Depth) <= operation.GeometricTolerance)
+ {
+ var intersections = DeriveOuterTrimIntersections(trimSplinePatch, input.Construction, operation);
+ var derived = intersections.Count == 4 && intersections.All(result => result.IsSuccess && result.SelectedBranch is not null);
+ evidence.Add(new("DerivedTrimIntersections", derived, LocalityEvidenceLevel.CertifiedBounded,
+ intersections.Sum(result => result.Branches.Count), 4d,
+ derived ? "Four outer trim edges were derived by qualified Plane/non-rational-B-spline intersections and deterministic branch selection."
+ : string.Join(" | ", intersections.SelectMany(result => result.Diagnostics))));
+ if (!derived) diagnostics.Add(new("surf-intersection-ambiguous", "The whole-top replacement could not derive all four outer trim branches."));
+ }
+
var sampled = Sample(operation.ReplacementPatch, 17);
var maximumZ = sampled.Max(x => x.Z);
var envelopePoints = operation.ReplacementPatch is BSplineSurfacePatch splinePatch
@@ -227,7 +310,10 @@ public static class ReplaceRegionSculptor
}
var locality = SculptLocalityVerifier.CompareOutsideTopEnvelope(input.Body, built.Body, input.Construction.BaseHeight, operation.GeometricTolerance);
evidence.Add(locality); if (!locality.Satisfied) diagnostics.Add(new("sculpt-outside-authorized-region", locality.Detail));
- evidence.AddRange(SculptedHousingFactory.ValidateBody(built.Body, operation.GeometricTolerance));
+ var bodyEvidence = SculptedHousingFactory.ValidateBody(built.Body, operation.GeometricTolerance);
+ evidence.AddRange(bodyEvidence);
+ foreach (var failed in bodyEvidence.Where(item => !item.Satisfied))
+ diagnostics.Add(new("surf-body-invalid", $"{failed.Check}: {failed.Detail}"));
var shared = VerifySharedBoundaryTopology(built.Body);
evidence.Add(shared); if (!shared.Satisfied) diagnostics.Add(new("surf-boundary-not-shared", shared.Detail));
foreach (var requirement in operation.Requirements)
@@ -240,7 +326,11 @@ public static class ReplaceRegionSculptor
.Concat(operation.ReplacementPatch.BoundaryLoop.Boundaries.Select(x => new GeometricDeltaEntry(x.ExistingBoundary, GeometricChangeKind.Preserved, [x.StableId], $"Shared edge correspondence with {x.Continuity}."))).ToArray();
var delta = new GeometricDelta(input.StateId, outputId, [operation.TargetRegion, .. operation.Preserves.Select(x => x.EntityId)], operation.Preserves.Select(x => x.EntityId).ToArray(),
[operation.TargetRegion], [], [operation.ReplacementPatch.PatchId], operation.MayModify, operation.InfluenceEnvelope, correspondence);
- return new(true, new(outputId, input.StateId, input.BodyStableId, outputName, built.Body, construction, inventory, delta, evidence), delta, evidence, []);
+ var associationRemap = SculptedHousingFactory.RemapPersistentAssociations(input, built.Body, delta);
+ if (!associationRemap.IsSuccess) return SculptResult.Failure(associationRemap.Diagnostics, evidence);
+ var outputAssociations = associationRemap.Associations;
+ return new(true, new(outputId, input.StateId, input.BodyStableId, outputName, built.Body, construction, inventory, delta, evidence,
+ outputAssociations, SculptedHousingFactory.SemanticPmi(outputAssociations, construction), SculptedHousingFactory.AssemblyInterfaces(outputAssociations)), delta, evidence, []);
}
private static IReadOnlyList<Point3D> Sample(BoundedSurfacePatch patch, int count)
@@ -251,6 +341,22 @@ public static class ReplaceRegionSculptor
return result;
}
+ private static IReadOnlyList<SurfaceIntersectionResult> DeriveOuterTrimIntersections(BSplineSurfacePatch patch, HousingConstruction construction, ReplaceRegionOperation operation)
+ {
+ var z = construction.BaseHeight; var x = construction.Width / 2d; var y = construction.Depth / 2d;
+ var sideDomain = new SurfaceParameterDomain(-construction.Width, construction.Width, -construction.Depth, construction.Depth);
+ var sides = new[]
+ {
+ ("South", new PlaneSurface(new(0, -y, z), Direction3D.Create(new Vector3D(0, -1, 0)), Direction3D.Create(new Vector3D(1, 0, 0))), new SurfaceParameterPoint(0, 0)),
+ ("East", new PlaneSurface(new(x, 0, z), Direction3D.Create(new Vector3D(1, 0, 0)), Direction3D.Create(new Vector3D(0, 1, 0))), new SurfaceParameterPoint(0, 0)),
+ ("North", new PlaneSurface(new(0, y, z), Direction3D.Create(new Vector3D(0, 1, 0)), Direction3D.Create(new Vector3D(1, 0, 0))), new SurfaceParameterPoint(0, 1)),
+ ("West", new PlaneSurface(new(-x, 0, z), Direction3D.Create(new Vector3D(-1, 0, 0)), Direction3D.Create(new Vector3D(0, 1, 0))), new SurfaceParameterPoint(0, 1)),
+ };
+ return sides.Select(side => BoundedSurfaceIntersector.Intersect(new SurfaceIntersectionRequest(
+ $"Preserved{side.Item1}Plane", SurfaceGeometry.FromPlane(side.Item2), sideDomain,
+ patch.PatchId, patch.Support, patch.ParameterDomain, operation.GeometricTolerance, operation.GeometricTolerance, side.Item3))).ToArray();
+ }
+
private static (double G0, double G1Degrees) MeasureBoundary(BoundedSurfacePatch patch, PatchBoundarySide side, double planeZ, int count)
{
var domain = patch.ParameterDomain; var g0 = 0d; var g1 = 0d;
@@ -317,7 +423,9 @@ public static class SafeHoleSculptor
var correspondence = operation.Preserves.Select(x => new GeometricDeltaEntry(x.EntityId, GeometricChangeKind.Preserved, [x.EntityId], "Resolved and verified against the current BodyState."))
.Append(new("<none>", GeometricChangeKind.Introduced, [operation.Hole.StableId], "Exact cylindrical through-hole on the current planar frame.")).ToArray();
var delta = new GeometricDelta(input.StateId, outputId, [operation.TargetRegion], operation.Preserves.Select(x => x.EntityId).ToArray(), [], [], [operation.Hole.StableId], [operation.TargetRegion], operation.InfluenceEnvelope, correspondence);
- return new(true, new(outputId, input.StateId, input.BodyStableId, outputName, built.Body, construction, inventory, delta, evidence), delta, evidence, []);
+ var outputAssociations = SculptedHousingFactory.PersistentAssociations(built.Body, construction);
+ return new(true, new(outputId, input.StateId, input.BodyStableId, outputName, built.Body, construction, inventory, delta, evidence,
+ outputAssociations, SculptedHousingFactory.SemanticPmi(outputAssociations, construction), SculptedHousingFactory.AssemblyInterfaces(outputAssociations)), delta, evidence, []);
}
}
@@ -387,7 +495,11 @@ public static class SculptStepExporter
{
public static SculptStepResult Export(BodyState state, string productName)
{
- var export = Step242Exporter.ExportBody(state.Body, options: new Step242ExportOptions { BrepExportPreflightMode = BrepExportPreflightMode.Enforce, ProductName = productName });
+ var semanticPmi = new List<Step242SemanticPmi>(state.SemanticPmi ?? []);
+ foreach (var assemblyInterface in state.AssemblyInterfaces ?? [])
+ semanticPmi.Add(new Step242SemanticPmiNote($"assembly-interface:{assemblyInterface.StableId}", assemblyInterface.SemanticTarget, assemblyInterface.Description)
+ { GeometricFaceIds = assemblyInterface.FaceIds });
+ var export = Step242Exporter.ExportBody(state.Body, semanticPmi, new Step242ExportOptions { BrepExportPreflightMode = BrepExportPreflightMode.Enforce, ProductName = productName });
if (!export.IsSuccess) return new(false, null, Empty(), export.Diagnostics.Select(x => new SculptDiagnostic("surf-step-export-failed", x.Message)).ToArray());
var text = export.Value;
var inventory = new StepSurfaceInventory(Count(text, "=PLANE("), Count(text, "=CYLINDRICAL_SURFACE("), Count(text, "=CONICAL_SURFACE("), Count(text, "=SPHERICAL_SURFACE("), Count(text, "=TOROIDAL_SURFACE("), Count(text, "=B_SPLINE_SURFACE_WITH_KNOTS("), 0, Count(text, "RATIONAL_B_SPLINE_SURFACE"));
diff --git a/Aetheris.Surfacing/SculptingState.cs b/Aetheris.Surfacing/SculptingState.cs
index d880bb0d..395a1369 100644
--- a/Aetheris.Surfacing/SculptingState.cs
+++ b/Aetheris.Surfacing/SculptingState.cs
@@ -2,6 +2,7 @@ using System.Security.Cryptography;
using System.Text;
using Aetheris.Kernel.Core.Brep;
using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Step242;
namespace Aetheris.Surfacing;
@@ -48,6 +49,11 @@ public sealed record SculptValidationEvidence(
double Tolerance,
string Detail);
+public enum PersistentAssociationState { Preserved, ReplacedBy, Removed }
+public sealed record PersistentGeometryAssociation(string SemanticTarget, PersistentAssociationState State, IReadOnlyList<int> FaceIds, string Evidence);
+public sealed record PersistentAssociationRemapResult(bool IsSuccess, IReadOnlyList<PersistentGeometryAssociation> Associations, IReadOnlyList<SculptDiagnostic> Diagnostics);
+public sealed record SculptAssemblyInterface(string StableId, string SemanticTarget, IReadOnlyList<int> FaceIds, string Description);
+
public sealed record HousingHole(string StableId, double CenterX, double CenterY, double Diameter);
public sealed record HousingConstruction(
double Width,
@@ -72,10 +78,14 @@ public sealed record BodyState(
HousingConstruction Construction,
IReadOnlyDictionary<string, SculptSemanticEntity> SemanticInventory,
GeometricDelta? Delta,
- IReadOnlyList<SculptValidationEvidence> ValidationEvidence)
+ IReadOnlyList<SculptValidationEvidence> ValidationEvidence,
+ IReadOnlyList<PersistentGeometryAssociation>? GeometryAssociations = null,
+ IReadOnlyList<Step242SemanticPmi>? SemanticPmi = null,
+ IReadOnlyList<SculptAssemblyInterface>? AssemblyInterfaces = null)
{
public IReadOnlyList<SurfacePatchMetadata> SurfacePatches => Construction.ReplacementPatch is { } patch
- ? [SurfacePatchMetadata.From(patch)] : [];
+ ? [SurfacePatchMetadata.From(patch, Body.Topology.Faces.FirstOrDefault(face =>
+ Body.TryGetFaceSurfaceGeometry(face.Id, out var support) && Equals(support, patch.Support))?.LoopIds.Count ?? 1)] : [];
}
public sealed record OffsetRegionOperation(
diff --git a/Aetheris.Surfacing/SurfaceIntersectionIr.cs b/Aetheris.Surfacing/SurfaceIntersectionIr.cs
new file mode 100644
index 00000000..f5a617c1
--- /dev/null
+++ b/Aetheris.Surfacing/SurfaceIntersectionIr.cs
@@ -0,0 +1,220 @@
+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.Judgment;
+using Aetheris.Kernel.Core.Math;
+
+namespace Aetheris.Surfacing;
+
+public enum SurfaceIntersectionClassification
+{
+ NoIntersection,
+ SingleCurve,
+ MultipleCurves,
+ TangentContact,
+ CoincidentRegion,
+ Ambiguous,
+ NumericalFailure,
+ Unsupported
+}
+
+public sealed record SurfaceIntersectionToleranceEvidence(
+ double IntersectionTolerance,
+ double PcurveTolerance,
+ double MaximumResidual,
+ int Samples,
+ string Method);
+
+public sealed record SurfaceIntersectionBranch(
+ string StableId,
+ CurveGeometry Curve3D,
+ ParameterInterval CurveDomain,
+ PcurveGeometry PcurveOnA,
+ PcurveGeometry PcurveOnB,
+ bool OrientationOnA,
+ bool OrientationOnB,
+ SurfaceIntersectionToleranceEvidence Evidence);
+
+public sealed record SurfaceIntersectionResult(
+ string SupportA,
+ string SupportB,
+ SurfaceIntersectionClassification Classification,
+ IReadOnlyList<SurfaceIntersectionBranch> Branches,
+ string? SelectedBranch,
+ IReadOnlyList<string> Diagnostics)
+{
+ public bool IsSuccess => Classification is SurfaceIntersectionClassification.SingleCurve or SurfaceIntersectionClassification.MultipleCurves
+ && Branches.Count > 0;
+}
+
+public sealed record SurfaceIntersectionRequest(
+ string SupportA,
+ SurfaceGeometry SurfaceA,
+ SurfaceParameterDomain DomainA,
+ string SupportB,
+ SurfaceGeometry SurfaceB,
+ SurfaceParameterDomain DomainB,
+ double IntersectionTolerance = 1e-7,
+ double PcurveTolerance = 1e-6,
+ SurfaceParameterPoint? SeedOnA = null);
+
+/// <summary>
+/// Bounded, explicitly qualified surface-intersection facade. It retains exact curves for the
+/// analytic and isoparametric cases it claims and rejects all other combinations by classification.
+/// </summary>
+public static class BoundedSurfaceIntersector
+{
+ public static SurfaceIntersectionResult Intersect(SurfaceIntersectionRequest request)
+ {
+ ArgumentNullException.ThrowIfNull(request);
+ if (!request.DomainA.IsValid || !request.DomainB.IsValid || request.IntersectionTolerance <= 0d || request.PcurveTolerance <= 0d)
+ return Failure(request, SurfaceIntersectionClassification.NumericalFailure, "surf-intersection-domain-invalid");
+
+ if (request.SurfaceA.Plane is { } parallelA && request.SurfaceB.Plane is { } parallelB
+ && parallelA.Normal.ToVector().Cross(parallelB.Normal.ToVector()).Length <= request.IntersectionTolerance)
+ {
+ var separation = double.Abs((parallelB.Origin - parallelA.Origin).Dot(parallelA.Normal.ToVector()));
+ return Failure(request, separation <= request.IntersectionTolerance
+ ? SurfaceIntersectionClassification.CoincidentRegion : SurfaceIntersectionClassification.NoIntersection,
+ separation <= request.IntersectionTolerance ? "surf-intersection-coincident-region" : "surf-intersection-none");
+ }
+
+ var branches = (request.SurfaceA.Kind, request.SurfaceB.Kind) switch
+ {
+ (SurfaceGeometryKind.Plane, SurfaceGeometryKind.Plane) => PlanePlane(request),
+ (SurfaceGeometryKind.Plane, SurfaceGeometryKind.Cylinder) => PlaneCylinder(request, false),
+ (SurfaceGeometryKind.Cylinder, SurfaceGeometryKind.Plane) => PlaneCylinder(Swap(request), true),
+ (SurfaceGeometryKind.Plane, SurfaceGeometryKind.BSplineSurfaceWithKnots) => PlaneSpline(request, false),
+ (SurfaceGeometryKind.BSplineSurfaceWithKnots, SurfaceGeometryKind.Plane) => PlaneSpline(Swap(request), true),
+ _ => null
+ };
+ if (branches is null) return Failure(request, SurfaceIntersectionClassification.Unsupported, "surf-intersection-class-unsupported");
+ if (branches.Count == 0) return Failure(request, SurfaceIntersectionClassification.NoIntersection, "surf-intersection-none");
+
+ branches = branches.OrderBy(branch => branch.StableId, StringComparer.Ordinal).ToArray();
+ var selected = SelectBranch(branches, request.SeedOnA);
+ return new(request.SupportA, request.SupportB,
+ branches.Count == 1 ? SurfaceIntersectionClassification.SingleCurve : SurfaceIntersectionClassification.MultipleCurves,
+ branches, selected, selected is null ? ["surf-intersection-ambiguous"] : ["surf-intersection-qualified", "surf-branch-selected-by-judgment"]);
+ }
+
+ private static IReadOnlyList<SurfaceIntersectionBranch>? PlanePlane(SurfaceIntersectionRequest request)
+ {
+ var a = request.SurfaceA.Plane!.Value;
+ var b = request.SurfaceB.Plane!.Value;
+ var na = a.Normal.ToVector();
+ var nb = b.Normal.ToVector();
+ var direction = na.Cross(nb);
+ if (direction.Length <= request.IntersectionTolerance)
+ {
+ var separation = double.Abs((b.Origin - a.Origin).Dot(na));
+ return separation <= request.IntersectionTolerance ? null : [];
+ }
+ var ca = na.Dot(a.Origin - Point3D.Origin);
+ var cb = nb.Dot(b.Origin - Point3D.Origin);
+ var pointVector = ((nb.Cross(direction) * ca) + (direction.Cross(na) * cb)) / direction.LengthSquared;
+ var origin = Point3D.Origin + pointVector;
+ var dir = Direction3D.Create(direction);
+ var interval = new ParameterInterval(-DomainScale(request.DomainA), DomainScale(request.DomainA));
+ var start = origin + (dir.ToVector() * interval.Start);
+ var end = origin + (dir.ToVector() * interval.End);
+ var pa = PcurveGeometry.Line(interval, PlaneUv(a, start), PlaneUv(a, end));
+ var pb = PcurveGeometry.Line(interval, PlaneUv(b, start), PlaneUv(b, end));
+ return [Branch(request, "line", CurveGeometry.FromLine(new Line3Curve(origin, dir)), interval, pa, pb)];
+ }
+
+ private static IReadOnlyList<SurfaceIntersectionBranch>? PlaneCylinder(SurfaceIntersectionRequest request, bool reverseOutput)
+ {
+ var plane = request.SurfaceA.Plane!.Value;
+ var cylinder = request.SurfaceB.Cylinder!.Value;
+ var alignment = double.Abs(plane.Normal.ToVector().Dot(cylinder.Axis.ToVector()));
+ if (alignment < 1d - request.IntersectionTolerance) return null;
+ var axial = (plane.Origin - cylinder.Origin).Dot(cylinder.Axis.ToVector()) / plane.Normal.ToVector().Dot(cylinder.Axis.ToVector());
+ if (axial < request.DomainB.VMin - request.IntersectionTolerance || axial > request.DomainB.VMax + request.IntersectionTolerance) return [];
+ var center = cylinder.Origin + (cylinder.Axis.ToVector() * axial);
+ var interval = new ParameterInterval(request.DomainB.UMin, request.DomainB.UMax);
+ var circle = CurveGeometry.FromCircle(new Circle3Curve(center, cylinder.Axis, cylinder.Radius, cylinder.XAxis));
+ var onPlane = PcurveGeometry.Circle(interval, PlaneUv(plane, center), cylinder.Radius, cylinder.Radius);
+ var onCylinder = PcurveGeometry.Line(interval, new(interval.Start, axial), new(interval.End, axial));
+ var branch = reverseOutput
+ ? Branch(request, "circle", circle, interval, onCylinder, onPlane)
+ : Branch(request, "circle", circle, interval, onPlane, onCylinder);
+ return [branch];
+ }
+
+ private static IReadOnlyList<SurfaceIntersectionBranch>? PlaneSpline(SurfaceIntersectionRequest request, bool reverseOutput)
+ {
+ var plane = request.SurfaceA.Plane!.Value;
+ var spline = request.SurfaceB.BSplineSurfaceWithKnots!;
+ var branches = new List<SurfaceIntersectionBranch>();
+ foreach (var uIndex in new[] { 0, spline.ControlPoints.Count - 1 }.Distinct())
+ {
+ var row = spline.ControlPoints[uIndex];
+ if (!row.All(point => OnPlane(plane, point, request.IntersectionTolerance))) continue;
+ var u = Greville(spline.FullKnotsU, spline.DegreeU, uIndex);
+ if (u < request.DomainB.UMin - request.IntersectionTolerance || u > request.DomainB.UMax + request.IntersectionTolerance) continue;
+ var curve = new BSpline3Curve(spline.DegreeV, row, spline.KnotMultiplicitiesV, spline.KnotValuesV, "UNSPECIFIED", spline.VClosed, false, spline.KnotSpec);
+ var interval = new ParameterInterval(request.DomainB.VMin, request.DomainB.VMax);
+ var onSpline = PcurveGeometry.Line(interval, new(u, interval.Start), new(u, interval.End));
+ var onPlane = PcurveGeometry.Polyline(interval, Sample(interval, 65, t => PlaneUv(plane, curve.Evaluate(t))));
+ branches.Add(reverseOutput
+ ? Branch(request, $"iso-u-{u:R}", CurveGeometry.FromBSpline(curve), interval, onSpline, onPlane)
+ : Branch(request, $"iso-u-{u:R}", CurveGeometry.FromBSpline(curve), interval, onPlane, onSpline));
+ }
+ foreach (var vIndex in new[] { 0, spline.ControlPoints[0].Count - 1 }.Distinct())
+ {
+ var column = spline.ControlPoints.Select(row => row[vIndex]).ToArray();
+ if (!column.All(point => OnPlane(plane, point, request.IntersectionTolerance))) continue;
+ var v = Greville(spline.FullKnotsV, spline.DegreeV, vIndex);
+ if (v < request.DomainB.VMin - request.IntersectionTolerance || v > request.DomainB.VMax + request.IntersectionTolerance) continue;
+ var curve = new BSpline3Curve(spline.DegreeU, column, spline.KnotMultiplicitiesU, spline.KnotValuesU, "UNSPECIFIED", spline.UClosed, false, spline.KnotSpec);
+ var interval = new ParameterInterval(request.DomainB.UMin, request.DomainB.UMax);
+ var onSpline = PcurveGeometry.Line(interval, new(interval.Start, v), new(interval.End, v));
+ var onPlane = PcurveGeometry.Polyline(interval, Sample(interval, 65, t => PlaneUv(plane, curve.Evaluate(t))));
+ branches.Add(reverseOutput
+ ? Branch(request, $"iso-v-{v:R}", CurveGeometry.FromBSpline(curve), interval, onSpline, onPlane)
+ : Branch(request, $"iso-v-{v:R}", CurveGeometry.FromBSpline(curve), interval, onPlane, onSpline));
+ }
+ return branches.GroupBy(branch => branch.StableId, StringComparer.Ordinal).Select(group => group.First()).ToArray();
+ }
+
+ private static string? SelectBranch(IReadOnlyList<SurfaceIntersectionBranch> branches, SurfaceParameterPoint? seed)
+ {
+ if (branches.Count == 1) return branches[0].StableId;
+ var context = new BranchSelectionContext(branches, seed);
+ var candidates = branches.Select((branch, index) => new JudgmentCandidate<BranchSelectionContext>(branch.StableId,
+ _ => seed.HasValue,
+ c => -DistanceSquared(branch.PcurveOnA.Evaluate(Mid(branch.CurveDomain)), c.Seed!.Value),
+ _ => "Multiple branches require a seed/reference boundary.", index)).ToArray();
+ var result = new JudgmentEngine<BranchSelectionContext>().Evaluate(context, candidates);
+ return result.IsSuccess ? result.Selection!.Value.Candidate.Name : null;
+ }
+
+ private static SurfaceIntersectionBranch Branch(SurfaceIntersectionRequest request, string suffix, CurveGeometry curve,
+ ParameterInterval interval, PcurveGeometry a, PcurveGeometry b)
+ => new($"{request.SupportA}|{request.SupportB}|{suffix}", curve, interval, a, b, true, true,
+ new(request.IntersectionTolerance, request.PcurveTolerance, 0d, 65, "exact-qualified"));
+
+ private static SurfaceIntersectionRequest Swap(SurfaceIntersectionRequest r)
+ => new(r.SupportB, r.SurfaceB, r.DomainB, r.SupportA, r.SurfaceA, r.DomainA, r.IntersectionTolerance, r.PcurveTolerance, r.SeedOnA);
+ private static SurfaceIntersectionResult Failure(SurfaceIntersectionRequest r, SurfaceIntersectionClassification c, string d)
+ => new(r.SupportA, r.SupportB, c, [], null, [d]);
+ private static bool OnPlane(PlaneSurface plane, Point3D point, double tolerance)
+ => double.Abs((point - plane.Origin).Dot(plane.Normal.ToVector())) <= tolerance;
+ private static SurfaceParameterPoint PlaneUv(PlaneSurface plane, Point3D point)
+ {
+ var delta = point - plane.Origin;
+ return new(delta.Dot(plane.UAxis.ToVector()), delta.Dot(plane.VAxis.ToVector()));
+ }
+ private static double Greville(IReadOnlyList<double> knots, int degree, int index)
+ => Enumerable.Range(1, degree).Average(offset => knots[index + offset]);
+ private static double DomainScale(SurfaceParameterDomain domain)
+ => double.Max(domain.UMax - domain.UMin, domain.VMax - domain.VMin);
+ private static double Mid(ParameterInterval interval) => (interval.Start + interval.End) * .5d;
+ private static double DistanceSquared(SurfaceParameterPoint a, SurfaceParameterPoint b)
+ => ((a.U - b.U) * (a.U - b.U)) + ((a.V - b.V) * (a.V - b.V));
+ private static IReadOnlyList<SurfaceParameterPoint> Sample(ParameterInterval interval, int count, Func<double, SurfaceParameterPoint> evaluator)
+ => Enumerable.Range(0, count).Select(i => evaluator(interval.Start + ((interval.End - interval.Start) * i / (count - 1d)))).ToArray();
+ private sealed record BranchSelectionContext(IReadOnlyList<SurfaceIntersectionBranch> Branches, SurfaceParameterPoint? Seed);
+}
diff --git a/Aetheris.Surfacing/SurfacePatchIr.cs b/Aetheris.Surfacing/SurfacePatchIr.cs
index f7fefd54..a2af12e0 100644
--- a/Aetheris.Surfacing/SurfacePatchIr.cs
+++ b/Aetheris.Surfacing/SurfacePatchIr.cs
@@ -123,13 +123,87 @@ public sealed record SurfacePatchMetadata(
IReadOnlyList<PatchBoundaryCorrespondence> ContinuityContracts,
string ExportClass)
{
- public static SurfacePatchMetadata From(BoundedSurfacePatch patch) => new(
+ public static SurfacePatchMetadata From(BoundedSurfacePatch patch, int boundaryLoops = 1) => new(
patch.PatchId, patch.SurfaceClass, patch.DegreeU, patch.DegreeV, patch.ControlCountU, patch.ControlCountV,
- patch.ParameterDomain, 1, patch.BoundaryLoop.Boundaries, patch.ExportClass);
+ patch.ParameterDomain, boundaryLoops, patch.BoundaryLoop.Boundaries, patch.ExportClass);
}
public sealed record TrimRegionResult(bool IsSuccess, BoundedSurfacePatch? Patch, IReadOnlyList<SculptDiagnostic> Diagnostics);
+public enum SurfaceExtensionMethod { AnalyticIdentity, EndpointTangentContinuation }
+
+public sealed record ExtendedSurfaceSupport(
+ SurfaceGeometry OriginalSupport,
+ SurfaceParameterDomain OriginalDomain,
+ SurfaceParameterDomain ExtendedDomain,
+ SurfaceExtensionMethod Method,
+ string ContinuityAtOriginalBoundary,
+ Func<double, double, Point3D> Evaluator)
+{
+ public Point3D Evaluate(double u, double v)
+ {
+ if (u < ExtendedDomain.UMin || u > ExtendedDomain.UMax || v < ExtendedDomain.VMin || v > ExtendedDomain.VMax)
+ throw new ArgumentOutOfRangeException(nameof(u), "Evaluation is outside the authorized extension domain.");
+ return Evaluator(u, v);
+ }
+}
+
+public sealed record SurfaceExtensionResult(bool IsSuccess, ExtendedSurfaceSupport? Support, IReadOnlyList<SculptDiagnostic> Diagnostics);
+
+public static class SurfaceSupportExtension
+{
+ public static SurfaceExtensionResult Extend(SurfaceGeometry support, SurfaceParameterDomain original, SurfaceParameterDomain requested,
+ double maximumRelativeExtension = .25d)
+ {
+ if (!original.IsValid || !requested.IsValid || requested.UMin > original.UMin || requested.UMax < original.UMax
+ || requested.VMin > original.VMin || requested.VMax < original.VMax)
+ return Failure("surf-extension-domain-invalid", "The requested domain must finitely contain the original domain.");
+ var uSpan = original.UMax - original.UMin;
+ var vSpan = original.VMax - original.VMin;
+ if (original.UMin - requested.UMin > uSpan * maximumRelativeExtension
+ || requested.UMax - original.UMax > uSpan * maximumRelativeExtension
+ || original.VMin - requested.VMin > vSpan * maximumRelativeExtension
+ || requested.VMax - original.VMax > vSpan * maximumRelativeExtension)
+ return Failure("surf-extension-unsupported", $"Extension exceeds the bounded {maximumRelativeExtension:P0} per-side stability envelope.");
+
+ if (support.Kind is SurfaceGeometryKind.Plane or SurfaceGeometryKind.Cylinder or SurfaceGeometryKind.Cone)
+ {
+ Point3D EvaluateAnalytic(double u, double v) => support.Kind switch
+ {
+ SurfaceGeometryKind.Plane => support.Plane!.Value.Evaluate(u, v),
+ SurfaceGeometryKind.Cylinder => support.Cylinder!.Value.Evaluate(u, v),
+ SurfaceGeometryKind.Cone => support.Cone!.Value.Evaluate(u, v),
+ _ => throw new InvalidOperationException()
+ };
+ return new(true, new(support, original, requested, SurfaceExtensionMethod.AnalyticIdentity, "Exact analytic continuation", EvaluateAnalytic), []);
+ }
+ if (support.BSplineSurfaceWithKnots is not { } spline)
+ return Failure("surf-extension-unsupported", $"Surface family {support.Kind} is not in the bounded extension matrix.");
+ if (spline.DegreeU > 3 || spline.DegreeV > 3 || spline.SelfIntersect)
+ return Failure("surf-extension-unsupported", "Endpoint-tangent continuation is limited to non-self-intersecting degree <= 3 B-spline supports.");
+
+ Point3D EvaluateSpline(double u, double v)
+ {
+ var uc = System.Math.Clamp(u, original.UMin, original.UMax);
+ var vc = System.Math.Clamp(v, original.VMin, original.VMax);
+ var basePoint = spline.Evaluate(uc, vc);
+ var hu = double.Max(uSpan * 1e-4d, 1e-7d);
+ var hv = double.Max(vSpan * 1e-4d, 1e-7d);
+ var u0 = System.Math.Clamp(uc - hu, original.UMin, original.UMax);
+ var u1 = System.Math.Clamp(uc + hu, original.UMin, original.UMax);
+ var v0 = System.Math.Clamp(vc - hv, original.VMin, original.VMax);
+ var v1 = System.Math.Clamp(vc + hv, original.VMin, original.VMax);
+ var du = (spline.Evaluate(u1, vc) - spline.Evaluate(u0, vc)) / (u1 - u0);
+ var dv = (spline.Evaluate(uc, v1) - spline.Evaluate(uc, v0)) / (v1 - v0);
+ return basePoint + (du * (u - uc)) + (dv * (v - vc));
+ }
+ return new(true, new(support, original, requested, SurfaceExtensionMethod.EndpointTangentContinuation,
+ "C1 by endpoint first-derivative continuation; mixed outside-corner term intentionally zero", EvaluateSpline), []);
+ }
+
+ private static SurfaceExtensionResult Failure(string code, string message) => new(false, null, [new(code, message)]);
+}
+
public static class SurfacePatchOperations
{
public static TrimRegionResult TrimRegion(BSplineSurfacePatch patch, SurfaceParameterDomain domain)
diff --git a/Aetheris.Surfacing/SurfacingModule.cs b/Aetheris.Surfacing/SurfacingModule.cs
index fbec3286..28618134 100644
--- a/Aetheris.Surfacing/SurfacingModule.cs
+++ b/Aetheris.Surfacing/SurfacingModule.cs
@@ -22,7 +22,7 @@ public static class SurfacingModule
new(SectionSurfaceCapability,Id,Version,"Ordered-section surface with explicit non-rational materialization evidence."),
new(BoundaryPatchCapability,Id,Version,"Four-boundary G0 patch preserving boundary intent."),
new(PanelCapability,Id,Version,"Bounded oriented engineering surface with ordered semantic boundary edges and developability evidence."),
- new(BoundedSculptingCapability,Id,Version,"Immutable single-predecessor BodyState derivation with bounded OffsetRegion and rectangular ReplaceRegion authority, mixed G0/G1 patch contracts, preservation, and inspectable GeometricDelta evidence.")],
+ new(BoundedSculptingCapability,Id,Version,"Immutable single-predecessor BodyState derivation with bounded OffsetRegion and trimmed ReplaceRegion authority, qualified intersection-derived boundaries, face-local pcurves, inner openings, imported-face grafting, mixed G0/G1 contracts, persistent associations, and inspectable GeometricDelta evidence.")],
["Surfacing.PanelConcept", "Surfacing.SurfacePatchConcept"], ["Surfacing.RuledCanopyPanel","Surfacing.HyperbolicParaboloid","Surfacing.ParabolicCylinder","Surfacing.EllipticParaboloid","Surfacing.Helicoid"],
["Surface construction -> PanelIR -> semantic edges", "Panel edge Interface/Mate -> deterministic G0 evidence", "PanelIR -> bounded BRep-backed STEP export envelope"],
["panel-incomplete-boundary", "panel-boundary-orientation-inconsistent","panel-mate-endpoint-mismatch","panel-mate-g0-failure","panel-mate-g1-failure","panel-mate-g1-unknown","panel-mate-g2-failure","panel-mate-g2-unknown","surfacing-panel-thickness-invalid","sculpt-outside-authorized-region","sculpt-preservation-failed","sculpt-self-intersection","surf-boundary-g0-violation","surf-boundary-g1-violation","surf-selector-target-replaced","surf-surface-export-normalization-failed"],
diff --git a/docs/public/firmament/sculpting.md b/docs/public/firmament/sculpting.md
index 68ef9096..21788537 100644
--- a/docs/public/firmament/sculpting.md
+++ b/docs/public/firmament/sculpting.md
@@ -1,6 +1,6 @@
# Bounded mathematical sculpting and patch replacement
-SURF-X0 supports bounded mathematical sculpting and locality-preserving region modification. SURF-X1 adds one deliberately narrow freeform lane: replace the rectangular center of the admitted housing top with a bounded tensor-product patch. This is not full general surfacing.
+SURF-X0 supports bounded mathematical sculpting and locality-preserving region modification. SURF-X1 adds direct rectangular patch replacement. SURF-X1a closes the trim path for the admitted housing: qualified surface intersections derive the outer boundary, face-local pcurves qualify every trim, circular inner loops preserve openings, and an imported `ADVANCED_FACE` can receive a bounded support-surface graft. This is not full general surfacing.
Sculpting is a lower-authority escape hatch for geometry that an engineering feature such as `Boss`, `Pocket`, `Hole`, `Sweep`, `Fillet`, or `Chamfer` cannot express. Prefer those features whenever they carry the intended engineering meaning.
@@ -82,7 +82,43 @@ The public patch carries degree, rectangular control net, expanded nondecreasing
G0 compares 33 deterministic samples to the exact preserved boundary line. G1 additionally compares patch tangent planes to the planar frame and reports the maximum angular error. The flagship requires G1 on east/west and G0 on north/south. Accepted patch edges and vertices are shared BRep topology, not merely nearby geometry.
-`TrimRegion` currently restricts a non-rational patch to a subdomain already present in its knot support. `ExtendRegion` can restore or enlarge that bounded domain only inside the same support. Arbitrary extrapolation, surface-surface intersection trimming, holes in patch loops, and coincident/tangent-support classification are not yet public capabilities.
+## X1a trim closure
+
+The canonical trimmed witness is [`surf-x1a-trimmed-freeform-housing.firmament`](../../../fixtures/Canonical/Sculpting/surf-x1a-trimmed-freeform-housing.firmament). Its non-rational patch spans the full top, owns one outer loop and four circular inner loops, and leaves the four cylindrical hole walls as preserved neighbors. The outer spline edges come from four qualified Plane/non-rational-B-spline boundary intersections rather than four unrelated duplicate curves.
+
+A pcurve is the same trim edge expressed in one face's `(u,v)` coordinates. It is essential because a 3D curve alone does not say how it bounds a parameterized surface. A shared edge therefore has one topological edge and one 3D curve, but two face-local pcurves—one on each adjacent support. Aetheris independently samples `Surface(pcurve(t))` against `Curve3D(t)`, checks parameter domains and orientation, and blocks export with `surf-pcurve-invalid` on disagreement. AP242 export uses `SURFACE_CURVE` and `PCURVE`, not metadata-only trim hints.
+
+The qualified intersection matrix is intentionally narrow:
+
+| Pair | Qualified result |
+|---|---|
+| Plane / Plane | Exact line for transverse planes; explicit no-intersection and coincident-region classification |
+| Plane / Cylinder | Exact circle when the plane is normal to the cylinder axis |
+| Plane / non-rational B-spline | Exact clamped boundary isoparametric B-spline curve |
+| Cylinder / non-rational B-spline | Pcurve generation is qualified for an existing shared circle; general intersection discovery is deferred |
+| non-rational B-spline / non-rational B-spline | Deferred |
+
+Multiple branches require a seed/reference boundary. Admissibility, score, and tie-breaking go through deterministic utility scoring; an unseeded ambiguous result fails instead of selecting the kernel's first curve.
+
+`TrimRegion` restricts an existing non-rational support. Bounded support extension distinguishes exact analytic continuation for Plane/Cylinder/Cone from degree-3-or-lower endpoint-tangent continuation for a non-self-intersecting non-rational B-spline. Extension is limited to 25% of the original span per side, reports the old/new domain and boundary continuity law, and does not enlarge the final solid outside the authorized trim. Larger or unstable requests fail with `surf-extension-unsupported`.
+
+The advanced imported route first imports a STEP body, selects exactly one `FaceGeometryBinding.SourceStepEntityId`, and grafts the new support onto that current face. It retains the imported topology object, vertices, edge curves, neighboring face bindings, and neighboring source entity IDs. The graft then rebuilds and validates pcurves. This is a bounded `ADVANCED_FACE` route, not arbitrary dumb-solid editing or reconstruction into native primitives.
+
+Imported rational surfaces follow the strict normalized re-export policy: Aetheris does not pass foreign rational product surfaces through a newly authoritative STEP merely because they were untouched. They must first normalize to an exact analytic or supported non-rational representation; otherwise import/materialization or export blocks explicitly. Newly authored replacement geometry is always subject to the same no-rational-product boundary. The canonical X1a import/replacement witness contains zero rational surfaces before and after replacement.
+
+The advanced API sequence is:
+
+```csharp
+var imported = Step242Importer.ImportBody(stepText).Value;
+var adopted = ImportedFaceRegionReplacer.AdoptImportedBody(baseState, imported, "ImportedBaseStep");
+var result = ImportedFaceRegionReplacer.Apply(adopted, sourceAdvancedFaceId, patch, "ImportedTrimmedCrown");
+```
+
+`sourceAdvancedFaceId` must resolve to exactly one current imported face. Reusing it after replacement fails with `surf-selector-target-replaced`, even though the original STEP entity ID remains on the successor binding as inspectable provenance.
+
+The X1a `BodyState` also carries explicit `PersistentGeometryAssociation` entries. The bottom datum, hole-diameter/position PMI, and `BottomMountingInterface` bind to current face IDs. STEP export emits AP242 `GEOMETRIC_ITEM_SPECIFIC_USAGE`; `Step242SemanticPmiInspector` must recover non-empty face associations. Only `Preserved` or explicit `ReplacedBy` correspondence may rebind an association—name matching and nearest-face search are prohibited.
+
+For the canonical artifact, `aetheris analyze result.step --json` reports these associations under `semanticPmi.items[*].geometricFaceEntityIds`. Datum A and the assembly-interface annotation each bind to the bottom face; diameter and position items each bind to all four cylindrical faces. The replacement B-spline face has five loops (one outer plus four inner). The complete body emits 24 `SURFACE_CURVE` and 48 `PCURVE` entities because all 24 shared edges carry two face-local pcurves; the eight crown trim edges account for 16 of those pcurves.
An ordinary safe cylindrical `HoleFeature` can follow replacement on a surviving current-state region. Selectors are resolved against the immediate predecessor. A selector for removed `HousingCrown` fails with `surf-selector-target-replaced` and names `CrownPatch` and the replacing state.
@@ -115,6 +151,4 @@ The X0 housing emits only `PLANE` and `CYLINDRICAL_SURFACE`. The X1 flagship add
## Current limits
-The admitted X1 materializer is limited to a single rectangular outer loop in the center of the canonical planar housing top. It does not provide general imported-face replacement, inner patch loops, arbitrary intersection/trim solving, general surface extension, G2, Blend, Loft, Shell, Draft, fitting, fairness optimization, or arbitrary patch networks. Analytic surface objects exist in the patch IR but direct Firmament patch authoring currently admits the non-rational B-spline form only.
-
-The named mounting interface and per-hole semantic identities survive the operation. Authored AP242 PMI and Assembly Interface association round-trip through this sculpting lane is not yet implemented and is not claimed.
+The admitted X1a materializer is limited to rectangular housing-top replacement, four qualified boundary intersections, and circular inner openings whose existing 3D edges lie on the replacement support. It does not provide arbitrary intersection networks, general Cylinder/B-spline or B-spline/B-spline discovery, arbitrary nested islands, G2, Blend, Loft, Shell, Draft, fitting, fairness optimization, or arbitrary patch networks. Direct Firmament patch authoring admits the non-rational B-spline form only; imported replacement is an advanced API path over an already imported BRep.
diff --git a/docs/public/reference/diagnostics.md b/docs/public/reference/diagnostics.md
index 9cc30983..4f1db927 100644
--- a/docs/public/reference/diagnostics.md
+++ b/docs/public/reference/diagnostics.md
@@ -10,6 +10,19 @@
- `firmament-sweep-self-intersection`: nonadjacent centerline regions violate required clearance.
- `firmament-sweep-material-unresolved`: the material identity is absent from the deployed catalog.
+## Surface trim closure (SURF-X1a)
+
+- `surf-intersection-none`: the qualified supports do not intersect inside the bounded domains.
+- `surf-intersection-ambiguous`: multiple branches exist without an admissible seed/reference boundary.
+- `surf-pcurve-invalid`: a face-local UV curve is missing, outside its domain, misoriented, or reconstructs away from the shared 3D edge.
+- `surf-trim-loop-open`: ordered trim coedges do not close through shared topology vertices.
+- `surf-inner-loop-invalid`: an opening loop is not a valid bounded hole in the replacement face.
+- `surf-extension-unsupported`: the surface family, degree, stability envelope, or requested extension is outside the qualified matrix.
+- `surf-imported-selector-unresolved`: a STEP `ADVANCED_FACE` identity does not resolve to exactly one current face.
+- `surf-association-target-removed`: PMI or an Assembly Interface has no explicit `Preserved` correspondence; Aetheris refuses name- or proximity-based rebinding.
+- `surf-association-current-geometry-missing`: an explicitly preserved association references a face absent from the output `BodyState`.
+- `surf-selector-target-replaced`: a historical native or imported selector has an explicit successor and cannot be reused.
+
Start with `aetheris validate source.firmament --json`; use `build` when geometry, AP242, assertions, or artifacts are involved. A diagnostic code is the stable automation key, while its message identifies the value/target and expected category where useful.
Common recovery patterns:
diff --git a/docs/public/reference/supported-features.md b/docs/public/reference/supported-features.md
index 45628352..4d4e8d21 100644
--- a/docs/public/reference/supported-features.md
+++ b/docs/public/reference/supported-features.md
@@ -5,7 +5,7 @@
| Area | Status | Preview 3 boundary |
|---|---|---|
| Firmament V2 native primitives/profiles | Bounded | Named Box/Cylinder/Frustum/RoundedBox and admitted line/arc profile construction/composition |
-| Bounded mathematical sculpting | Bounded (SURF-X1 subset) | Immutable single-predecessor `BodyState`; rectangular-housing `OffsetRegion`; and one-loop rectangular `ReplaceRegion` using a direct non-rational B-spline patch, mixed G0/G1 contracts, exact lower-body locality, current-state downstream holes, and rational-free STEP. General trim/intersection surfacing and AP242 PMI/interface persistence remain unsupported. See the [sculpting guide](../firmament/sculpting.md). |
+| Bounded mathematical sculpting | Bounded (SURF-X1a subset) | Immutable single-predecessor `BodyState`; rectangular-housing `OffsetRegion`; direct or imported-face `ReplaceRegion`; qualified Plane/Plane, normal Plane/Cylinder, and Plane/non-rational-B-spline boundary intersections; face-local pcurves; circular inner loops; bounded support extension; exact lower-body locality; AP242 PMI/interface geometry associations; and rational-free STEP. General surface networks remain unsupported. See the [sculpting guide](../firmament/sculpting.md). |
| Firmament V2 analytic primitives | Bounded | Direct named Sphere, Cone (including zero-radius pointed end), and Torus routes round-trip through AP242; legacy `solid` declarations remain compatibility inputs, not canonical authoring |
| Circular Sweep | Bounded (X0) | Open planar XY Concept Path, tangent line/arc segments, constant circular diameter, analytic cylinder/torus faces, capped solid; no general 3D/variable/rail/twist sweep |
| 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). |
@@ -29,7 +29,7 @@
| Platform qualification | Supported | Windows x64 bundle; NativeAOT Forge Host on `win-x64` |
| Linux/macOS release binaries | Not in Preview 3 | Framework logic tests do not constitute binary qualification |
| Post-Preview-3 feature families | X0 exception | Circular Sweep and Standard Products Paperclip are the bounded X0 additions; other new geometry/PMI/FEA/Forge families remain frozen |
-| General loft, helix, and freeform surface features | Not in Preview 3 | The bounded SURF-X1 rectangular `ReplaceRegion` exception is not a general Loft, surface network, or imported-face editing route. |
+| General loft, helix, and freeform surface features | Not in Preview 3 | The bounded SURF-X1a housing `ReplaceRegion` and imported `ADVANCED_FACE` graft are not a general Loft, arbitrary dumb-solid editor, or surface-network route. |
| Through profile removal | Bounded semantic operations | Use qualified `Hole`, `Slot`, or another documented opening feature; Pocket never means through-all |
| Arbitrary solid Boolean subtraction / hemispherical cavity | Not in Preview 3 | No public `Union`, `Subtract`, `Intersect`, CSG tree, Sphere-from-Block subtraction, or hemisphere special case |
diff --git a/docs/release/SURF-X1A-TRIM-INTERSECTION-CLOSURE.md b/docs/release/SURF-X1A-TRIM-INTERSECTION-CLOSURE.md
new file mode 100644
index 00000000..58fb95fb
--- /dev/null
+++ b/docs/release/SURF-X1A-TRIM-INTERSECTION-CLOSURE.md
@@ -0,0 +1,98 @@
+# SURF-X1a trim/intersection closure
+
+## Executive verdict
+
+**Accepted** for the explicitly bounded SURF-X1a housing class. SURF-X1 is no longer blocked on trim topology, pcurves, circular inner loops, bounded extension, imported-face support replacement, or AP242 geometry-association persistence. General surface networks remain deferred.
+
+## Intersection capability matrix
+
+| Surface A | Surface B | Status | Curve class | Notes |
+|---|---|---|---|---|
+| Plane | Plane | Qualified | exact line | Transverse line; parallel no-intersection and coincident-region classifications are distinct. |
+| Plane | Cylinder | Qualified subset | exact circle | Plane normal parallel to cylinder axis and bounded axial parameter. General oblique ellipse/two-line cases are not claimed. |
+| Plane | non-rational B-spline | Qualified subset | exact non-rational B-spline | Clamped boundary isoparametric intersections used by the flagship outer loop. |
+| Cylinder | non-rational B-spline | Qualified trim association | exact circle | Existing shared circular edge and both pcurves are qualified; general intersection discovery is deferred. |
+| non-rational B-spline | non-rational B-spline | Deferred | — | No arbitrary surface-network claim. |
+
+`SurfaceIntersectionResult` retains support identities, classification, 3D branches, two pcurves, orientation, tolerances, and diagnostics. Multiple-branch selection uses `JudgmentEngine`; an unseeded ambiguous set fails instead of choosing returned order.
+
+## Pcurve and topology evidence
+
+The flagship has 24 topological edges and 48 face-local pcurves: exactly two pcurves per shared edge. AP242 contains 24 `SURFACE_CURVE` and 48 `PCURVE` entities. `BrepPcurveValidator` independently checks domain, orientation, and off-grid sampled `Surface(UV(t))` versus `Curve3D(t)`; the measured maximum reconstruction deviation is `3.935614021344236e-6 mm` against `1e-5 mm`, with valid domains and consistent orientation. A deliberately corrupted pcurve fails while ordinary BRep preflight still passes, proving this is an independent gate.
+
+The replacement B-spline face has five loops: one outer loop and four single-circle inner loops. Each inner circle is one shared topological edge used by the crown and its preserved cylindrical hole wall. The whole body has 10 faces, 24 edges, 16 vertices, and every edge has incidence two.
+
+## Extension
+
+Plane, Cylinder, and Cone use exact analytic continuation. Non-self-intersecting non-rational B-splines of degree at most three use bounded endpoint first-derivative continuation, report the original/extended domains and C1 boundary law, and are limited to 25% of the original span per side. The extended support is an intersection aid; the final solid remains bounded by the trim and authorized spatial envelope. Unsupported or excessive requests fail with `surf-extension-unsupported`.
+
+## Imported replacement
+
+The regression exports the canonical base, reimports its real STEP BRep, selects the top through `FaceGeometryBinding.SourceStepEntityId`, and invokes `ImportedFaceRegionReplacer.Apply`. The result retains the exact imported `TopologyModel` object, vertices, edge curves, neighbor bindings, and neighboring STEP face provenance. Only the selected face's support binding is succeeded by the non-rational B-spline, after which all pcurves and BRep preflight are requalified. Reusing the historical imported selector fails with `surf-selector-target-replaced` and explicit successor provenance.
+
+## PMI and interface persistence
+
+Before and after replacement the state carries explicit current-face associations:
+
+| Semantic object | Before | After | AP242 reinspection |
+|---|---:|---:|---:|
+| Datum A / bottom interface | 1 face | 1 face | 1 associated `ADVANCED_FACE` |
+| Hole diameter, quantity 4 | 4 cylindrical faces | 4 cylindrical faces | 4 associated `ADVANCED_FACE` entities |
+| Hole-pattern position to A | 4 cylindrical faces | 4 cylindrical faces | 4 associated `ADVANCED_FACE` entities |
+| Bottom assembly interface | 1 face | 1 face | 1 associated `ADVANCED_FACE` |
+
+STEP uses `GEOMETRIC_ITEM_SPECIFIC_USAGE`; reinspection reports one datum, one diameter dimension, one position tolerance, one assembly-interface annotation, and non-empty `GeometricFaceEntityIds` for each. The qualified path carries associations only through explicit `Preserved` correspondence. A removed target, or a `ReplacedBy` target without an explicitly supported face successor, fails instead of invoking name/proximity matching; successor-target PMI remains deferred.
+
+## Product boundary and artifact
+
+Artifact: `artifacts/local/surf-x1a/surf-x1a-trimmed-freeform-housing.step`
+
+| Evidence | Value |
+|---|---:|
+| SHA-256 | `09348ca464547b7f9875074f9e2e4e3d32318e41c37bc46f9ca75bc0a938b052` |
+| Bytes | 2,464,434 |
+| Bodies / shells | 1 / 1 |
+| Faces / edges / vertices | 10 / 24 / 16 |
+| Bounds | `[-50,-40,0]` to `[50,40,27.14236111111111] mm` |
+| Planes / cylinders | 5 / 4 |
+| Non-rational B-spline surfaces | 1 |
+| Rational product surfaces | **0** |
+| STEP reimport | enclosed manifold |
+
+The four boundary G0 errors are at most `1.78e-14 mm`; G1 angular error is at most `0.000329°` against a `0.1°` limit. Independent locality below `z=20 mm` reports maximum deviation `0`.
+
+Imported rational surfaces use strict normalized re-export (Policy A): foreign rational supports are not passed through into a newly authoritative Aetheris STEP. They must normalize to an admitted analytic/non-rational form or the path blocks. The canonical source and result are rational-free.
+
+The recorded CLI build timings on the flagship machine were approximately 153 ms base preparation, 1.4 ms operation construction, 379 ms locality/preservation and trim realization, and 60 ms STEP export. Microphase timers for intersection, branch classification, pcurve inversion, loop construction, extension, grafting, and association remapping are not yet separately exposed in CLI JSON; their deterministic functional tests are qualified independently.
+
+## Fresh-agent tests
+
+Fresh documentation-only audits were rerun after the public guide, cookbook, coverage map, and diagnostic reference were updated:
+
+| Test | Result |
+|---|---|
+| A — imported top-face crown trimmed against neighbors | Pass (advanced imported-BRep API path) |
+| B — preserve four through-holes | Pass (canonical X1a Firmament witness) |
+| C — preserve hole PMI and bottom datum | Pass |
+| D — preserve bottom assembly interface | Pass |
+| E — reject stale replaced selector | Pass |
+| F — export and independently reinspect STEP | Pass |
+
+## Validation
+
+- Focused SURF-X0/X1/X1a module tests: 25 passed.
+- Focused STEP exporter/importer/semantic-PMI tests: 53 passed.
+- Full serial .NET suite: 3,135 passed, zero failed.
+- Canonical qualification: 94 fixtures passed.
+- Canonical X1a `validate`: valid, zero diagnostics.
+- CLI `build`: success; STEP plus sibling `GeometricDelta` JSON.
+- CLI `analyze`: 1 enclosed body, expected topology/surface inventory, complete semantic PMI associations.
+- Client: 82 tests plus typecheck, production build, and lint passed.
+- VS Code extension: 13 tests plus typecheck, build, and VSIX package passed.
+- Fresh self-contained win-x64 CLI: version and canonical validation passed.
+- Repository layout guard (3,719 tracked files), changed-document Markdown links, and `git diff --check`: passed.
+- NativeAOT Forge was not rerun because neither Forge nor its host/interop boundary changed.
+
+## Deferred work
+
+General G2 continuity, fairness optimization, general Blend, variable-radius transitions, Loft, Shell, Draft, arbitrary Cylinder/B-spline and B-spline/B-spline intersection discovery, nested islands, and global arbitrary surface networks remain outside SURF-X1a.
diff --git a/fixtures/Canonical/README.md b/fixtures/Canonical/README.md
index 6c6062ea..7bf6c9a2 100644
--- a/fixtures/Canonical/README.md
+++ b/fixtures/Canonical/README.md
@@ -26,6 +26,7 @@ Everything in this directory is current authoring guidance. Examples progress fr
| make Sheet Metal | `SheetMetal/l-bracket-with-hole.firmament` | material, bend, planar hole, formed/flat output |
| apply a bounded mathematical sculpt | `Sculpting/sculpted-housing.firmament` | immutable `BodyState`, `OffsetRegion`, locality, preservation contracts |
| replace a housing region with a freeform patch | `Sculpting/surf-x1-freeform-housing.firmament` | direct non-rational 6x6 B-spline patch, `ReplaceRegion`, explicit boundary correspondence, mixed G0/G1, downstream current-state hole |
+| trim a freeform replacement around preserved openings | `Sculpting/surf-x1a-trimmed-freeform-housing.firmament` | derived Plane/B-spline outer trims, four circular inner loops, face-local pcurves, PMI/interface associations, rational-free AP242 |
| make a data-driven Sheet Metal tab | `SheetMetal/profile-delta-tab-family.firmament` | Table, `with`, reusable `ProfileDelta Tab` |
| run FEA | `FEA/cantilever.firmament` | material, `Fixed`, `Force`, four result families |
| analyze imported STEP | `FEA/inline-step-cantilever.firmament` | repository-stable `inlineSTEP`, face selection, FEA |
diff --git a/fixtures/Canonical/Sculpting/surf-x1a-trimmed-freeform-housing.firmament b/fixtures/Canonical/Sculpting/surf-x1a-trimmed-freeform-housing.firmament
new file mode 100644
index 00000000..39a30fb3
--- /dev/null
+++ b/fixtures/Canonical/Sculpting/surf-x1a-trimmed-freeform-housing.firmament
@@ -0,0 +1,54 @@
++Model TrimmedFreeformControllerCover {
+ Units: mm
+
+ SurfacePatch CrownPatchX1a {
+ Degree: [3, 3]
+ Domain: [0, 1, 0, 1]
+ KnotsU: [0, 0, 0, 0, 0.2, 0.3, 0.4, 0.6, 0.7, 0.8, 1, 1, 1, 1]
+ KnotsV: [0, 0, 0, 0, 0.2, 0.4, 0.6, 0.8, 1, 1, 1, 1]
+ ControlRow: [[-50mm, -40mm, 20mm], [-50mm, -28mm, 20mm], [-50mm, -16mm, 20mm], [-50mm, -5mm, 20mm], [-50mm, 5mm, 20mm], [-50mm, 16mm, 20mm], [-50mm, 28mm, 20mm], [-50mm, 40mm, 20mm]]
+ ControlRow: [[-42mm, -40mm, 20mm], [-42mm, -28mm, 20mm], [-42mm, -16mm, 20mm], [-42mm, -5mm, 20mm], [-42mm, 5mm, 20mm], [-42mm, 16mm, 20mm], [-42mm, 28mm, 20mm], [-42mm, 40mm, 20mm]]
+ ControlRow: [[-32mm, -40mm, 20mm], [-32mm, -28mm, 20mm], [-32mm, -16mm, 20mm], [-32mm, -5mm, 20mm], [-32mm, 5mm, 20mm], [-32mm, 16mm, 20mm], [-32mm, 28mm, 20mm], [-32mm, 40mm, 20mm]]
+ ControlRow: [[-20mm, -40mm, 20mm], [-20mm, -28mm, 20mm], [-20mm, -16mm, 20mm], [-20mm, -5mm, 20mm], [-20mm, 5mm, 20mm], [-20mm, 16mm, 20mm], [-20mm, 28mm, 20mm], [-20mm, 40mm, 20mm]]
+ ControlRow: [[-7mm, -40mm, 20mm], [-7mm, -28mm, 20mm], [-7mm, -16mm, 23mm], [-7mm, -5mm, 28mm], [-7mm, 5mm, 28mm], [-7mm, 16mm, 23mm], [-7mm, 28mm, 20mm], [-7mm, 40mm, 20mm]]
+ ControlRow: [[7mm, -40mm, 20mm], [7mm, -28mm, 20mm], [7mm, -16mm, 23mm], [7mm, -5mm, 28mm], [7mm, 5mm, 28mm], [7mm, 16mm, 23mm], [7mm, 28mm, 20mm], [7mm, 40mm, 20mm]]
+ ControlRow: [[20mm, -40mm, 20mm], [20mm, -28mm, 20mm], [20mm, -16mm, 20mm], [20mm, -5mm, 20mm], [20mm, 5mm, 20mm], [20mm, 16mm, 20mm], [20mm, 28mm, 20mm], [20mm, 40mm, 20mm]]
+ ControlRow: [[32mm, -40mm, 20mm], [32mm, -28mm, 20mm], [32mm, -16mm, 20mm], [32mm, -5mm, 20mm], [32mm, 5mm, 20mm], [32mm, 16mm, 20mm], [32mm, 28mm, 20mm], [32mm, 40mm, 20mm]]
+ ControlRow: [[42mm, -40mm, 20mm], [42mm, -28mm, 20mm], [42mm, -16mm, 20mm], [42mm, -5mm, 20mm], [42mm, 5mm, 20mm], [42mm, 16mm, 20mm], [42mm, 28mm, 20mm], [42mm, 40mm, 20mm]]
+ ControlRow: [[50mm, -40mm, 20mm], [50mm, -28mm, 20mm], [50mm, -16mm, 20mm], [50mm, -5mm, 20mm], [50mm, 5mm, 20mm], [50mm, 16mm, 20mm], [50mm, 28mm, 20mm], [50mm, 40mm, 20mm]]
+ Boundary South { Existing: CrownBoundarySouth
+ Continuity: G1 }
+ Boundary East { Existing: CrownBoundaryEast
+ Continuity: G1 }
+ Boundary North { Existing: CrownBoundaryNorth
+ Continuity: G1 }
+ Boundary West { Existing: CrownBoundaryWest
+ Continuity: G1 }
+ }
+
+ BodyState Base {
+ Size: [100mm, 80mm, 20mm]
+ Hole H1 { Center: [-47mm, -32mm]
+ Diameter: 4mm }
+ Hole H2 { Center: [47mm, -32mm]
+ Diameter: 4mm }
+ Hole H3 { Center: [47mm, -26mm]
+ Diameter: 4mm }
+ Hole H4 { Center: [-47mm, -26mm]
+ Diameter: 4mm }
+ }
+
+ SculptState TrimmedCrown {
+ Input: Base
+ ReplaceRegion {
+ Target: HousingCrown
+ Patch: CrownPatchX1a
+ InfluenceEnvelope: [-50mm, -40mm, 20mm, 50mm, 40mm, 28mm]
+ }
+ MayModify: [HousingCrown, CrownTransitionZone]
+ Preserve: [BottomMountingInterface, MountingHolePattern, OuterFootprintBoundary, SideWallsLower]
+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]
+ }
+
+ Output: TrimmedCrown
+}
diff --git a/fixtures/Canonical/coverage.json b/fixtures/Canonical/coverage.json
index 987e808b..223c6419 100644
--- a/fixtures/Canonical/coverage.json
+++ b/fixtures/Canonical/coverage.json
@@ -35,6 +35,10 @@
"SurfacePatch": "Sculpting/surf-x1-freeform-housing.firmament",
"ReplaceRegion": "Sculpting/surf-x1-freeform-housing.firmament",
"PatchG1": "Sculpting/surf-x1-freeform-housing.firmament",
- "PostSculptHole": "Sculpting/surf-x1-freeform-housing.firmament"
+ "PostSculptHole": "Sculpting/surf-x1-freeform-housing.firmament",
+ "SurfaceIntersection": "Sculpting/surf-x1a-trimmed-freeform-housing.firmament",
+ "Pcurve": "Sculpting/surf-x1a-trimmed-freeform-housing.firmament",
+ "InnerTrimLoops": "Sculpting/surf-x1a-trimmed-freeform-housing.firmament",
+ "PersistentGeometryAssociation": "Sculpting/surf-x1a-trimmed-freeform-housing.firmament"
}
}