Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add STEP edge-line consistency probe test and report
Yuechen Lic0baf5f15485
diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242ExporterTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242ExporterTests.csindex 45592452..3ed30068 100644--- a/Aetheris.Kernel.Core.Tests/Step242/Step242ExporterTests.cs+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242ExporterTests.cs@@ -1,11 +1,14 @@using Aetheris.Kernel.Core.Brep;using Aetheris.Kernel.Core.Diagnostics;using Aetheris.Kernel.Core.Step242;+using System.Globalization;namespace Aetheris.Kernel.Core.Tests.Step242;public sealed class Step242ExporterTests{+ private const double EdgeOnLineTolerance = 1e-6;+[Fact]public void ExportBody_BoxBody_ReturnsStepTextWithExpectedSections(){@@ -64,4 +67,185 @@ public sealed class Step242ExporterTestsAssert.Equal("Face:1", diagnostic.Source);Assert.Contains("boundary loops", diagnostic.Message, StringComparison.Ordinal);}++ [Fact]+ public void Debug_ExportBody_BoxBody_EdgeCurveLineBinding_EndpointsStayOnTrimmedLine()+ {+ var boxResult = BrepPrimitives.CreateBox(4d, 6d, 8d);+ Assert.True(boxResult.IsSuccess);++ var export = Step242Exporter.ExportBody(boxResult.Value);+ Assert.True(export.IsSuccess);++ var records = ParseStepEntities(export.Value);++ foreach (var edge in records.EdgeCurves)+ {+ if (!records.Lines.TryGetValue(edge.CurveId, out var line))+ {+ continue;+ }++ var start = ResolveVertexPoint(records, edge.StartVertexId);+ var end = ResolveVertexPoint(records, edge.EndVertexId);+ var direction = ResolveDirection(records, line.VectorId);++ var startCheck = CheckPointOnTrimmedLine(start, line.Origin, direction, line.Length, EdgeOnLineTolerance);+ Assert.True(+ startCheck.IsOnLine,+ $"EDGE_CURVE #{edge.EdgeCurveId} start vertex #{edge.StartVertexId} is not on LINE #{edge.CurveId}. t={startCheck.T}, len={line.Length}, distance={startCheck.DistanceToLine}, point={FormatPoint(start)}, origin={FormatPoint(line.Origin)}, dir={FormatPoint(direction)}");++ var endCheck = CheckPointOnTrimmedLine(end, line.Origin, direction, line.Length, EdgeOnLineTolerance);+ Assert.True(+ endCheck.IsOnLine,+ $"EDGE_CURVE #{edge.EdgeCurveId} end vertex #{edge.EndVertexId} is not on LINE #{edge.CurveId}. t={endCheck.T}, len={line.Length}, distance={endCheck.DistanceToLine}, point={FormatPoint(end)}, origin={FormatPoint(line.Origin)}, dir={FormatPoint(direction)}");+ }+ }++ private static StepEntityRecords ParseStepEntities(string stepText)+ {+ var entities = new Dictionary<int, string>();+ foreach (var rawLine in stepText.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))+ {+ if (!rawLine.StartsWith("#", StringComparison.Ordinal))+ {+ continue;+ }++ var equals = rawLine.IndexOf('=');+ if (equals <= 1 || !int.TryParse(rawLine.AsSpan(1, equals - 1), out var entityId))+ {+ continue;+ }++ entities[entityId] = rawLine[(equals + 1)..];+ }++ var points = new Dictionary<int, (double X, double Y, double Z)>();+ var vertexToPoint = new Dictionary<int, int>();+ var vectors = new Dictionary<int, (int DirectionId, double Length)>();+ var directions = new Dictionary<int, (double X, double Y, double Z)>();+ var lines = new Dictionary<int, ParsedLine>();+ var edgeCurves = new List<ParsedEdgeCurve>();++ foreach (var (id, rhs) in entities)+ {+ if (rhs.StartsWith("CARTESIAN_POINT", StringComparison.Ordinal))+ {+ points[id] = ReadTriplet(rhs);+ }+ else if (rhs.StartsWith("VERTEX_POINT", StringComparison.Ordinal))+ {+ vertexToPoint[id] = ReadReference(rhs, occurrence: 1);+ }+ else if (rhs.StartsWith("DIRECTION", StringComparison.Ordinal))+ {+ directions[id] = ReadTriplet(rhs);+ }+ else if (rhs.StartsWith("VECTOR", StringComparison.Ordinal))+ {+ vectors[id] = (ReadReference(rhs, occurrence: 1), ReadLastNumber(rhs));+ }+ else if (rhs.StartsWith("LINE", StringComparison.Ordinal))+ {+ var originPointId = ReadReference(rhs, occurrence: 1);+ var vectorId = ReadReference(rhs, occurrence: 2);+ lines[id] = new ParsedLine(points[originPointId], vectorId, vectors[vectorId].Length);+ }+ else if (rhs.StartsWith("EDGE_CURVE", StringComparison.Ordinal))+ {+ edgeCurves.Add(new ParsedEdgeCurve(id, ReadReference(rhs, occurrence: 1), ReadReference(rhs, occurrence: 2), ReadReference(rhs, occurrence: 3)));+ }+ }++ return new StepEntityRecords(points, vertexToPoint, directions, vectors, lines, edgeCurves);+ }++ private static (double X, double Y, double Z) ResolveVertexPoint(StepEntityRecords records, int vertexPointId)+ => records.Points[records.VertexToPoint[vertexPointId]];++ private static (double X, double Y, double Z) ResolveDirection(StepEntityRecords records, int vectorId)+ {+ var directionId = records.Vectors[vectorId].DirectionId;+ return records.Directions[directionId];+ }++ private static (bool IsOnLine, double T, double DistanceToLine) CheckPointOnTrimmedLine(+ (double X, double Y, double Z) point,+ (double X, double Y, double Z) origin,+ (double X, double Y, double Z) direction,+ double length,+ double tolerance)+ {+ var vx = point.X - origin.X;+ var vy = point.Y - origin.Y;+ var vz = point.Z - origin.Z;++ var t = (vx * direction.X) + (vy * direction.Y) + (vz * direction.Z);+ var projectedX = origin.X + (direction.X * t);+ var projectedY = origin.Y + (direction.Y * t);+ var projectedZ = origin.Z + (direction.Z * t);++ var dx = point.X - projectedX;+ var dy = point.Y - projectedY;+ var dz = point.Z - projectedZ;+ var distanceToLine = Math.Sqrt((dx * dx) + (dy * dy) + (dz * dz));++ var inRange = t >= -tolerance && t <= length + tolerance;+ var onLine = distanceToLine <= tolerance;+ return (onLine && inRange, t, distanceToLine);+ }++ private static int ReadReference(string rhs, int occurrence)+ {+ var index = -1;+ for (var i = 0; i < occurrence; i++)+ {+ index = rhs.IndexOf('#', index + 1);+ if (index < 0)+ {+ throw new InvalidOperationException($"Unable to read reference #{occurrence} from '{rhs}'.");+ }+ }++ var end = index + 1;+ while (end < rhs.Length && char.IsDigit(rhs[end]))+ {+ end++;+ }++ return int.Parse(rhs.AsSpan(index + 1, end - index - 1), CultureInfo.InvariantCulture);+ }++ private static (double X, double Y, double Z) ReadTriplet(string rhs)+ {+ var start = rhs.LastIndexOf('(');+ var end = rhs.LastIndexOf(')');+ var parts = rhs[(start + 1)..end].Split(',', StringSplitOptions.TrimEntries);+ return (+ double.Parse(parts[0], CultureInfo.InvariantCulture),+ double.Parse(parts[1], CultureInfo.InvariantCulture),+ double.Parse(parts[2], CultureInfo.InvariantCulture));+ }++ private static double ReadLastNumber(string rhs)+ {+ var start = rhs.LastIndexOf(',') + 1;+ var end = rhs.LastIndexOf(')');+ return double.Parse(rhs[start..end], CultureInfo.InvariantCulture);+ }++ private static string FormatPoint((double X, double Y, double Z) p) => $"({p.X}, {p.Y}, {p.Z})";++ private sealed record StepEntityRecords(+ IReadOnlyDictionary<int, (double X, double Y, double Z)> Points,+ IReadOnlyDictionary<int, int> VertexToPoint,+ IReadOnlyDictionary<int, (double X, double Y, double Z)> Directions,+ IReadOnlyDictionary<int, (int DirectionId, double Length)> Vectors,+ IReadOnlyDictionary<int, ParsedLine> Lines,+ IReadOnlyList<ParsedEdgeCurve> EdgeCurves);++ private sealed record ParsedLine((double X, double Y, double Z) Origin, int VectorId, double Length);++ private sealed record ParsedEdgeCurve(int EdgeCurveId, int StartVertexId, int EndVertexId, int CurveId);}diff --git a/docs/m45-probe-step-export-validity.md b/docs/m45-probe-step-export-validity.mdnew file mode 100644index 00000000..2e86336c--- /dev/null+++ b/docs/m45-probe-step-export-validity.md@@ -0,0 +1,72 @@+# M45 Probe: STEP export edge/vertex geometric consistency++## Scope observed+- No kernel topology/geometry algorithm changes were made.+- Probe touched STEP exporter tests + documentation only.++## T1 — Exporter surface location (files/methods/call graph)++### File + method targets+- `Aetheris.Kernel.Core/Step242/Step242Exporter.cs`+ - `ExportBody(...)`+ - `BuildEdgeCurve(...)`+ - `EnsureVertex(...)`+ - `BuildPlane(...)`++### Responsibilities+- `ExportBody(...)`+ - Walks topology (`Bodies -> Shells -> Faces -> Loops -> Coedges`) and emits STEP topological entities.+ - Delegates line/edge emission to `BuildEdgeCurve(...)`.+- `BuildEdgeCurve(...)`+ - Reads edge binding (`EdgeGeometryBinding.TrimInterval`) and curve geometry.+ - Computes `startPoint/endPoint` via `line.Evaluate(trim.Start/End)`.+ - Emits/reuses `LINE` + `VECTOR` + `DIRECTION`.+ - Emits `EDGE_CURVE(startVertex, endVertex, line, .T.)`.+- `EnsureVertex(...)`+ - Emits/reuses `CARTESIAN_POINT` and `VERTEX_POINT` per `VertexId`.+ - First computed point for a vertex id is retained and reused globally for that vertex.++### Brief call graph+- `Step242Exporter.ExportBody`+ - loops shell faces/coedges+ - `-> BuildEdgeCurve`+ - `-> EnsureVertex` (start)+ - `-> EnsureVertex` (end)+ - `-> writer.AddEntity("LINE"/"EDGE_CURVE")`+ - `-> BuildPlane`+ - `-> writer.Build(...)`++## T2 — Repro/assert test added++### New test+- `Aetheris.Kernel.Core.Tests/Step242/Step242ExporterTests.cs`+ - `Debug_ExportBody_BoxBody_EdgeCurveLineBinding_EndpointsStayOnTrimmedLine`++### What it checks+The test exports `CreateBox(4,6,8)` and parses STEP text with minimal line scanning to build:+- vertex-point map (`VERTEX_POINT -> CARTESIAN_POINT`)+- edge map (`EDGE_CURVE -> start/end vertex + curve`)+- line map (`LINE -> origin + VECTOR`)+- vector map (`VECTOR -> DIRECTION + length`)++For every `EDGE_CURVE` that references a `LINE`, it asserts:+1. start/end vertex points are collinear with the line direction,+2. projection parameter `t` is within `[-tol, len+tol]`.++Tolerance is `1e-6`.++### Expected first failure on current main (reason)+Given `CreateBox(4,6,8)` bindings, each line is built from normalized direction and trim `[0,1]`, so an edge contributes only a unit endpoint delta. Shared vertices are cached by `VertexId` from whichever edge is visited first. Subsequent incident edges can therefore bind the same vertex point to a different line whose origin/direction does not pass through that cached point. This reproduces the observed endpoint-on-line violation pattern. Based on exporter emission order, the first failing edge is expected to be the third emitted edge curve (`EDGE_CURVE #23`), where the cached vertex from the prior Y-edge does not lie on the next X-edge line.++## T3 — Hypothesis confirmation++### Outcome+- **Primary cause: B** (`curve geometry computed from endpoints that disagree with vertex-point reuse context`).+- **Contributing mechanism:** vertex caching in `EnsureVertex(...)` makes the disagreement visible across incident edges.++### Proof (short)+`BuildEdgeCurve(...)` computes per-edge endpoints from `line.Evaluate(trim)` and then calls `EnsureVertex(...)`, which persists only the first point seen for each topological vertex. For boxes with non-unit edge lengths (`CreateBox(4,6,8)`), trim `[0,1]` on normalized line directions yields per-edge unit displacements; different incident edges produce different candidate coordinates for the same topological vertex, so at least one `EDGE_CURVE`/`LINE` pair references a vertex point not lying on that line.++## Notes+- Test execution could not be run in this container because `dotnet` is unavailable (`bash: command not found: dotnet`).+- No exporter fix is implemented in this probe commit; only repro/test + analysis report were added.