Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
M17b: support analytic body queries for boolean native bodies
Yuechen Li5dd1334caef5
diff --git a/Aetheris.Kernel.Core.Tests/Brep/Queries/AnalyticDisplayQueryTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Queries/AnalyticDisplayQueryTests.csindex 3c06fbf2..9d4f7825 100644--- a/Aetheris.Kernel.Core.Tests/Brep/Queries/AnalyticDisplayQueryTests.cs+++ b/Aetheris.Kernel.Core.Tests/Brep/Queries/AnalyticDisplayQueryTests.cs@@ -1,6 +1,10 @@using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Boolean;using Aetheris.Kernel.Core.Brep.Features;using Aetheris.Kernel.Core.Brep.Queries;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Curves;+using Aetheris.Kernel.Core.Geometry.Surfaces;using Aetheris.Kernel.Core.Math;namespace Aetheris.Kernel.Core.Tests.Brep.Queries;@@ -139,6 +143,80 @@ public sealed class AnalyticDisplayQueryTestsAssert.Equal(Aetheris.Kernel.Core.Geometry.SurfaceGeometryKind.Torus, hit.SurfaceKind);}+ [Fact]+ public void BodyLevelNearestHit_BoxCylinderThroughHole_QueriesExteriorAndHoleSurface()+ {+ var body = CreateBoxCylinderThroughHole();++ var exteriorRay = new Ray3D(new Point3D(-30d, 0d, 6d), Direction3D.Create(new Vector3D(1d, 0d, 0d)));+ Assert.True(AnalyticDisplayQuery.TryIntersectBody(body, exteriorRay, out var exteriorHit));+ Assert.Equal(SurfaceGeometryKind.Plane, exteriorHit.SurfaceKind);++ var openingRay = new Ray3D(new Point3D(3d, -2d, 20d), Direction3D.Create(new Vector3D(0d, 0d, -1d)));+ Assert.False(AnalyticDisplayQuery.TryIntersectBody(body, openingRay, out _));++ var holeInteriorRay = new Ray3D(new Point3D(3d, -2d, 6d), Direction3D.Create(new Vector3D(1d, 0d, 0d)));+ Assert.True(AnalyticDisplayQuery.TryIntersectBody(body, holeInteriorRay, out var holeHit));+ Assert.Equal(SurfaceGeometryKind.Cylinder, holeHit.SurfaceKind);+ Assert.True(holeHit.Normal.X > 0d);++ Assert.True(AnalyticDisplayQuery.TryIntersectBody(body, holeInteriorRay, out var holeHitRepeat));+ Assert.Equal(holeHit.Distance, holeHitRepeat.Distance, 12);+ Assert.Equal(holeHit.FaceId, holeHitRepeat.FaceId);++ var spatial = BrepSpatialQueries.Raycast(body, openingRay);+ Assert.False(spatial.IsSuccess);+ }++ [Fact]+ public void BodyLevelNearestHit_BoxConeThroughHole_QueriesExteriorOpeningAndConicalSide()+ {+ var body = CreateBoxConeThroughHole();++ var exteriorRay = new Ray3D(new Point3D(-30d, 0d, 6d), Direction3D.Create(new Vector3D(1d, 0d, 0d)));+ Assert.True(AnalyticDisplayQuery.TryIntersectBody(body, exteriorRay, out var exteriorHit));+ Assert.Equal(SurfaceGeometryKind.Plane, exteriorHit.SurfaceKind);++ var openingRay = new Ray3D(new Point3D(0d, 0d, 20d), Direction3D.Create(new Vector3D(0d, 0d, -1d)));+ Assert.False(AnalyticDisplayQuery.TryIntersectBody(body, openingRay, out _));++ var sideRay = new Ray3D(new Point3D(0d, 0d, 6d), Direction3D.Create(new Vector3D(1d, 0d, 0d)));+ Assert.True(AnalyticDisplayQuery.TryIntersectBody(body, sideRay, out var sideHit));+ Assert.Equal(SurfaceGeometryKind.Cone, sideHit.SurfaceKind);++ Assert.True(AnalyticDisplayQuery.TryIntersectBody(body, sideRay, out var sideHitRepeat));+ Assert.Equal(sideHit.Distance, sideHitRepeat.Distance, 12);+ Assert.Equal(sideHit.FaceId, sideHitRepeat.FaceId);+ }++ [Fact]+ public void BodyLevelNearestHit_BoxSphereCavity_DoesNotExposeCavityToExteriorRays()+ {+ var body = CreateBoxSphereCavity();++ var exteriorRay = new Ray3D(new Point3D(-30d, 0d, 0d), Direction3D.Create(new Vector3D(1d, 0d, 0d)));+ Assert.True(AnalyticDisplayQuery.TryIntersectBody(body, exteriorRay, out var exteriorHit));+ Assert.Equal(SurfaceGeometryKind.Plane, exteriorHit.SurfaceKind);++ var innerRay = new Ray3D(new Point3D(0d, 0d, 0d), Direction3D.Create(new Vector3D(1d, 0d, 0d)));+ Assert.True(AnalyticDisplayQuery.TryIntersectBody(body, innerRay, out var innerHit));+ Assert.Equal(SurfaceGeometryKind.Sphere, innerHit.SurfaceKind);+ }++ [Fact]+ public void BodyLevelNearestHit_BoxBooleanRegression_StillResolvesNearestHit()+ {+ var left = BrepBooleanBoxRecognition.CreateBoxFromExtents(new AxisAlignedBoxExtents(-2d, 2d, -2d, 2d, -2d, 2d)).Value;+ var right = BrepBooleanBoxRecognition.CreateBoxFromExtents(new AxisAlignedBoxExtents(1d, 3d, -2d, 2d, -2d, 2d)).Value;+ var result = BrepBoolean.Intersect(left, right);+ Assert.True(result.IsSuccess);++ var ray = new Ray3D(new Point3D(-5d, 0d, 0d), Direction3D.Create(new Vector3D(1d, 0d, 0d)));+ Assert.True(AnalyticDisplayQuery.TryIntersectBody(result.Value, ray, out var hit));+ Assert.Equal(SurfaceGeometryKind.Plane, hit.SurfaceKind);+ Assert.Equal(1d, hit.Position.X, 12);+ }+private static Aetheris.Kernel.Core.Topology.FaceId FindFaceByKind(BrepBody body, Aetheris.Kernel.Core.Geometry.SurfaceGeometryKind kind){foreach (var face in body.Topology.Faces.OrderBy(f => f.Id.Value))@@ -152,4 +230,116 @@ public sealed class AnalyticDisplayQueryTeststhrow new InvalidOperationException($"Face kind {kind} not found.");}++ private static BrepBody CreateBoxCylinderThroughHole()+ {+ var left = BrepBooleanBoxRecognition.CreateBoxFromExtents(new AxisAlignedBoxExtents(-20d, 20d, -15d, 15d, 0d, 12d)).Value;+ var right = TransformBody(BrepPrimitives.CreateCylinder(4d, 20d).Value, Transform3D.CreateTranslation(new Vector3D(3d, -2d, 6d)));+ var result = BrepBoolean.Subtract(left, right);+ Assert.True(result.IsSuccess);+ return result.Value;+ }++ private static BrepBody CreateBoxConeThroughHole()+ {+ var left = BrepBooleanBoxRecognition.CreateBoxFromExtents(new AxisAlignedBoxExtents(-12d, 12d, -10d, 10d, 0d, 10d)).Value;+ var right = CreateCone(bottomRadius: 6d, topRadius: 0d, height: 20d);+ var result = BrepBoolean.Subtract(left, right);+ Assert.True(result.IsSuccess);+ return result.Value;+ }++ private static BrepBody CreateBoxSphereCavity()+ {+ var left = BrepBooleanBoxRecognition.CreateBoxFromExtents(new AxisAlignedBoxExtents(-10d, 10d, -10d, 10d, -10d, 10d)).Value;+ var right = TransformBody(BrepPrimitives.CreateSphere(6d).Value, Transform3D.CreateTranslation(new Vector3D(0d, 0d, 0d)));+ var result = BrepBoolean.Subtract(left, right);+ Assert.True(result.IsSuccess);+ return result.Value;+ }++ private static BrepBody CreateCone(double bottomRadius, double topRadius, double height)+ {+ var frame = new ExtrudeFrame3D(+ origin: Point3D.Origin,+ normal: Direction3D.Create(new Vector3D(0d, 0d, 1d)),+ uAxis: Direction3D.Create(new Vector3D(1d, 0d, 0d)));+ var axis = new RevolveAxis3D(Point3D.Origin, new Vector3D(0d, 0d, 1d));++ var result = BrepRevolve.Create(+ [+ new ProfilePoint2D(bottomRadius, 0d),+ new ProfilePoint2D(topRadius, height)+ ],+ frame,+ axis);++ Assert.True(result.IsSuccess);+ return result.Value;+ }++ private static BrepBody TransformBody(BrepBody body, Transform3D transform)+ {+ var geometry = new BrepGeometryStore();+ foreach (var curveEntry in body.Geometry.Curves)+ {+ geometry.AddCurve(curveEntry.Key, curveEntry.Value.Kind switch+ {+ CurveGeometryKind.Line3 => CurveGeometry.FromLine(new Line3Curve(+ transform.Apply(curveEntry.Value.Line3!.Value.Origin),+ transform.Apply(curveEntry.Value.Line3.Value.Direction))),+ CurveGeometryKind.Circle3 => CurveGeometry.FromCircle(new Circle3Curve(+ transform.Apply(curveEntry.Value.Circle3!.Value.Center),+ transform.Apply(curveEntry.Value.Circle3.Value.Normal),+ curveEntry.Value.Circle3.Value.Radius,+ transform.Apply(curveEntry.Value.Circle3.Value.XAxis))),+ _ => curveEntry.Value+ });+ }++ foreach (var surfaceEntry in body.Geometry.Surfaces)+ {+ geometry.AddSurface(surfaceEntry.Key, surfaceEntry.Value.Kind switch+ {+ SurfaceGeometryKind.Plane => SurfaceGeometry.FromPlane(new PlaneSurface(+ transform.Apply(surfaceEntry.Value.Plane!.Value.Origin),+ transform.Apply(surfaceEntry.Value.Plane.Value.Normal),+ transform.Apply(surfaceEntry.Value.Plane.Value.UAxis))),+ SurfaceGeometryKind.Cylinder => SurfaceGeometry.FromCylinder(new CylinderSurface(+ transform.Apply(surfaceEntry.Value.Cylinder!.Value.Origin),+ transform.Apply(surfaceEntry.Value.Cylinder.Value.Axis),+ surfaceEntry.Value.Cylinder.Value.Radius,+ transform.Apply(surfaceEntry.Value.Cylinder.Value.XAxis))),+ SurfaceGeometryKind.Cone => SurfaceGeometry.FromCone(new ConeSurface(+ transform.Apply(surfaceEntry.Value.Cone!.Value.PlacementOrigin),+ transform.Apply(surfaceEntry.Value.Cone.Value.Axis),+ surfaceEntry.Value.Cone.Value.PlacementRadius,+ surfaceEntry.Value.Cone.Value.SemiAngleRadians,+ transform.Apply(surfaceEntry.Value.Cone.Value.ReferenceAxis))),+ SurfaceGeometryKind.Torus => SurfaceGeometry.FromTorus(new TorusSurface(+ transform.Apply(surfaceEntry.Value.Torus!.Value.Center),+ transform.Apply(surfaceEntry.Value.Torus.Value.Axis),+ surfaceEntry.Value.Torus.Value.MajorRadius,+ surfaceEntry.Value.Torus.Value.MinorRadius,+ transform.Apply(surfaceEntry.Value.Torus.Value.XAxis))),+ SurfaceGeometryKind.Sphere => SurfaceGeometry.FromSphere(new SphereSurface(+ transform.Apply(surfaceEntry.Value.Sphere!.Value.Center),+ transform.Apply(surfaceEntry.Value.Sphere.Value.Axis),+ surfaceEntry.Value.Sphere.Value.Radius,+ transform.Apply(surfaceEntry.Value.Sphere.Value.XAxis))),+ _ => surfaceEntry.Value+ });+ }++ var vertexPoints = new Dictionary<Aetheris.Kernel.Core.Topology.VertexId, Point3D>();+ foreach (var vertex in body.Topology.Vertices)+ {+ if (body.TryGetVertexPoint(vertex.Id, out var point))+ {+ vertexPoints[vertex.Id] = transform.Apply(point);+ }+ }++ return new BrepBody(body.Topology, geometry, body.Bindings, vertexPoints, body.SafeBooleanComposition, body.ShellRepresentation);+ }}diff --git a/Aetheris.Kernel.Core/Brep/Queries/AnalyticDisplayQuery.cs b/Aetheris.Kernel.Core/Brep/Queries/AnalyticDisplayQuery.csindex d4e7bc16..174584a3 100644--- a/Aetheris.Kernel.Core/Brep/Queries/AnalyticDisplayQuery.cs+++ b/Aetheris.Kernel.Core/Brep/Queries/AnalyticDisplayQuery.cs@@ -23,37 +23,46 @@ public static class AnalyticDisplayQuery{var context = tolerance ?? ToleranceContext.Default;hit = default;- var bodyEntity = body.Topology.Bodies.OrderBy(b => b.Id.Value).FirstOrDefault();- if (bodyEntity is not Body resolvedBody)- {- return false;- }-- var faceIds = resolvedBody.ShellIds+ var faceIds = GetOrderedShellIds(body).SelectMany(shellId => body.Topology.GetShell(shellId).FaceIds).Distinct().OrderBy(id => id.Value).ToArray();-- var found = false;- AnalyticRayHit best = default;+ var candidates = new List<AnalyticRayHit>(faceIds.Length);foreach (var faceId in faceIds){- if (TryIntersectFace(body, faceId, ray, out var candidate, maxDistance, context)- && (!found || candidate.Distance < best.Distance - context.Linear || (ToleranceMath.AlmostEqual(candidate.Distance, best.Distance, context) && candidate.FaceId.Value < best.FaceId.Value)))+ if (TryIntersectFace(body, faceId, ray, out var candidate, maxDistance, context)){- found = true;- best = candidate;+ candidates.Add(candidate);}}- if (!found)+ if (candidates.Count == 0){return false;}- hit = best;+ var ordered = candidates+ .OrderBy(candidate => candidate.Distance)+ .ThenBy(candidate => candidate.FaceId.Value)+ .ToArray();++ var sampleOffset = double.Max(context.Linear * 32d, 1e-6d);+ foreach (var candidate in ordered)+ {+ var beforePoint = ray.PointAt(double.Max(0d, candidate.Distance - sampleOffset));+ var afterPoint = ray.PointAt(candidate.Distance + sampleOffset);+ var beforeInside = IsPointInMaterial(body, beforePoint, context);+ var afterInside = IsPointInMaterial(body, afterPoint, context);+ if (beforeInside != afterInside)+ {+ hit = candidate;+ return true;+ }+ }++ hit = ordered[0];return true;}@@ -374,64 +383,94 @@ public static class AnalyticDisplayQueryreturn true;}- var circularBoundary = false;- var circleCenter = Point3D.Origin;- var circleRadius = 0d;+ var circularBoundaries = new List<(LoopId LoopId, Point3D Center, double Radius)>();foreach (var loopId in face.LoopIds){var loop = body.Topology.GetLoop(loopId);+ var loopHasOnlyCircles = loop.CoedgeIds.Count > 0;+ Point3D? loopCenter = null;+ double? loopRadius = null;+foreach (var coedgeId in loop.CoedgeIds){var edgeId = body.Topology.GetCoedge(coedgeId).EdgeId;if (!body.Bindings.TryGetEdgeBinding(edgeId, out var edgeBinding)|| !body.Geometry.TryGetCurve(edgeBinding.CurveGeometryId, out var curve)){+ loopHasOnlyCircles = false;continue;}- if (curve.Kind == CurveGeometryKind.Circle3 && curve.Circle3 is { } circle)+ if (curve is { Kind: CurveGeometryKind.Circle3, Circle3: { } circle }){- circularBoundary = true;- circleCenter = circle.Center;- circleRadius = circle.Radius;+ loopCenter ??= circle.Center;+ loopRadius ??= circle.Radius;+ continue;}++ loopHasOnlyCircles = false;}- }- if (circularBoundary)- {- var radial = point - circleCenter;- var height = radial.Dot(plane.Normal.ToVector());- var inPlaneRadial = radial - (plane.Normal.ToVector() * height);- return inPlaneRadial.Dot(inPlaneRadial) <= (circleRadius + tolerance.Linear) * (circleRadius + tolerance.Linear);+ if (loopHasOnlyCircles && loopCenter.HasValue && loopRadius.HasValue)+ {+ circularBoundaries.Add((loopId, loopCenter.Value, loopRadius.Value));+ }}+ var inAxisAlignedFaceBounds = true;if (TryResolveAxisAlignedBoxBounds(body, out var min, out var max)){var normal = plane.Normal.ToVector();if (double.Abs(normal.X) > 0.9d){- return point.Y >= min.Y - tolerance.Linear && point.Y <= max.Y + tolerance.Linear+ inAxisAlignedFaceBounds = point.Y >= min.Y - tolerance.Linear && point.Y <= max.Y + tolerance.Linear&& point.Z >= min.Z - tolerance.Linear && point.Z <= max.Z + tolerance.Linear;}-- if (double.Abs(normal.Y) > 0.9d)+ else if (double.Abs(normal.Y) > 0.9d){- return point.X >= min.X - tolerance.Linear && point.X <= max.X + tolerance.Linear+ inAxisAlignedFaceBounds = point.X >= min.X - tolerance.Linear && point.X <= max.X + tolerance.Linear&& point.Z >= min.Z - tolerance.Linear && point.Z <= max.Z + tolerance.Linear;}-- if (double.Abs(normal.Z) > 0.9d)+ else if (double.Abs(normal.Z) > 0.9d){- return point.X >= min.X - tolerance.Linear && point.X <= max.X + tolerance.Linear+ inAxisAlignedFaceBounds = point.X >= min.X - tolerance.Linear && point.X <= max.X + tolerance.Linear&& point.Y >= min.Y - tolerance.Linear && point.Y <= max.Y + tolerance.Linear;}}+ if (!inAxisAlignedFaceBounds)+ {+ return false;+ }++ if (circularBoundaries.Count == 1 && face.LoopIds.Count == 1)+ {+ return IsPointInsideCircularBoundary(point, plane, circularBoundaries[0].Center, circularBoundaries[0].Radius, tolerance);+ }++ if (face.LoopIds.Count > 1 && circularBoundaries.Count > 0)+ {+ foreach (var boundary in circularBoundaries)+ {+ if (IsPointInsideCircularBoundary(point, plane, boundary.Center, boundary.Radius, tolerance))+ {+ return false;+ }+ }+ }+return true;}+ private static bool IsPointInsideCircularBoundary(Point3D point, PlaneSurface plane, Point3D center, double radius, ToleranceContext tolerance)+ {+ var radial = point - center;+ var height = radial.Dot(plane.Normal.ToVector());+ var inPlaneRadial = radial - (plane.Normal.ToVector() * height);+ return inPlaneRadial.Dot(inPlaneRadial) <= (radius + tolerance.Linear) * (radius + tolerance.Linear);+ }+private static bool TryResolveAxisAlignedBoxBounds(BrepBody body, out Point3D min, out Point3D max){min = default;@@ -600,4 +639,76 @@ public static class AnalyticDisplayQueryreturn candidates.Length == 0 ? double.NaN : candidates[0];}++ private static IReadOnlyList<ShellId> GetOrderedShellIds(BrepBody body)+ {+ if (body.ShellRepresentation is { } representation)+ {+ return representation.OrderedShellIds;+ }++ var topologyBody = body.Topology.Bodies.OrderBy(topologyBody => topologyBody.Id.Value).FirstOrDefault();+ return topologyBody?.ShellIds.OrderBy(shellId => shellId.Value).ToArray() ?? [];+ }++ private static bool IsPointInMaterial(BrepBody body, Point3D point, ToleranceContext tolerance)+ {+ var shellIds = GetOrderedShellIds(body);+ if (shellIds.Count == 0)+ {+ return false;+ }++ var outerShellId = shellIds[0];+ if (!IsPointInShell(body, outerShellId, point, tolerance))+ {+ return false;+ }++ for (var index = 1; index < shellIds.Count; index++)+ {+ if (IsPointInShell(body, shellIds[index], point, tolerance))+ {+ return false;+ }+ }++ return true;+ }++ private static bool IsPointInShell(BrepBody body, ShellId shellId, Point3D point, ToleranceContext tolerance)+ {+ var shell = body.Topology.GetShell(shellId);+ var probeDirection = Direction3D.Create(new Vector3D(1d, 0.3125d, 0.1875d));+ var probeRay = new Ray3D(point, probeDirection);+ var intersections = new List<double>(shell.FaceIds.Count);++ foreach (var faceId in shell.FaceIds)+ {+ if (TryIntersectFace(body, faceId, probeRay, out var hit, maxDistance: 1e6d, tolerance)+ && hit.Distance > tolerance.Linear * 4d)+ {+ intersections.Add(hit.Distance);+ }+ }++ if (intersections.Count == 0)+ {+ return false;+ }++ intersections.Sort();+ var uniqueCount = 0;+ double? previous = null;+ foreach (var distance in intersections)+ {+ if (!previous.HasValue || double.Abs(distance - previous.Value) > tolerance.Linear * 16d)+ {+ uniqueCount++;+ previous = distance;+ }+ }++ return (uniqueCount & 1) == 1;+ }}