Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Kernel: exact speedups for spline STEP reimport (pcurve seeds, B-spline evaluation, import memo)

Claude98ad67781d5a
diff --git a/Aetheris.Kernel.Core/Brep/BrepPcurveRecovery.cs b/Aetheris.Kernel.Core/Brep/BrepPcurveRecovery.cs
index 016e0d38..75df4275 100644
--- a/Aetheris.Kernel.Core/Brep/BrepPcurveRecovery.cs
+++ b/Aetheris.Kernel.Core/Brep/BrepPcurveRecovery.cs
@@ -235,35 +235,48 @@ public static class BrepPcurveRecovery
private static SurfaceParameterPoint GridSeed(BSplineSurfaceWithKnots spline, Point3D target)
{
+ // BUILD-PERF-M2: the seed samples depend only on the surface, so they are evaluated once per
+ // surface and scanned per target. Same samples, same order, same strict comparison: the
+ // result is identical to evaluating them for every target (which was ~9300 surface
+ // evaluations per seed and dominated spline-tube imports).
+ var samples = SeedSamples.GetValue(spline, BuildSeedSamples);
var best = new SurfaceParameterPoint(spline.DomainStartU, spline.DomainStartV);
var distance = double.PositiveInfinity;
+ for (var i = 0; i < samples.Length; i++)
+ {
+ var d = (samples[i].Point - target).LengthSquared;
+ if (d < distance) { distance = d; best = samples[i].Uv; }
+ }
+ return best;
+ }
+
+ private static readonly System.Runtime.CompilerServices.ConditionalWeakTable<BSplineSurfaceWithKnots, (SurfaceParameterPoint Uv, Point3D Point)[]> SeedSamples = new();
+
+ private static (SurfaceParameterPoint Uv, Point3D Point)[] BuildSeedSamples(BSplineSurfaceWithKnots spline)
+ {
const int divisions = 32;
+ // Trim endpoints commonly lie on a support-domain boundary. A narrow patch can
+ // be missed by a two-dimensional grid even when its boundary is easy to sample.
+ const int boundaryDivisions = 2048;
+ var samples = new List<(SurfaceParameterPoint, Point3D)>(((divisions + 1) * (divisions + 1)) + (4 * (boundaryDivisions + 1)));
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); }
+ Add(u, v);
}
- // Trim endpoints commonly lie on a support-domain boundary. A narrow patch can
- // be missed by a two-dimensional grid even when its boundary is easy to sample.
- const int boundaryDivisions = 2048;
for (var i = 0; i <= boundaryDivisions; i++)
{
var u = spline.DomainStartU + (spline.DomainEndU - spline.DomainStartU) * i / boundaryDivisions;
var v = spline.DomainStartV + (spline.DomainEndV - spline.DomainStartV) * i / boundaryDivisions;
- Check(u, spline.DomainStartV);
- Check(u, spline.DomainEndV);
- Check(spline.DomainStartU, v);
- Check(spline.DomainEndU, v);
+ Add(u, spline.DomainStartV);
+ Add(u, spline.DomainEndV);
+ Add(spline.DomainStartU, v);
+ Add(spline.DomainEndU, v);
}
- return best;
+ return samples.ToArray();
- void Check(double u, double v)
- {
- var d = (spline.Evaluate(u, v) - target).LengthSquared;
- if (d < distance) { distance = d; best = new(u, v); }
- }
+ void Add(double u, double v) => samples.Add((new SurfaceParameterPoint(u, v), spline.Evaluate(u, v)));
}
private static Point3D EvaluateCurve(CurveGeometry curve, double parameter) => curve.Kind switch
diff --git a/Aetheris.Kernel.Core/Geometry/Surfaces/BSplineSurfaceWithKnots.cs b/Aetheris.Kernel.Core/Geometry/Surfaces/BSplineSurfaceWithKnots.cs
index 586dd837..2f52d705 100644
--- a/Aetheris.Kernel.Core/Geometry/Surfaces/BSplineSurfaceWithKnots.cs
+++ b/Aetheris.Kernel.Core/Geometry/Surfaces/BSplineSurfaceWithKnots.cs
@@ -165,86 +165,70 @@ public sealed record BSplineSurfaceWithKnots
var uClamped = ClampToDomain(u, DomainStartU, DomainEndU);
var vClamped = ClampToDomain(v, DomainStartV, DomainEndV);
- if (_weightedNet is not null && _weightNet is not null)
+ // BUILD-PERF-M2: evaluation runs on flat arrays of the same data (no interface dispatch, no
+ // heap scratch). The arithmetic and its order are unchanged, so results are bit-identical.
+ var arrays = EvaluationArrays.GetValue(this, static surface => new Arrays(surface));
+ if (arrays.WeightedNet is not null && arrays.WeightNet is not null)
{
- var numerator = EvaluateNet(_weightedNet, uClamped, vClamped);
- var weight = EvaluateNet(_weightNet, uClamped, vClamped).X;
+ var numerator = EvaluateNet(arrays.WeightedNet, arrays, uClamped, vClamped);
+ var weight = EvaluateNet(arrays.WeightNet, arrays, uClamped, vClamped).X;
return new Point3D(numerator.X / weight, numerator.Y / weight, numerator.Z / weight);
}
- return EvaluateNet(ControlPoints, uClamped, vClamped);
+ return EvaluateNet(arrays.Net, arrays, uClamped, vClamped);
}
- private Point3D EvaluateNet(IReadOnlyList<IReadOnlyList<Point3D>> net, double uClamped, double vClamped)
- {
- if (double.Abs(uClamped - DomainEndU) <= 1e-12d && double.Abs(vClamped - DomainEndV) <= 1e-12d)
- {
- return net[^1][^1];
- }
+ // Kept beside the record, not in it: record equality and `with` copies stay as they were.
+ private static readonly System.Runtime.CompilerServices.ConditionalWeakTable<BSplineSurfaceWithKnots, Arrays> EvaluationArrays = new();
- // Tensor-product locality: de Boor in U consumes only DegreeU + 1
- // rows. Evaluating the whole net makes long helical supports needlessly
- // expensive, especially in the browser interpreter.
- if (double.Abs(uClamped - DomainEndU) <= 1e-12d)
- return EvaluateCurve(net[^1], DegreeV, FullKnotsV, DomainStartV, DomainEndV, vClamped);
- var span = FindSpan(net.Count, DegreeU, FullKnotsU, uClamped);
- var rowPoints = new Point3D[DegreeU + 1];
- for (var i = 0; i <= DegreeU; i++)
+ private sealed class Arrays
+ {
+ public Arrays(BSplineSurfaceWithKnots surface)
{
- rowPoints[i] = EvaluateCurve(
- net[span - DegreeU + i],
- DegreeV,
- FullKnotsV,
- DomainStartV,
- DomainEndV,
- vClamped);
+ Net = surface.ControlPoints.Select(row => row.ToArray()).ToArray();
+ WeightedNet = surface._weightedNet?.Select(row => row.ToArray()).ToArray();
+ WeightNet = surface._weightNet?.Select(row => row.ToArray()).ToArray();
+ KnotsU = surface.FullKnotsU.ToArray();
+ KnotsV = surface.FullKnotsV.ToArray();
+ DegreeU = surface.DegreeU;
+ DegreeV = surface.DegreeV;
+ DomainStartV = surface.DomainStartV;
+ DomainEndU = surface.DomainEndU;
+ DomainEndV = surface.DomainEndV;
}
- return BlendActiveSpan(rowPoints, span, DegreeU, FullKnotsU, uClamped);
+ public readonly Point3D[][] Net;
+ public readonly Point3D[][]? WeightedNet;
+ public readonly Point3D[][]? WeightNet;
+ public readonly double[] KnotsU;
+ public readonly double[] KnotsV;
+ public readonly int DegreeU;
+ public readonly int DegreeV;
+ public readonly double DomainStartV;
+ public readonly double DomainEndU;
+ public readonly double DomainEndV;
}
- private static IReadOnlyList<double> ExpandKnots(IReadOnlyList<int> multiplicities, IReadOnlyList<double> values)
+ private static Point3D EvaluateNet(Point3D[][] net, Arrays a, double uClamped, double vClamped)
{
- if (multiplicities is null || values is null || multiplicities.Count == 0 || multiplicities.Count != values.Count)
+ if (double.Abs(uClamped - a.DomainEndU) <= 1e-12d && double.Abs(vClamped - a.DomainEndV) <= 1e-12d)
{
- throw new ArgumentException("Knot multiplicities and values must be non-empty and have matching counts.");
+ return net[^1][^1];
}
- var knots = new List<double>();
- for (var i = 0; i < multiplicities.Count; i++)
+ if (double.Abs(uClamped - a.DomainEndU) <= 1e-12d)
+ return EvaluateCurve(net[^1], a.DegreeV, a.KnotsV, a.DomainStartV, a.DomainEndV, vClamped);
+ var span = FindSpan(net.Length, a.DegreeU, a.KnotsU, uClamped);
+ Span<Point3D> rowPoints = a.DegreeU < 32 ? stackalloc Point3D[a.DegreeU + 1] : new Point3D[a.DegreeU + 1];
+ for (var i = 0; i <= a.DegreeU; i++)
{
- if (multiplicities[i] <= 0 || !double.IsFinite(values[i]))
- {
- throw new ArgumentException("Knot multiplicities must be positive and knot values must be finite.");
- }
-
- for (var j = 0; j < multiplicities[i]; j++)
- {
- knots.Add(values[i]);
- }
+ rowPoints[i] = EvaluateCurve(net[span - a.DegreeU + i], a.DegreeV, a.KnotsV, a.DomainStartV, a.DomainEndV, vClamped);
}
- return knots;
+ return BlendActiveSpan(rowPoints, span, a.DegreeU, a.KnotsU, uClamped);
}
- private static void EnsureNonDecreasing(IReadOnlyList<double> knots, string dimension)
- {
- for (var i = 1; i < knots.Count; i++)
- {
- if (knots[i] < knots[i - 1])
- {
- throw new ArgumentException($"Expanded {dimension} knot vector must be non-decreasing.");
- }
- }
- }
-
- private static Point3D EvaluateCurve(
- IReadOnlyList<Point3D> controlPoints,
- int degree,
- IReadOnlyList<double> fullKnots,
- double domainStart,
- double domainEnd,
- double parameter)
+ private static Point3D EvaluateCurve(Point3D[] controlPoints, int degree, double[] fullKnots, double domainStart, double domainEnd, double parameter)
{
var u = ClampToDomain(parameter, domainStart, domainEnd);
if (double.Abs(u - domainEnd) <= 1e-12d)
@@ -252,18 +236,13 @@ public sealed record BSplineSurfaceWithKnots
return controlPoints[^1];
}
- var span = FindSpan(controlPoints.Count, degree, fullKnots, u);
- var d = new Point3D[degree + 1];
- for (var j = 0; j <= degree; j++)
- {
- d[j] = controlPoints[span - degree + j];
- }
-
+ var span = FindSpan(controlPoints.Length, degree, fullKnots, u);
+ Span<Point3D> d = degree < 32 ? stackalloc Point3D[degree + 1] : new Point3D[degree + 1];
+ controlPoints.AsSpan(span - degree, degree + 1).CopyTo(d);
return BlendActiveSpan(d, span, degree, fullKnots, u);
}
- private static Point3D BlendActiveSpan(Point3D[] d, int span, int degree,
- IReadOnlyList<double> fullKnots, double u)
+ private static Point3D BlendActiveSpan(Span<Point3D> d, int span, int degree, double[] fullKnots, double u)
{
for (var r = 1; r <= degree; r++)
{
@@ -280,7 +259,7 @@ public sealed record BSplineSurfaceWithKnots
return d[degree];
}
- private static int FindSpan(int controlPointCount, int degree, IReadOnlyList<double> fullKnots, double parameter)
+ private static int FindSpan(int controlPointCount, int degree, double[] fullKnots, double parameter)
{
var n = controlPointCount - 1;
if (parameter >= fullKnots[n + 1])
@@ -308,6 +287,41 @@ public sealed record BSplineSurfaceWithKnots
return mid;
}
+ private static IReadOnlyList<double> ExpandKnots(IReadOnlyList<int> multiplicities, IReadOnlyList<double> values)
+ {
+ if (multiplicities is null || values is null || multiplicities.Count == 0 || multiplicities.Count != values.Count)
+ {
+ throw new ArgumentException("Knot multiplicities and values must be non-empty and have matching counts.");
+ }
+
+ var knots = new List<double>();
+ for (var i = 0; i < multiplicities.Count; i++)
+ {
+ if (multiplicities[i] <= 0 || !double.IsFinite(values[i]))
+ {
+ throw new ArgumentException("Knot multiplicities must be positive and knot values must be finite.");
+ }
+
+ for (var j = 0; j < multiplicities[i]; j++)
+ {
+ knots.Add(values[i]);
+ }
+ }
+
+ return knots;
+ }
+
+ private static void EnsureNonDecreasing(IReadOnlyList<double> knots, string dimension)
+ {
+ for (var i = 1; i < knots.Count; i++)
+ {
+ if (knots[i] < knots[i - 1])
+ {
+ throw new ArgumentException($"Expanded {dimension} knot vector must be non-decreasing.");
+ }
+ }
+ }
+
private static double ClampToDomain(double parameter, double start, double end)
{
if (parameter <= start)
diff --git a/Aetheris.Kernel.Core/Step242/Step242Importer.cs b/Aetheris.Kernel.Core/Step242/Step242Importer.cs
index e51a47ac..9fd8cc0f 100644
--- a/Aetheris.Kernel.Core/Step242/Step242Importer.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242Importer.cs
@@ -115,11 +115,42 @@ public static class Step242Importer
public static KernelResult<BrepBody> ImportBody(string stepText, ImportPolicy? policy = null)
{
using var buildPerfPhase = Aetheris.Kernel.Core.Diagnostics.BuildPerfTrace.Phase("step.import-body");
+ // BUILD-PERF-M2: one build reimports the same canonical STEP several times (export
+ // validation, volume assertions, the assembly definition). Import is a pure function of the
+ // text unless a policy, a diagnostics capture or rational preservation is in effect, so a
+ // recent successful import is replayed as an independent clone of the same body.
+ var memoizable = policy is null && !RationalSurfacesArePreserved && CircularSamplingDiagnosticsSink.Value is null
+ && CoedgeGapDiagnosticsSink.Value is null && CylinderProjectionDiagnosticsSink.Value is null
+ && TorusProjectionDiagnosticsSink.Value is null && PlanarMultiBoundJudgmentDiagnosticsSink.Value is null;
+ if (memoizable)
+ {
+ lock (RecentImports)
+ {
+ for (var i = RecentImports.Count - 1; i >= 0; i--)
+ {
+ var (text, body, diagnostics) = RecentImports[i];
+ if (text.Length != stepText.Length || !string.Equals(text, stepText, StringComparison.Ordinal)) continue;
+ return KernelResult<BrepBody>.Success(body.Clone(), diagnostics);
+ }
+ }
+ }
var orchestrator = ImportOrchestrator.CreateDefault();
- var result = orchestrator.Import(new ImportRequest(stepText, policy));
- return result.BodyResult;
+ var result = orchestrator.Import(new ImportRequest(stepText, policy)).BodyResult;
+ if (memoizable && result.IsSuccess && result.Value is not null)
+ {
+ var retained = result.Value.Clone();
+ lock (RecentImports)
+ {
+ RecentImports.Add((stepText, retained, result.Diagnostics));
+ if (RecentImports.Count > RecentImportCapacity) RecentImports.RemoveAt(0);
+ }
+ }
+ return result;
}
+ private const int RecentImportCapacity = 8;
+ private static readonly List<(string Text, BrepBody Body, IReadOnlyList<Aetheris.Kernel.Core.Diagnostics.KernelDiagnostic> Diagnostics)> RecentImports = [];
+
private static KernelResult<BrepBody> ImportAuto(Step242ParsedDocument document)
{
if (Step242TessellatedImportLane.HasTessellatedRoot(document))