Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add analytic cone and torus map hits
Yuechen Li14f27ad2b92b
diff --git a/Aetheris.CLI.Tests/CliBaselineTests.cs b/Aetheris.CLI.Tests/CliBaselineTests.csindex a12cd80f..19672dba 100644--- a/Aetheris.CLI.Tests/CliBaselineTests.cs+++ b/Aetheris.CLI.Tests/CliBaselineTests.cs@@ -1,5 +1,7 @@using System.Text.Json;using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Features;+using Aetheris.Kernel.Core.Math;using Aetheris.Kernel.Core.Step242;namespace Aetheris.CLI.Tests;@@ -569,6 +571,63 @@ public sealed class CliBaselineTestsAssert.Empty(hit.GetProperty("diagnostics").EnumerateArray());}+ [Fact]+ public void Analyze_Map_RayProbe_Cone_Uses_Analytic_Exact_Hits()+ {+ var stepPath = ExportPrimitiveToTempStep(CreateCone(4d, 2d, 8d), "cli-ray-map-cone");+ using var doc = RunAnalyzeRayMap(stepPath, "--plane", "xz", "--direction", "+y", "--resolution", "5x5", "--point", "3,0");+ var root = doc.RootElement;++ Assert.True(root.GetProperty("summary").GetProperty("analyticHitCount").GetInt32() > 0);+ Assert.Equal(0, root.GetProperty("summary").GetProperty("tessellatedFallbackHitCount").GetInt32());+ var hit = root.GetProperty("hits").EnumerateArray().First(h => h.GetProperty("surfaceFamily").GetString() == "cone");+ Assert.Equal("analytic", hit.GetProperty("intersectionMode").GetString());+ Assert.Equal("exact", hit.GetProperty("confidence").GetString());+ Assert.InRange(hit.GetProperty("position").GetProperty("z").GetDouble(), 0d, 8d);+ Assert.True(hit.TryGetProperty("normal", out _));+ }++ [Fact]+ public void Analyze_Map_RayProbe_Torus_CenterHole_Does_Not_Lie()+ {+ var stepPath = ExportPrimitiveToTempStep(BrepPrimitives.CreateTorus(3d, 1d).Value, "cli-ray-map-torus-hole");+ using var doc = RunAnalyzeRayMap(stepPath, "--plane", "xz", "--direction", "+y", "--resolution", "5x5", "--point", "0,0");+ var root = doc.RootElement;++ Assert.Equal(0, root.GetProperty("summary").GetProperty("tessellatedFallbackHitCount").GetInt32());+ Assert.Equal(0, root.GetProperty("hitCount").GetInt32());+ Assert.DoesNotContain("torus", root.GetRawText(), StringComparison.Ordinal);+ }++ [Fact]+ public void Analyze_Map_RayProbe_Torus_RingHit_Uses_Analytic_Exact_Hits()+ {+ var stepPath = ExportPrimitiveToTempStep(BrepPrimitives.CreateTorus(3d, 1d).Value, "cli-ray-map-torus-ring");+ using var doc = RunAnalyzeRayMap(stepPath, "--plane", "xz", "--direction", "+y", "--resolution", "5x5", "--point", "3,0");+ var root = doc.RootElement;++ Assert.True(root.GetProperty("summary").GetProperty("analyticHitCount").GetInt32() > 0);+ Assert.Equal(0, root.GetProperty("summary").GetProperty("tessellatedFallbackHitCount").GetInt32());+ var hits = root.GetProperty("hits").EnumerateArray().Where(h => h.GetProperty("surfaceFamily").GetString() == "torus").ToArray();+ Assert.Single(hits);+ Assert.All(hits, hit =>+ {+ Assert.Equal("analytic", hit.GetProperty("intersectionMode").GetString());+ Assert.Equal("exact", hit.GetProperty("confidence").GetString());+ Assert.InRange(Math.Abs(hit.GetProperty("position").GetProperty("y").GetDouble()), 0.999d, 1.001d);+ });+ }++ [Fact]+ public void Analyze_Map_RayProbe_Torus_Outside_Misses()+ {+ var stepPath = ExportPrimitiveToTempStep(BrepPrimitives.CreateTorus(3d, 1d).Value, "cli-ray-map-torus-outside");+ using var doc = RunAnalyzeRayMap(stepPath, "--plane", "xz", "--direction", "+y", "--resolution", "5x5", "--point", "5,0");++ Assert.Equal(0, doc.RootElement.GetProperty("hitCount").GetInt32());+ Assert.Equal(0, doc.RootElement.GetProperty("summary").GetProperty("tessellatedFallbackHitCount").GetInt32());+ }+[Fact]public void Analyze_Map_RayProbe_LinearExtrusion_Discloses_Tessellated_Fallback(){@@ -1422,6 +1481,17 @@ public sealed class CliBaselineTestsreturn JsonDocument.Parse(stdout.ToString());}++ private static BrepBody CreateCone(double bottomRadius, double topRadius, double height)+ {+ var result = BrepRevolve.Create(+ [new ProfilePoint2D(bottomRadius, 0d), new ProfilePoint2D(topRadius, height)],+ new ExtrudeFrame3D(Point3D.Origin, Direction3D.Create(new Vector3D(0d, 0d, 1d)), Direction3D.Create(new Vector3D(1d, 0d, 0d))),+ new RevolveAxis3D(Point3D.Origin, new Vector3D(0d, 0d, 1d)));+ Assert.True(result.IsSuccess, string.Join(Environment.NewLine, result.Diagnostics.Select(d => d.Message)));+ return result.Value;+ }+private static string ExportPrimitiveToTempStep(BrepBody body, string stem){var export = Step242Exporter.ExportBody(body);diff --git a/Aetheris.CLI/StepAnalyzer.cs b/Aetheris.CLI/StepAnalyzer.csindex e1753143..9bc26b71 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" and not "cylinder" and not "sphere").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" and not "cone" and not "torus").OrderBy(f => f, StringComparer.Ordinal)){AddDiagnostic(diagnostics, diagnosticSet, $"Exact ray intersection unavailable for {family}; used tessellated fallback.");}@@ -1918,6 +1918,18 @@ public sealed record VolumeAnalysisResult(continue;}+ if (surface.Cone is ConeSurface cone)+ {+ hits.AddRange(IntersectAnalyticConeFaceRay(body, face, cone, origin, direction, faceSurfaceKinds));+ continue;+ }++ if (surface.Torus is TorusSurface torus)+ {+ hits.AddRange(IntersectAnalyticTorusFaceRay(body, face, torus, origin, direction, faceSurfaceKinds));+ continue;+ }+continue;}@@ -2025,6 +2037,141 @@ public sealed record VolumeAnalysisResult(return hits;}++ private static IReadOnlyList<RayMapHit> IntersectAnalyticConeFaceRay(BrepBody body, Face face, ConeSurface cone, Point3D origin, Vector3D direction, IReadOnlyDictionary<int, string> faceSurfaceKinds)+ {+ var hits = new List<RayMapHit>();+ var axis = cone.Axis.ToVector();+ if (!TryNormalize(axis, out axis)) return hits;+ if (!TryGetFaceAxisSpan(body, face.Id, cone.Apex, axis, out var minAxis, out var maxAxis)) return hits;++ var tan = Math.Tan(cone.SemiAngleRadians);+ var tan2 = tan * tan;+ var delta = origin - cone.Apex;+ var dAxial = direction.Dot(axis);+ var oAxial = delta.Dot(axis);+ var dPerp = direction - axis * dAxial;+ var oPerp = delta - axis * oAxial;+ var a = dPerp.Dot(dPerp) - tan2 * dAxial * dAxial;+ var b = 2d * (oPerp.Dot(dPerp) - tan2 * oAxial * dAxial);+ var c = oPerp.Dot(oPerp) - tan2 * oAxial * oAxial;+ if (Math.Abs(a) < 1e-14d) return hits;++ foreach (var t in SolveQuadraticNonnegative(a, b, c))+ {+ var p = origin + direction * t;+ var axial = (p - cone.Apex).Dot(axis);+ if (axial < Math.Max(0d, minAxis) - 1e-7d || axial > maxAxis + 1e-7d) continue;+ var radial = (p - cone.Apex) - axis * axial;+ if (!TryNormalize(radial, out var radialNormal)) continue;+ if (!TryNormalize(radialNormal - axis * tan, out var normal)) continue;+ var family = faceSurfaceKinds.TryGetValue(face.Id.Value, out var sf) ? sf : "cone";+ hits.Add(new RayMapHit(t, p, face.Id.Value, family, normal, "analytic", "exact", []));+ }++ return DeduplicateHits(hits);+ }++ private static IReadOnlyList<RayMapHit> IntersectAnalyticTorusFaceRay(BrepBody body, Face face, TorusSurface torus, Point3D origin, Vector3D direction, IReadOnlyDictionary<int, string> faceSurfaceKinds)+ {+ var hits = new List<RayMapHit>();+ if (torus.MajorRadius <= 0d || torus.MinorRadius <= 0d) return hits;+ if (body.Topology.Faces.Count() != 1)+ {+ return hits;+ }++ if (!TryIntersectBoundingSphere(origin, direction, torus.Center, torus.MajorRadius + torus.MinorRadius, out var near, out var far)) return hits;+ near = Math.Max(0d, near);+ if (far < near) return hits;++ const int samples = 1024;+ var dt = (far - near) / samples;+ var roots = new List<double>();+ var prevT = near;+ var prevF = TorusImplicit(origin + direction * prevT, torus);+ if (Math.Abs(prevF) <= 1e-9d) roots.Add(prevT);+ for (var i = 1; i <= samples; i++)+ {+ var t = i == samples ? far : near + i * dt;+ var f = TorusImplicit(origin + direction * t, torus);+ if (Math.Abs(f) <= 1e-9d) roots.Add(t);+ if ((prevF < 0d && f > 0d) || (prevF > 0d && f < 0d)) roots.Add(BisectTorusRoot(prevT, t, origin, direction, torus));+ prevT = t; prevF = f;+ }++ var family = faceSurfaceKinds.TryGetValue(face.Id.Value, out var sf) ? sf : "torus";+ foreach (var t in roots.Where(t => t >= -1e-9d).Select(t => Math.Max(0d, t)).OrderBy(t => t))+ {+ if (hits.Any(h => Math.Abs(h.T - t) <= 1e-7d)) continue;+ var p = origin + direction * t;+ if (!TryTorusNormal(p, torus, out var normal)) continue;+ hits.Add(new RayMapHit(t, p, face.Id.Value, family, normal, "analytic", "exact", []));+ }+ return hits;+ }++ private static bool TryIntersectBoundingSphere(Point3D origin, Vector3D direction, Point3D center, double radius, out double near, out double far)+ {+ near = far = 0d;+ var oc = origin - center;+ var b = 2d * oc.Dot(direction);+ var c = oc.Dot(oc) - radius * radius;+ var disc = b * b - 4d * direction.Dot(direction) * c;+ if (disc < -1e-9d) return false;+ var sqrt = Math.Sqrt(Math.Max(0d, disc));+ var a2 = 2d * direction.Dot(direction);+ near = (-b - sqrt) / a2;+ far = (-b + sqrt) / a2;+ return far >= -1e-9d;+ }++ private static double TorusImplicit(Point3D p, TorusSurface torus)+ {+ var d = p - torus.Center;+ var x = d.Dot(torus.XAxis.ToVector());+ var y = d.Dot(torus.YAxis.ToVector());+ var z = d.Dot(torus.Axis.ToVector());+ var sum = x*x + y*y + z*z + torus.MajorRadius*torus.MajorRadius - torus.MinorRadius*torus.MinorRadius;+ return sum*sum - 4d*torus.MajorRadius*torus.MajorRadius*(x*x + y*y);+ }++ private static double BisectTorusRoot(double lo, double hi, Point3D origin, Vector3D direction, TorusSurface torus)+ {+ var flo = TorusImplicit(origin + direction * lo, torus);+ for (var i = 0; i < 80; i++)+ {+ var mid = (lo + hi) * 0.5d;+ var fmid = TorusImplicit(origin + direction * mid, torus);+ if (Math.Abs(fmid) <= 1e-12d || hi - lo <= 1e-9d) return mid;+ if ((flo < 0d && fmid > 0d) || (flo > 0d && fmid < 0d)) hi = mid;+ else { lo = mid; flo = fmid; }+ }+ return (lo + hi) * 0.5d;+ }++ private static bool TryTorusNormal(Point3D p, TorusSurface torus, out Vector3D normal)+ {+ var d = p - torus.Center;+ var xAxis = torus.XAxis.ToVector();+ var yAxis = torus.YAxis.ToVector();+ var zAxis = torus.Axis.ToVector();+ var x = d.Dot(xAxis); var y = d.Dot(yAxis); var z = d.Dot(zAxis);+ var common = x*x + y*y + z*z + torus.MajorRadius*torus.MajorRadius - torus.MinorRadius*torus.MinorRadius;+ var n = xAxis * (4d*x*(common - 2d*torus.MajorRadius*torus.MajorRadius))+ + yAxis * (4d*y*(common - 2d*torus.MajorRadius*torus.MajorRadius))+ + zAxis * (4d*z*common);+ return TryNormalize(n, out normal);+ }++ private static IReadOnlyList<RayMapHit> DeduplicateHits(List<RayMapHit> hits)+ {+ var ordered = hits.OrderBy(h => h.T).ToList();+ for (var i = ordered.Count - 1; i > 0; i--)+ if (Math.Abs(ordered[i].T - ordered[i - 1].T) <= 1e-7d) ordered.RemoveAt(i);+ return ordered;+ }+private static IReadOnlyList<double> SolveQuadraticNonnegative(double a, double b, double c){var discriminant = (b * b) - (4d * a * c);diff --git a/docs/implementation/analyze-map-a2-cylinder-sphere-analytic-hits.md b/docs/implementation/analyze-map-a2-cylinder-sphere-analytic-hits.mdindex 8bb8db00..bfaa1451 100644--- a/docs/implementation/analyze-map-a2-cylinder-sphere-analytic-hits.md+++ b/docs/implementation/analyze-map-a2-cylinder-sphere-analytic-hits.md@@ -86,3 +86,5 @@ It does not change `analyze volume`, DisplayIR/frontend behavior, modeling capab## Next planned truth passThe 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.++Forward link: ANALYZE-MAP-A3 extends this analytic tier to cone and torus hits; see `docs/implementation/analyze-map-a3-cone-torus-analytic-hits.md`.diff --git a/docs/implementation/analyze-map-a3-cone-torus-analytic-hits.md b/docs/implementation/analyze-map-a3-cone-torus-analytic-hits.mdnew file mode 100644index 00000000..d81b851f--- /dev/null+++ b/docs/implementation/analyze-map-a3-cone-torus-analytic-hits.md@@ -0,0 +1,83 @@+# ANALYZE-MAP-A3 Cone/Torus Analytic Ray Hits++ANALYZE-MAP-A3 extends the `aetheris analyze map` analytic-first ray backend from planes, cylinders, and spheres to conical and toroidal surfaces. The goal is to keep LLM-facing spatial measurements independent from display tessellation whenever the imported analytic surface is sufficient.++## Surfaces now analytic++- plane+- cylinder+- sphere+- cone+- torus++## Cone implementation summary++Cone hits use the imported `ConeSurface` representation: apex, axis, semi-angle, placement radius/origin, and reference axis. For each ray `P(t) = O + tD`, the implementation solves the infinite right-circular cone quadratic in apex/axis coordinates, filters nonnegative roots, filters roots to the face axial span derived from bounded face vertices, sorts hits by ray parameter, and computes normals from the radial direction minus the cone slope component.++Simple full conical/frustum faces with reliable vertex-derived axial bounds report:++```json+{+ "surfaceFamily": "cone",+ "intersectionMode": "analytic",+ "confidence": "exact",+ "diagnostics": []+}+```++If a future conical face cannot provide a reliable bounded span, the analytic candidate is not claimed as exact and the existing explicit tessellated fallback path remains responsible for diagnostics.++## Torus implementation summary++Torus hits use the imported `TorusSurface` center, axis, orthonormal local axes, major radius, and minor radius. The ray is evaluated in torus-local coordinates against the standard implicit equation:++```text+(x² + y² + z² + R² - r²)² - 4R²(x² + y²) = 0+```++A bounding sphere first limits the candidate interval. The current CLI path then isolates real roots numerically over that bounded interval with fixed sampling plus bisection on sign changes, using tolerances around `1e-9` for root detection and `1e-7` for duplicate suppression. This avoids depending on the torus display mesh for simple full-torus truth-pass probes.++Normals are computed from the gradient of the implicit torus equation and transformed back to model coordinates.++## Containment policy++- Cone: exact only when the conical face has a reliable finite axial span from its bounded topology. Angular trim handling is intentionally not generalized in A3.+- Torus: exact for the current single-face full-torus primitive/import shape. Trimmed torus patches are not claimed as exact by this milestone and may continue through explicit fallback diagnostics.+- Tessellated hits are not duplicated for faces that already produced analytic hits.++## Torus truth-pass tests++A3 adds focused CLI tests using a generated torus with major radius `3` and minor radius `1`:++- center-hole ray: a ray through the torus hole returns no torus hit and no tessellated false positive;+- ring ray: a ray through the ring returns an analytic torus hit with exact confidence;+- outside ray: a ray outside `major + minor` misses.++These tests specifically guard against display tessellation making the donut goblin lie to the LLM.++## Fixture paths++The focused tests generate STEP fixtures through existing primitive export paths at test runtime:++- cone/frustum: generated from `BrepRevolve.Create` in `Aetheris.CLI.Tests`;+- torus: generated from `BrepPrimitives.CreateTorus(3, 1)` in `Aetheris.CLI.Tests`.++The ruled/linear-extrusion fallback regression continues to use:++```text+testdata/step242/generated/ruled-a2/ellipse-linear-extrusion-production.step+```++## Surfaces still fallback++- linear-extrusion+- surface-of-revolution+- B-spline++## Limitations and non-scope++- Trimmed torus patches may still fallback.+- The torus solver is a bounded numeric isolation strategy with documented tolerances rather than a symbolic quartic solver.+- No volume integration behavior is changed.+- No linear-extrusion, surface-of-revolution, or B-spline analytic hits are added.+- No DisplayIR/frontend changes or new modeling features are included.