Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add analytic map hits for cylinders and spheres

Yuechen Li06d57769ee50
diff --git a/Aetheris.CLI.Tests/CliBaselineTests.cs b/Aetheris.CLI.Tests/CliBaselineTests.cs
index 4c04444c..a12cd80f 100644
--- a/Aetheris.CLI.Tests/CliBaselineTests.cs
+++ b/Aetheris.CLI.Tests/CliBaselineTests.cs
@@ -536,6 +536,39 @@ public sealed class CliBaselineTests
Assert.Equal(2, root.GetProperty("samples")[12].GetProperty("intersectionModes").GetProperty("analytic").GetInt32());
}
+
+ [Fact]
+ public void Analyze_Map_RayProbe_CylinderSide_Uses_Analytic_Exact_Hits()
+ {
+ var stepPath = ExportPrimitiveToTempStep(BrepPrimitives.CreateCylinder(3d, 8d).Value, "cli-ray-map-cylinder-side");
+ using var doc = RunAnalyzeRayMap(stepPath, "--plane", "xz", "--direction", "+y", "--resolution", "5x5", "--point", "0,0");
+ var root = doc.RootElement;
+
+ Assert.True(root.GetProperty("summary").GetProperty("analyticHitCount").GetInt32() > 0);
+ Assert.Equal(0, root.GetProperty("summary").GetProperty("tessellatedFallbackHitCount").GetInt32());
+ Assert.Equal("analytic", root.GetProperty("intersectionMode").GetString());
+ var hit = root.GetProperty("hits").EnumerateArray().First(h => h.GetProperty("surfaceFamily").GetString() == "cylinder");
+ Assert.Equal("analytic", hit.GetProperty("intersectionMode").GetString());
+ Assert.Equal("exact", hit.GetProperty("confidence").GetString());
+ Assert.Empty(hit.GetProperty("diagnostics").EnumerateArray());
+ }
+
+ [Fact]
+ public void Analyze_Map_RayProbe_Sphere_Uses_Analytic_Exact_Hits()
+ {
+ var stepPath = ExportPrimitiveToTempStep(BrepPrimitives.CreateSphere(3d).Value, "cli-ray-map-sphere");
+ using var doc = RunAnalyzeRayMap(stepPath, "--plane", "xy", "--direction", "-z", "--resolution", "5x5", "--point", "0,0");
+ var root = doc.RootElement;
+
+ Assert.True(root.GetProperty("summary").GetProperty("analyticHitCount").GetInt32() > 0);
+ Assert.Equal(0, root.GetProperty("summary").GetProperty("tessellatedFallbackHitCount").GetInt32());
+ Assert.Equal("analytic", root.GetProperty("intersectionMode").GetString());
+ var hit = root.GetProperty("hits").EnumerateArray().First(h => h.GetProperty("surfaceFamily").GetString() == "sphere");
+ Assert.Equal("analytic", hit.GetProperty("intersectionMode").GetString());
+ Assert.Equal("exact", hit.GetProperty("confidence").GetString());
+ Assert.Empty(hit.GetProperty("diagnostics").EnumerateArray());
+ }
+
[Fact]
public void Analyze_Map_RayProbe_LinearExtrusion_Discloses_Tessellated_Fallback()
{
diff --git a/Aetheris.CLI/StepAnalyzer.cs b/Aetheris.CLI/StepAnalyzer.cs
index b7088f5c..e1753143 100644
--- a/Aetheris.CLI/StepAnalyzer.cs
+++ b/Aetheris.CLI/StepAnalyzer.cs
@@ -942,7 +942,7 @@ public sealed record VolumeAnalysisResult(
var faceSurfaceKinds = BuildFaceSurfaceKinds(body, familyNames: true);
var diagnostics = new List<string>();
var diagnosticSet = new HashSet<string>(StringComparer.Ordinal);
- foreach (var family in faceSurfaceKinds.Values.Distinct(StringComparer.Ordinal).Where(f => f is not "plane").OrderBy(f => f, StringComparer.Ordinal))
+ foreach (var family in faceSurfaceKinds.Values.Distinct(StringComparer.Ordinal).Where(f => f is not "plane" and not "cylinder" and not "sphere").OrderBy(f => f, StringComparer.Ordinal))
{
AddDiagnostic(diagnostics, diagnosticSet, $"Exact ray intersection unavailable for {family}; used tessellated fallback.");
}
@@ -969,9 +969,10 @@ public sealed record VolumeAnalysisResult(
{
var u = point?.U ?? frame.MinU + (cols == 1 ? 0.5d : i / (double)(cols - 1)) * frame.RangeU;
var origin = frame.PlaneOrigin + (frame.UAxis * u) + (frame.VAxis * v) - (frame.RayDirection * Math.Max(1e-5d, ToleranceContext.Default.Linear * 64d));
- var analyticHits = IntersectAnalyticPlaneRay(body, origin, frame.RayDirection, faceSurfaceKinds).ToArray();
+ var analyticHits = IntersectAnalyticRay(body, origin, frame.RayDirection, faceSurfaceKinds).ToArray();
+ var analyticFaceIds = analyticHits.Select(h => h.FaceIndex).Where(id => id.HasValue).Select(id => id!.Value).ToHashSet();
var tessellatedHits = IntersectTessellatedRay(tessellation, origin, frame.RayDirection, faceSurfaceKinds)
- .Where(h => h.SurfaceFamily is not "plane")
+ .Where(h => h.SurfaceFamily is not "plane" && (h.FaceIndex is null || !analyticFaceIds.Contains(h.FaceIndex.Value)))
.ToArray();
foreach (var hit in tessellatedHits)
@@ -1893,13 +1894,30 @@ public sealed record VolumeAnalysisResult(
}
}
- private static IReadOnlyList<RayMapHit> IntersectAnalyticPlaneRay(BrepBody body, Point3D origin, Vector3D direction, IReadOnlyDictionary<int, string> faceSurfaceKinds)
+ private static IReadOnlyList<RayMapHit> IntersectAnalyticRay(BrepBody body, Point3D origin, Vector3D direction, IReadOnlyDictionary<int, string> faceSurfaceKinds)
{
var hits = new List<RayMapHit>();
foreach (var face in body.Topology.Faces)
{
- if (!body.TryGetFaceSurface(face.Id, out var surface) || surface?.Plane is not PlaneSurface plane)
+ if (!body.TryGetFaceSurface(face.Id, out var surface) || surface is null)
+ {
+ continue;
+ }
+
+ if (surface.Plane is not PlaneSurface plane)
{
+ if (surface.Cylinder is CylinderSurface cylinder)
+ {
+ hits.AddRange(IntersectAnalyticCylinderFaceRay(body, face, cylinder, origin, direction, faceSurfaceKinds));
+ continue;
+ }
+
+ if (surface.Sphere is SphereSurface sphere)
+ {
+ hits.AddRange(IntersectAnalyticSphereFaceRay(body, face, sphere, origin, direction, faceSurfaceKinds));
+ continue;
+ }
+
continue;
}
@@ -1929,6 +1947,128 @@ public sealed record VolumeAnalysisResult(
return hits.OrderBy(h => h.T).ToArray();
}
+
+ private static IReadOnlyList<RayMapHit> IntersectAnalyticCylinderFaceRay(BrepBody body, Face face, CylinderSurface cylinder, Point3D origin, Vector3D direction, IReadOnlyDictionary<int, string> faceSurfaceKinds)
+ {
+ var hits = new List<RayMapHit>();
+ var axis = cylinder.Axis.ToVector();
+ if (!TryNormalize(axis, out axis) || cylinder.Radius <= 0d)
+ {
+ return hits;
+ }
+
+ if (!TryGetFaceAxisSpan(body, face.Id, cylinder.Origin, axis, out var minAxis, out var maxAxis))
+ {
+ return hits;
+ }
+
+ var oc = origin - cylinder.Origin;
+ var dParallel = axis * direction.Dot(axis);
+ var oParallel = axis * oc.Dot(axis);
+ var dPerp = direction - dParallel;
+ var oPerp = oc - oParallel;
+ var a = dPerp.Dot(dPerp);
+ var b = 2d * oPerp.Dot(dPerp);
+ var c = oPerp.Dot(oPerp) - (cylinder.Radius * cylinder.Radius);
+ if (Math.Abs(a) < 1e-14d)
+ {
+ return hits;
+ }
+
+ foreach (var t in SolveQuadraticNonnegative(a, b, c))
+ {
+ var p = origin + direction * t;
+ var axial = (p - cylinder.Origin).Dot(axis);
+ if (axial < minAxis - 1e-7d || axial > maxAxis + 1e-7d)
+ {
+ continue;
+ }
+
+ var radial = (p - cylinder.Origin) - (axis * axial);
+ if (!TryNormalize(radial, out var normal))
+ {
+ continue;
+ }
+
+ var family = faceSurfaceKinds.TryGetValue(face.Id.Value, out var sf) ? sf : "cylinder";
+ hits.Add(new RayMapHit(t, p, face.Id.Value, family, normal, "analytic", "exact", []));
+ }
+
+ return hits;
+ }
+
+ private static IReadOnlyList<RayMapHit> IntersectAnalyticSphereFaceRay(BrepBody body, Face face, SphereSurface sphere, Point3D origin, Vector3D direction, IReadOnlyDictionary<int, string> faceSurfaceKinds)
+ {
+ var hits = new List<RayMapHit>();
+ if (sphere.Radius <= 0d || body.GetEdges(face.Id).Any())
+ {
+ return hits;
+ }
+
+ var oc = origin - sphere.Center;
+ var a = direction.Dot(direction);
+ var b = 2d * oc.Dot(direction);
+ var c = oc.Dot(oc) - (sphere.Radius * sphere.Radius);
+ foreach (var t in SolveQuadraticNonnegative(a, b, c))
+ {
+ var p = origin + direction * t;
+ var radial = p - sphere.Center;
+ if (!TryNormalize(radial, out var normal))
+ {
+ continue;
+ }
+
+ var family = faceSurfaceKinds.TryGetValue(face.Id.Value, out var sf) ? sf : "sphere";
+ hits.Add(new RayMapHit(t, p, face.Id.Value, family, normal, "analytic", "exact", []));
+ }
+
+ return hits;
+ }
+
+ private static IReadOnlyList<double> SolveQuadraticNonnegative(double a, double b, double c)
+ {
+ var discriminant = (b * b) - (4d * a * c);
+ if (discriminant < -1e-10d)
+ {
+ return [];
+ }
+
+ if (Math.Abs(discriminant) <= 1e-10d)
+ {
+ var t = -b / (2d * a);
+ return t >= -1e-9d ? [Math.Max(0d, t)] : [];
+ }
+
+ var sqrt = Math.Sqrt(discriminant);
+ var t0 = (-b - sqrt) / (2d * a);
+ var t1 = (-b + sqrt) / (2d * a);
+ var roots = new List<double>(2);
+ if (t0 >= -1e-9d) roots.Add(Math.Max(0d, t0));
+ if (t1 >= -1e-9d && Math.Abs(t1 - t0) > 1e-8d) roots.Add(Math.Max(0d, t1));
+ roots.Sort();
+ return roots;
+ }
+
+ private static bool TryGetFaceAxisSpan(BrepBody body, FaceId faceId, Point3D axisOrigin, Vector3D axis, out double minAxis, out double maxAxis)
+ {
+ var projections = body.GetEdges(faceId)
+ .SelectMany(edge => body.GetVertices(edge))
+ .Distinct()
+ .Select(vertex => body.TryGetVertexPoint(vertex, out var p) ? (double?)(p - axisOrigin).Dot(axis) : null)
+ .Where(v => v.HasValue)
+ .Select(v => v!.Value)
+ .ToArray();
+ if (projections.Length < 2)
+ {
+ minAxis = maxAxis = 0d;
+ return false;
+ }
+
+ minAxis = projections.Min();
+ maxAxis = projections.Max();
+ return maxAxis - minAxis > 1e-8d;
+ }
+
private static bool IsPointInPlanarFaceBounds(BrepBody body, FaceId faceId, PlaneSurface plane, Point3D point)
{
var vertices = body.GetEdges(faceId)
diff --git a/docs/implementation/analyze-map-a1-analytic-backend-provenance.md b/docs/implementation/analyze-map-a1-analytic-backend-provenance.md
index d327db56..880d5e78 100644
--- a/docs/implementation/analyze-map-a1-analytic-backend-provenance.md
+++ b/docs/implementation/analyze-map-a1-analytic-backend-provenance.md
@@ -109,3 +109,8 @@ CIR/evaluable intersection remains the next architectural hook once an admitted
```text
ANALYZE-MAP-A3: analytic cone + torus truth pass
```
+
+
+## Forward link
+
+ANALYZE-MAP-A2 extends this analytic tier from planes to cylinders and spheres; see `docs/implementation/analyze-map-a2-cylinder-sphere-analytic-hits.md`.
diff --git a/docs/implementation/analyze-map-a2-cylinder-sphere-analytic-hits.md b/docs/implementation/analyze-map-a2-cylinder-sphere-analytic-hits.md
new file mode 100644
index 00000000..8bb8db00
--- /dev/null
+++ b/docs/implementation/analyze-map-a2-cylinder-sphere-analytic-hits.md
@@ -0,0 +1,88 @@
+# ANALYZE-MAP-A2 Cylinder/Sphere Analytic Ray Hits
+
+`aetheris analyze map` now extends the analytic-first ray backend from bounded planes to common round analytic surfaces:
+
+- plane
+- cylinder
+- sphere
+
+The backend policy remains truth-first:
+
+1. analytic exact intersection for supported bounded faces;
+2. CIR/evaluable intersection later;
+3. tessellated fallback, explicitly marked approximate.
+
+## Cylinder formula
+
+For a ray `P(t) = O + tD` and cylinder support with origin point `C`, unit axis `A`, and radius `r`, the implementation removes the component parallel to the axis:
+
+- `D_perp = D - A * dot(D, A)`
+- `O_perp = (O - C) - A * dot(O - C, A)`
+
+It then solves:
+
+`dot(D_perp, D_perp)t² + 2 dot(O_perp, D_perp)t + dot(O_perp, O_perp) - r² = 0`
+
+Nonnegative roots are sorted by ray parameter. For each candidate, the hit point, face id, surface family, ray parameter, and radial normal are emitted.
+
+## Sphere formula
+
+For a ray `P(t) = O + tD` and sphere center `C` with radius `r`, the implementation solves:
+
+`dot(D, D)t² + 2 dot(O - C, D)t + dot(O - C, O - C) - r² = 0`
+
+Nonnegative roots are sorted by ray parameter. The normal is the normalized vector from the sphere center to the hit point.
+
+## Containment policy
+
+A2 only reports `confidence: exact` when the bounded-face containment policy is reliable for the current importer topology:
+
+- Planes continue to use the existing planar face-bound polygon check.
+- Cylinders use exact analytic infinite-cylinder math plus the finite axial span resolved from the cylindrical face vertices. The current exact path is intended for the full cylindrical side faces emitted by current primitive and hole fixtures; more complex cylindrical trims should remain on the explicit fallback path until stronger trim containment is added.
+- Spheres are reported exact for loopless full spherical faces. Trimmed spherical patches are not promoted to exact by this milestone; they remain eligible for explicit tessellated fallback until exact spherical trim containment is added.
+
+A2 intentionally does not claim exact bounded hits for unsupported trims. Tessellated fallback remains present and is still reported as `intersectionMode: tessellated-fallback` with `confidence: approximate`.
+
+## JSON provenance examples
+
+Exact cylinder/sphere hits use the same provenance fields introduced in A1:
+
+```json
+{
+ "surfaceFamily": "cylinder",
+ "intersectionMode": "analytic",
+ "confidence": "exact",
+ "diagnostics": []
+}
+```
+
+Fallback remains explicit:
+
+```json
+{
+ "surfaceFamily": "linear-extrusion",
+ "intersectionMode": "tessellated-fallback",
+ "confidence": "approximate",
+ "diagnostics": [
+ "Exact ray intersection unavailable for linear-extrusion; used tessellated fallback."
+ ]
+}
+```
+
+Top-level summaries continue to count `analyticHitCount`, `cirHitCount`, `tessellatedFallbackHitCount`, and per-sample `intersectionModes`.
+
+## Still fallback / non-scope
+
+A2 does not implement analytic hits for:
+
+- cone
+- torus
+- linear-extrusion
+- surface-of-revolution
+- B-spline
+
+It does not change `analyze volume`, DisplayIR/frontend behavior, modeling capabilities, CIR rewriting, volume integration, or feature reconstruction.
+
+## Next planned truth pass
+
+The next analytic map pass is expected to focus on cone and torus ray intersections plus a stronger trim-containment story for more complex bounded analytic patches.