Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Validate oriented mesh topology after STL float32 conversion
Yuechen Lie1310ce2d581
diff --git a/Aetheris.CLI.Tests/StlIntegrityCommandTests.cs b/Aetheris.CLI.Tests/StlIntegrityCommandTests.csnew file mode 100644index 00000000..d3f93f3d--- /dev/null+++ b/Aetheris.CLI.Tests/StlIntegrityCommandTests.cs@@ -0,0 +1,51 @@+using System.Text.Json;+using Aetheris.Kernel.Core.Math;++namespace Aetheris.CLI.Tests;++public sealed class StlIntegrityCommandTests+{+ [Fact]+ public void Ctc01SerializedStlHasOppositeEdgeUsesAndOriginIndependentVolume()+ {+ var root = new DirectoryInfo(AppContext.BaseDirectory);+ while (root is not null && !File.Exists(Path.Combine(root.FullName, "Aetheris.slnx"))) root = root.Parent;+ var folder = Path.Combine(root!.FullName, "artifacts/local/stl-integrity/tests"); Directory.CreateDirectory(folder);+ var output = Path.Combine(folder, Guid.NewGuid() + ".stl");+ try+ {+ var stdout = new StringWriter(); var stderr = new StringWriter();+ // A real CLI import/serialization is required here: checking the+ // memoized BRep or the production validator cannot qualify STL bytes.+ var exit = Aetheris.CLI.CliRunner.Run(["mesh", Path.Combine(root.FullName,+ "testdata/step242/nist/CTC/nist_ctc_01_asme1_ap242-e1.stp"), "--format", "stl", "--output", output, "--json"], stdout, stderr);+ Assert.True(exit == 0, stdout + stderr.ToString());+ using var json = JsonDocument.Parse(stdout.ToString()); var report = json.RootElement;+ Assert.True(report.GetProperty("watertight").GetBoolean());+ Assert.True(report.GetProperty("consistentlyOriented").GetBoolean());+ Assert.Equal(0, report.GetProperty("orientationConflictEdgeCount").GetInt32());++ using var reader = new BinaryReader(File.OpenRead(output));+ reader.ReadBytes(80); var count = reader.ReadUInt32();+ Assert.Equal(84L + 50L * count, reader.BaseStream.Length);+ var triangles = new List<Point3D[]>();+ var edges = new Dictionary<(Point3D, Point3D), int>();+ for (var i = 0; i < count; i++)+ {+ reader.ReadBytes(12); var triangle = new[] { ReadPoint(), ReadPoint(), ReadPoint() }; reader.ReadUInt16();+ triangles.Add(triangle);+ for (var j = 0; j < 3; j++)+ {+ var edge = (triangle[j], triangle[(j + 1) % 3]); edges[edge] = edges.GetValueOrDefault(edge) + 1;+ }+ }+ Assert.All(edges, pair => Assert.Equal(pair.Value, edges.GetValueOrDefault((pair.Key.Item2, pair.Key.Item1))));+ var volumes = new[] { new Point3D(0, 0, 0), new Point3D(1000, 2000, 3000), new Point3D(-1000, -2000, -3000) }+ .Select(origin => triangles.Sum(t => (t[0] - origin).Dot((t[1] - origin).Cross(t[2] - origin)) / 6)).ToArray();+ Assert.All(volumes, volume => Assert.InRange(double.Abs(volume - report.GetProperty("meshSignedVolumeMm3").GetDouble()), 0, .01));+ Assert.InRange(volumes[0], 14_640_000, 14_655_000);+ Point3D ReadPoint() => new(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle());+ }+ finally { if (File.Exists(output)) File.Delete(output); }+ }+}diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 97e8ce5a..df452aff 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -1483,6 +1483,8 @@ Model CanonicalPanel {vertexCount = obj.VertexCount, normalCount = obj.NormalCount, textureCoordinateCount = obj.TextureCoordinateCount,finalTriangleCount = objTopology.TriangleCount, watertight,crackCount = objTopology.CrackCount, nonManifoldEdgeCount = objTopology.NonManifoldEdgeCount,+ orientationConflictEdgeCount = objTopology.OrientationConflictEdgeCount,+ consistentlyOriented = objTopology.IsConsistentlyOriented,duplicateTriangleCount = objTopology.DuplicateTriangleCount, zeroAreaTriangleCount = objTopology.ZeroAreaTriangleCount,connected = objTopology.IsConnected, outwardOriented = objTopology.IsOutwardOriented,foreignTrimResolutionCount = document.ForeignTrimResolutions?.Count ?? 0,@@ -1512,11 +1514,12 @@ Model CanonicalPanel {}var loweringWatch = System.Diagnostics.Stopwatch.StartNew();if (!SurfaceMeshIrTessellator.TryLowerToTriangleMesh(document, out var mesh, out var topology))- return WriteMeshFailure([$"SurfaceMeshIR could not lower the validated document to a watertight TriangleMesh for STL: cracks={topology.CrackCount}, nonmanifold={topology.NonManifoldEdgeCount}, duplicates={topology.DuplicateTriangleCount}, zeroArea={topology.ZeroAreaTriangleCount}, connected={topology.IsConnected}, outward={topology.IsOutwardOriented}."], json, fullInput, stdout, stderr);- BinaryStlExporter.Export(outputPath, mesh);+ return WriteMeshFailure([$"SurfaceMeshIR could not lower the validated document to a watertight TriangleMesh for STL: cracks={topology.CrackCount}, nonmanifold={topology.NonManifoldEdgeCount}, orientationConflicts={topology.OrientationConflictEdgeCount}, duplicates={topology.DuplicateTriangleCount}, zeroArea={topology.ZeroAreaTriangleCount}, connected={topology.IsConnected}, outward={topology.IsOutwardOriented}."], json, fullInput, stdout, stderr);+ try { BinaryStlExporter.Export(outputPath, mesh, out topology); }+ catch (InvalidOperationException error) { return WriteMeshFailure([error.Message], json, fullInput, stdout, stderr); }loweringWatch.Stop();var stlBytes = new FileInfo(outputPath).Length;- if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "mesh", success = true, pipeline = "SurfaceMeshIR", input = fullInput, outputPath, format = "binary-stl", patchCount = document.Metrics.PatchCount, cellCount = document.Metrics.CellCount, quadCount = document.Metrics.QuadCount, triangleCount = topology.TriangleCount, vertexCount = topology.VertexCount, watertight = topology.IsWatertight, maxChordalDeviation = document.Metrics.MaxChordalDeviation, normalDeviation = document.Metrics.MaxNormalDeviation, timingsMilliseconds = new { brepImport = importWatch.Elapsed.TotalMilliseconds, surfaceMeshIr = meshIrWatch.Elapsed.TotalMilliseconds, triangleLoweringAndStlSerialization = loweringWatch.Elapsed.TotalMilliseconds }, deterministicHash = mesh.DeterministicHash, bytes = stlBytes }, JsonOptions));+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "mesh", success = true, pipeline = "SurfaceMeshIR", input = fullInput, outputPath, format = "binary-stl", patchCount = document.Metrics.PatchCount, cellCount = document.Metrics.CellCount, quadCount = document.Metrics.QuadCount, triangleCount = topology.TriangleCount, vertexCount = topology.VertexCount, watertight = topology.IsWatertight, orientationConflictEdgeCount = topology.OrientationConflictEdgeCount, consistentlyOriented = topology.IsConsistentlyOriented, outwardOriented = topology.IsOutwardOriented, meshSignedVolumeMm3 = topology.HasValidSignedVolume ? (double?)topology.SignedVolume : null, maxChordalDeviation = document.Metrics.MaxChordalDeviation, normalDeviation = document.Metrics.MaxNormalDeviation, timingsMilliseconds = new { brepImport = importWatch.Elapsed.TotalMilliseconds, surfaceMeshIr = meshIrWatch.Elapsed.TotalMilliseconds, triangleLoweringAndStlSerialization = loweringWatch.Elapsed.TotalMilliseconds }, deterministicHash = mesh.DeterministicHash, bytes = stlBytes }, JsonOptions));else stdout.WriteLine($"SurfaceMeshIR STL: {outputPath}\nTriangles: {topology.TriangleCount}; watertight: {topology.IsWatertight}; max chordal error: {document.Metrics.MaxChordalDeviation:R}");return 0;}diff --git a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SurfaceMeshIrTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SurfaceMeshIrTests.csindex cabf72dc..12a0f94e 100644--- a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SurfaceMeshIrTests.cs+++ b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/SurfaceMeshIrTests.cs@@ -121,7 +121,7 @@ public sealed class SurfaceMeshIrTestsAssert.Equal(6, charts.Length);Assert.All(charts, chart => Assert.All(chart.Cells, cell => Assert.IsType<QuadCell>(cell)));Assert.Contains(charts.SelectMany(chart => chart.Cells).SelectMany(cell => cell.VertexIds).GroupBy(id => id), group => group.Count() >= 4);- Assert.True(SurfaceMeshIrTessellator.TryLowerToTriangleMesh(document, out var mesh, out var topology));+ Assert.True(SurfaceMeshIrTessellator.TryLowerToTriangleMesh(document, out var mesh, out var topology), topology.ToString());Assert.True(topology.IsWatertight);Assert.All(mesh.Normals, normal => Assert.True(double.Abs(normal.Length - 1d) < 1e-9d));}@@ -205,8 +205,10 @@ public sealed class SurfaceMeshIrTestsAssert.Equal(2, rings.Length);Assert.All(rings, ring => Assert.Equal(ring.Samples[0].Id, ring.Samples[^1].Id));Assert.True(SurfaceMeshIrValidator.TryValidate(document, out var irFailure), irFailure);- Assert.True(SurfaceMeshIrTessellator.TryLowerToTriangleMesh(document, out var mesh, out var topology));+ Assert.True(SurfaceMeshIrTessellator.TryLowerToTriangleMesh(document, out var mesh, out var topology), topology.ToString());Assert.True(topology.IsWatertight);+ Assert.InRange(topology.SignedVolume, 40d * 30d * 4d - 36d * double.Pi - 2,+ 40d * 30d * 4d - 36d * double.Pi + 2);Assert.True(topology.IsOutwardOriented);Assert.NotEmpty(mesh.HardEdges);var legacy = BrepDisplayTessellator.TessellateLegacyForComparison(body.Value);@@ -324,7 +326,7 @@ public sealed class SurfaceMeshIrTests{var body = BrepBoolean.Subtract(BrepPrimitives.CreateBox(20d, 20d, 2d).Value, BrepPrimitives.CreateCylinder(2d, 6d).Value).Value;Assert.True(SurfaceMeshIrTessellator.TryBuild(body, SurfaceMeshPolicy.FromDisplayOptions(DisplayTessellationOptions.Default), out var document));- Assert.True(SurfaceMeshIrTessellator.TryLowerToTriangleMesh(document, out var mesh, out _));+ Assert.True(SurfaceMeshIrTessellator.TryLowerToTriangleMesh(document, out var mesh, out var topology), topology.ToString());var path = Path.Combine(Path.GetTempPath(), $"aetheris-{Guid.NewGuid():N}.stl");try{diff --git a/Aetheris.Kernel.Core.Tests/Brep/Tessellation/TriangleMeshIntegrityTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/TriangleMeshIntegrityTests.csnew file mode 100644index 00000000..722bd657--- /dev/null+++ b/Aetheris.Kernel.Core.Tests/Brep/Tessellation/TriangleMeshIntegrityTests.cs@@ -0,0 +1,87 @@+using Aetheris.Kernel.Core.Brep.Tessellation;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Tests.Step242;++namespace Aetheris.Kernel.Core.Tests.Brep.Tessellation;++public sealed class TriangleMeshIntegrityTests+{+ private static TriangleMesh Tetrahedron() => new(+ [new(0, 0, 0), new(2, 0, 0), new(0, 2, 0), new(0, 0, 2)], [],+ [0, 2, 1, 0, 1, 3, 0, 3, 2, 1, 2, 3], new HashSet<(int, int)>(), "test");++ [Fact]+ public void PositiveVolumeAndTwoUsesPerEdgeDoNotProveOrientation()+ {+ var mesh = Tetrahedron(); var indices = mesh.TriangleIndices.ToArray();+ (indices[1], indices[2]) = (indices[2], indices[1]);+ Assert.False(TriangleMeshValidator.TryValidateClosed(mesh with { TriangleIndices = indices }, out var report, out var failure));+ Assert.Equal(0, report.CrackCount); Assert.Equal(0, report.NonManifoldEdgeCount);+ Assert.True(report.SignedVolume > 0);+ Assert.Equal(3, report.OrientationConflictEdgeCount);+ Assert.False(report.IsOutwardOriented); Assert.False(report.HasValidSignedVolume);+ Assert.Contains("orientationConflicts=3", failure);+ }++ [Fact]+ public void ClosedVolumeRemainsStableFarFromWorldOrigin()+ {+ var mesh = Tetrahedron();+ foreach (var translation in new[] { new Vector3D(0, 0, 0), new Vector3D(1e12, -1e12, 1e12) })+ {+ var moved = mesh with { Positions = mesh.Positions.Select(p => p + translation).ToArray() };+ Assert.True(TriangleMeshValidator.TryValidateClosed(moved, out var report, out var failure), failure);+ Assert.Equal(8d / 6, report.SignedVolume, 12);+ Assert.True(report.IsConsistentlyOriented); Assert.True(report.HasValidSignedVolume);+ }+ }++ [Fact]+ public void EntirelyInwardClosedMeshIsNotReportedOutward()+ {+ var mesh = Tetrahedron();+ var indices = mesh.TriangleIndices.Chunk(3).SelectMany(t => new[] { t[0], t[2], t[1] }).ToArray();+ Assert.False(TriangleMeshValidator.TryValidateClosed(mesh with { TriangleIndices = indices }, out var report, out _));+ Assert.True(report.IsConsistentlyOriented); Assert.True(report.HasValidSignedVolume);+ Assert.False(report.IsOutwardOriented); Assert.True(report.SignedVolume < 0);+ }++ [Fact]+ public void StlPrecisionFailureCannotReplaceAnExistingFile()+ {+ var folder = Step242Corpus.Path("artifacts/local/stl-integrity/tests"); Directory.CreateDirectory(folder);+ var file = Path.Combine(folder, Guid.NewGuid() + ".stl");+ File.WriteAllText(file, "preserve previous artifact");+ try+ {+ var mesh = Tetrahedron();+ mesh = mesh with { Positions = mesh.Positions.Select(p => p + new Vector3D(1e9, 1e9, 1e9)).ToArray() };+ var error = Assert.Throws<InvalidOperationException>(() => BinaryStlExporter.Export(file, mesh));+ Assert.Contains("float32", error.Message);+ Assert.Equal("preserve previous artifact", File.ReadAllText(file));+ }+ finally { File.Delete(file); }+ }++ [Fact]+ [Trait("Category", "SlowCorpus")]+ public void Ctc01HasOppositeDirectedUsesAndOriginIndependentVolume()+ {+ var body = Step242Corpus.Body("testdata/step242/nist/CTC/nist_ctc_01_asme1_ap242-e1.stp");+ Assert.True(SurfaceMeshIrTessellator.TryBuild(body, SurfaceMeshPolicy.FromDisplayOptions(DisplayTessellationOptions.Default), out var document, out var failure), failure);+ Assert.True(SurfaceMeshIrTessellator.TryLowerToTriangleMesh(document, out var mesh, out var report));+ Assert.Equal(0, report.OrientationConflictEdgeCount);+ var edges = mesh.TriangleIndices.Chunk(3).SelectMany(t => new[] { (t[0], t[1]), (t[1], t[2]), (t[2], t[0]) })+ .GroupBy(e => e).ToDictionary(g => g.Key, g => g.Count());+ Assert.All(edges, pair => Assert.Equal(pair.Value, edges.GetValueOrDefault((pair.Key.Item2, pair.Key.Item1))));+ foreach (var origin in new[] { new Point3D(0, 0, 0), new Point3D(1000, 2000, 3000), new Point3D(-1000, -2000, -3000) })+ {+ var volume = mesh.TriangleIndices.Chunk(3).Sum(t => (mesh.Positions[t[0]] - origin)+ .Dot((mesh.Positions[t[1]] - origin).Cross(mesh.Positions[t[2]] - origin)) / 6);+ Assert.InRange(double.Abs(volume - report.SignedVolume), 0, .001);+ }+ // Frozen independent STL witness: the old mixed winding produced 15.44M.+ Assert.InRange(report.SignedVolume, 14_640_000, 14_655_000);+ }+}+diff --git a/Aetheris.Kernel.Core/Brep/Boolean/BrepBooleanBoxCylinderHoleBuilder.cs b/Aetheris.Kernel.Core/Brep/Boolean/BrepBooleanBoxCylinderHoleBuilder.csindex 264be63d..3cc1ff5d 100644--- a/Aetheris.Kernel.Core/Brep/Boolean/BrepBooleanBoxCylinderHoleBuilder.cs+++ b/Aetheris.Kernel.Core/Brep/Boolean/BrepBooleanBoxCylinderHoleBuilder.cs@@ -939,7 +939,9 @@ public static class BrepBooleanBoxCylinderHoleBuilderbindings.AddEdgeBinding(new EdgeGeometryBinding(topology.TopCircle, topCurveId, new ParameterInterval(0d, 2d * double.Pi)));bindings.AddEdgeBinding(new EdgeGeometryBinding(topology.BottomCircle, bottomCurveId, new ParameterInterval(0d, 2d * double.Pi)));bindings.AddEdgeBinding(new EdgeGeometryBinding(topology.Seam, seamCurveId, new ParameterInterval(0d, geometryData.SeamLength)));- bindings.AddFaceBinding(new FaceGeometryBinding(holeFaces[i], surfaceId));+ // Subtraction walls face into the cavity, opposite the cylinder's+ // radial support normal. Do not rely on chart traversal to hide it.+ bindings.AddFaceBinding(new FaceGeometryBinding(holeFaces[i], surfaceId, IsAlignedWithSurface: false));if (topology.Hole.IsBlind){diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/BinaryStlExporter.cs b/Aetheris.Kernel.Core/Brep/Tessellation/BinaryStlExporter.csindex 8e76cbc2..3cd2b3c0 100644--- a/Aetheris.Kernel.Core/Brep/Tessellation/BinaryStlExporter.cs+++ b/Aetheris.Kernel.Core/Brep/Tessellation/BinaryStlExporter.cs@@ -6,8 +6,25 @@ namespace Aetheris.Kernel.Core.Brep.Tessellation;public static class BinaryStlExporter{public static void Export(string path, TriangleMesh mesh)+ => Export(path, mesh, out _);++ public static void Export(string path, TriangleMesh mesh, out TriangleMeshTopologyReport topology){if (!TriangleMeshValidator.TryValidateClosed(mesh, out _, out var failure)) throw new InvalidOperationException(failure);+ // STL stores float32 coordinates and no vertex identities. Qualify the+ // actual representation, including vertices which collapse on conversion,+ // before creating or replacing the destination file.+ var positions = new List<Point3D>(); var index = new Dictionary<Point3D, int>();+ var remap = new int[mesh.Positions.Count];+ for (var i = 0; i < mesh.Positions.Count; i++)+ {+ var p = mesh.Positions[i]; var stored = new Point3D((float)p.X, (float)p.Y, (float)p.Z);+ if (!index.TryGetValue(stored, out var id)) { id = positions.Count; index.Add(stored, id); positions.Add(stored); }+ remap[i] = id;+ }+ mesh = mesh with { Positions = positions, TriangleIndices = mesh.TriangleIndices.Select(i => remap[i]).ToArray() };+ if (!TriangleMeshValidator.TryValidateClosed(mesh, out topology, out failure))+ throw new InvalidOperationException("Binary STL float32 coordinates do not preserve a closed oriented mesh: " + failure);using var stream = File.Create(path);using var writer = new BinaryWriter(stream, Encoding.ASCII, leaveOpen: false);var header = new byte[80]; Encoding.ASCII.GetBytes("Aetheris SurfaceMeshIR validated binary STL").CopyTo(header, 0); writer.Write(header);diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.cs b/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.csindex b4be2e2b..2064b56a 100644--- a/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.cs+++ b/Aetheris.Kernel.Core/Brep/Tessellation/SurfaceMeshIr.cs@@ -325,14 +325,6 @@ public static class SurfaceMeshIrTessellatorvar hard = BuildHardEdges(document, indexById);var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(string.Join("|", positions.Select(p => $"{p.X:R},{p.Y:R},{p.Z:R}") ) + ";" + string.Join(',', indices)))).ToLowerInvariant();mesh = new TriangleMesh(positions, normals, indices, hard, hash);- // A B-rep's shell orientation is authoritative. The global sign is a- // final deterministic correction, never a repair/weld operation.- if (!TriangleMeshValidator.TryValidateClosed(mesh, out report, out _)- && report.SignedVolume < 0d)- {- for (var i = 0; i < indices.Count; i += 3) (indices[i + 1], indices[i + 2]) = (indices[i + 2], indices[i + 1]);- mesh = mesh with { TriangleIndices = indices };- }return TriangleMeshValidator.TryValidateClosed(mesh, out report, out _);}@@ -470,6 +462,49 @@ public static class SurfaceMeshIrTessellatorvar preMetrics = ComputeMetrics(vertices, patches, sharedPlans, triangleCount: 0);var foreignTrimResolutions = BuildForeignTrimResolutions(body, sharedPlans, policy);var builtDocument = new SurfaceMeshDocument(vertices, patches, sharedPlans, preMetrics, foreignTrimResolutions);+ // Chart traversal is not material orientation. Strip/bridge planners may+ // walk their local chart either way; publish every cell in the resolved+ // BRep support orientation once, before OBJ, display or STL consumes it.+ var vertexById = vertices.ToDictionary(v => v.Id);+ patches = patches.Select(patch =>+ {+ var normal = ResolvePatchNormal(builtDocument, patch, vertexById);+ return patch with { Cells = patch.Cells.Select(cell =>+ {+ if (cell.VertexIds.Count < 3) return cell;+ var ids = cell.VertexIds;+ // Use the analytic chart's Jacobian orientation, not a chord's+ // approximate 3D normal. Thin trimmed ears may span appreciable+ // curvature; independently flipping those chords folds a patch.+ var chart = ids.Select(id => patch.Support.Kind switch+ {+ SurfaceMeshSupportKind.Cylinder when patch.Support.Cylinder is { } c => TryProjectPointToCylinderUv(c, vertexById[id].Position),+ SurfaceMeshSupportKind.Cone when patch.Support.Cone is { } c => TryProjectPointToConeUv(c, vertexById[id].Position),+ SurfaceMeshSupportKind.Torus when patch.Support.Torus is { } t => TryProjectPointToTorusUv(t, vertexById[id].Position),+ _ => null+ }).ToArray();+ if (chart.All(p => p is not null))+ {+ var uv = UnwrapPeriodicU(chart.Select(p => p!.Value).ToArray());+ if (patch.Support.Kind == SurfaceMeshSupportKind.Torus)+ uv = UnwrapPeriodicU(uv.Select(p => (p.V, p.U)).ToArray()).Select(p => (U: p.V, V: p.U)).ToArray();+ var positive = SignedArea(uv) > 0;+ return positive != patch.IsAlignedWithSupport+ ? cell with { VertexIds = ids.Take(1).Concat(ids.Skip(1).Reverse()).ToArray() } : cell;+ }+ var origin = vertexById[ids[0]].Position;+ var area = new Vector3D(0, 0, 0); var outward = new Vector3D(0, 0, 0);+ for (var i = 0; i < ids.Count; i++)+ {+ var point = vertexById[ids[i]].Position;+ area += (point - origin).Cross(vertexById[ids[(i + 1) % ids.Count]].Position - origin);+ outward += normal(point);+ }+ return area.Dot(outward) < 0+ ? cell with { VertexIds = ids.Take(1).Concat(ids.Skip(1).Reverse()).ToArray() } : cell;+ }).ToArray() };+ }).ToList();+ builtDocument = builtDocument with { Patches = patches };var triangleCount = builtDocument.Patches.Sum(p => CountLoweredTriangles(builtDocument, p));document = builtDocument with { Metrics = ComputeMetrics(vertices, patches, sharedPlans, triangleCount) };return true;diff --git a/Aetheris.Kernel.Core/Brep/Tessellation/TriangleMesh.cs b/Aetheris.Kernel.Core/Brep/Tessellation/TriangleMesh.csindex 8a717547..ebb93fe6 100644--- a/Aetheris.Kernel.Core/Brep/Tessellation/TriangleMesh.cs+++ b/Aetheris.Kernel.Core/Brep/Tessellation/TriangleMesh.cs@@ -20,7 +20,12 @@ public sealed record TriangleMeshTopologyReport(int ZeroAreaTriangleCount,int TriangleCount,int VertexCount,- double SignedVolume);+ double SignedVolume)+{+ public int OrientationConflictEdgeCount { get; init; }+ public bool IsConsistentlyOriented { get; init; }+ public bool HasValidSignedVolume { get; init; }+}public static class TriangleMeshValidator{@@ -28,9 +33,11 @@ public static class TriangleMeshValidatorpublic static bool TryValidateClosed(TriangleMesh mesh, out TriangleMeshTopologyReport report, out string? failure){- var edges = new Dictionary<(int A, int B), int>();+ var edges = new Dictionary<(int A, int B), (int Count, int Balance)>();var triangles = new HashSet<(int A, int B, int C)>();var zero = 0; var duplicate = 0;+ if (mesh.Positions.Any(p => !double.IsFinite(p.X) || !double.IsFinite(p.Y) || !double.IsFinite(p.Z)))+ { failure = "Triangle mesh contains a nonfinite position."; report = Empty(mesh); return false; }for (var i = 0; i < mesh.TriangleIndices.Count; i += 3){if (i + 2 >= mesh.TriangleIndices.Count) { failure = "Triangle index buffer is not a multiple of three."; report = Empty(mesh); return false; }@@ -41,19 +48,25 @@ public static class TriangleMeshValidatorif (((mesh.Positions[b] - mesh.Positions[a]).Cross(mesh.Positions[c] - mesh.Positions[a])).Length <= AreaEpsilon) zero++;AddEdge(a, b); AddEdge(b, c); AddEdge(c, a);}- var cracks = edges.Count(pair => pair.Value == 1);- var nonmanifold = edges.Count(pair => pair.Value != 2);+ var cracks = edges.Count(pair => pair.Value.Count == 1);+ var nonmanifold = edges.Count(pair => pair.Value.Count != 2);+ var conflicts = edges.Count(pair => pair.Value.Count == 2 && pair.Value.Balance != 0);var connected = IsConnected(mesh);var volume = SignedVolume(mesh);- report = new TriangleMeshTopologyReport(cracks == 0 && nonmanifold == 0 && duplicate == 0 && zero == 0 && connected && volume > 0d,- connected, volume > 0d, cracks, nonmanifold, duplicate, zero, mesh.TriangleIndices.Count / 3, mesh.Positions.Count, volume);- failure = report.IsWatertight ? null : $"Triangle mesh topology failed: cracks={cracks}, nonmanifold={nonmanifold}, duplicates={duplicate}, zeroArea={zero}, connected={connected}, signedVolume={volume:R}.";+ var consistent = cracks == 0 && nonmanifold == 0 && conflicts == 0;+ var validVolume = consistent && connected && duplicate == 0 && zero == 0 && double.IsFinite(volume);+ var outward = validVolume && volume > 0d;+ report = new TriangleMeshTopologyReport(outward, connected, outward, cracks, nonmanifold, duplicate, zero,+ mesh.TriangleIndices.Count / 3, mesh.Positions.Count, volume)+ { OrientationConflictEdgeCount = conflicts, IsConsistentlyOriented = consistent, HasValidSignedVolume = validVolume };+ failure = report.IsWatertight ? null : $"Triangle mesh topology failed: cracks={cracks}, nonmanifold={nonmanifold}, orientationConflicts={conflicts}, duplicates={duplicate}, zeroArea={zero}, connected={connected}, signedVolumeValid={validVolume}, signedVolume={volume:R}.";return report.IsWatertight;void AddEdge(int x, int y){var edge = x < y ? (x, y) : (y, x);- edges[edge] = edges.GetValueOrDefault(edge) + 1;+ var old = edges.GetValueOrDefault(edge);+ edges[edge] = (old.Count + 1, old.Balance + (x < y ? 1 : -1));}}@@ -81,11 +94,19 @@ public static class TriangleMeshValidatorprivate static double SignedVolume(TriangleMesh mesh){- var volume = 0d;+ if (mesh.Positions.Count == 0) return 0;+ // A nearby anchor avoids cancellation for closed parts far from world+ // zero. This is numerical conditioning, not a closure/orientation proof.+ var origin = mesh.Positions[0];+ var volume = 0d; var compensation = 0d;for (var i = 0; i < mesh.TriangleIndices.Count; i += 3){var a = mesh.Positions[mesh.TriangleIndices[i]]; var b = mesh.Positions[mesh.TriangleIndices[i + 1]]; var c = mesh.Positions[mesh.TriangleIndices[i + 2]];- volume += new Vector3D(a.X, a.Y, a.Z).Dot(new Vector3D(b.X, b.Y, b.Z).Cross(new Vector3D(c.X, c.Y, c.Z))) / 6d;+ var term = (a - origin).Dot((b - origin).Cross(c - origin)) / 6d;+ var corrected = term - compensation;+ var next = volume + corrected;+ compensation = (next - volume) - corrected;+ volume = next;}return volume;}diff --git a/Aetheris.Kernel.Firmament.Tests/SurfaceMeshIrM4HexBoltTests.cs b/Aetheris.Kernel.Firmament.Tests/SurfaceMeshIrM4HexBoltTests.csindex 7f524aaa..ff45a49f 100644--- a/Aetheris.Kernel.Firmament.Tests/SurfaceMeshIrM4HexBoltTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/SurfaceMeshIrM4HexBoltTests.cs@@ -18,6 +18,7 @@ public sealed class SurfaceMeshIrM4HexBoltTestsvar roots = document.Patches.Where(patch => patch.Support.Kind == SurfaceMeshSupportKind.Torus).ToArray();Assert.Equal(8, cones.Length); // six head sectors and two tip sectorsAssert.Equal(2, roots.Length);+ Assert.All(roots, patch => Assert.False(patch.IsAlignedWithSupport));Assert.All(cones.Concat(roots), patch => Assert.All(patch.Cells, cell => Assert.IsType<QuadCell>(cell)));var hyperbolas = document.SharedBoundaries.Where(boundary => boundary.CurveKind == CurveGeometryKind.Hyperbola3).ToArray();@@ -29,7 +30,7 @@ public sealed class SurfaceMeshIrM4HexBoltTestsAssert.Equal(2, consumers.Length);});- Assert.True(SurfaceMeshIrTessellator.TryLowerToTriangleMesh(document, out var mesh, out var topology));+ Assert.True(SurfaceMeshIrTessellator.TryLowerToTriangleMesh(document, out var mesh, out var topology), topology.ToString());Assert.True(topology.IsWatertight);Assert.True(topology.IsOutwardOriented);Assert.Equal(0, topology.NonManifoldEdgeCount);@@ -84,7 +85,7 @@ public sealed class SurfaceMeshIrM4HexBoltTestsAssert.True(SurfaceMeshIrTessellator.TryBuild(fixture.Value.Body, SurfaceMeshPolicy.FromDisplayOptions(DisplayTessellationOptions.Default), out var document));Assert.Equal(8, document.SharedBoundaries.Count(boundary => boundary.CurveKind == CurveGeometryKind.Hyperbola3));Assert.Equal(2, document.Patches.Count(patch => patch.Support.Kind == SurfaceMeshSupportKind.Torus));- Assert.True(SurfaceMeshIrTessellator.TryLowerToTriangleMesh(document, out _, out var topology));+ Assert.True(SurfaceMeshIrTessellator.TryLowerToTriangleMesh(document, out _, out var topology), topology.ToString());Assert.True(topology.IsWatertight);}}diff --git a/Aetheris.Kernel.StandardLibrary/ExactConstructionMaterializers.cs b/Aetheris.Kernel.StandardLibrary/ExactConstructionMaterializers.csindex 59746d93..721fda84 100644--- a/Aetheris.Kernel.StandardLibrary/ExactConstructionMaterializers.cs+++ b/Aetheris.Kernel.StandardLibrary/ExactConstructionMaterializers.cs@@ -235,8 +235,10 @@ internal static class PeriodicTorusBlendMaterializervar support = SurfaceGeometry.FromTorus(new TorusSurface(new Point3D(blend.End, 0d, 0d), plusX, blend.ShoulderRadius, blend.Radius, plusY));var supportId = context.SharedSurface(support);return new([- context.Face([[new(shoulder.Arc0, false), new(minus, false), new(cylinder.Arc0, true), new(plus, true)]], support, sharedSurfaceId: supportId),- context.Face([[new(shoulder.Arc1, false), new(plus, false), new(cylinder.Arc1, true), new(minus, true)]], support, sharedSurfaceId: supportId)]);+ // This is the inner quadrant of the torus tube: material-outward+ // normals oppose the support normal at both shoulder and shaft.+ context.Face([[new(shoulder.Arc0, false), new(minus, false), new(cylinder.Arc0, true), new(plus, true)]], support, sameSense: false, sharedSurfaceId: supportId),+ context.Face([[new(shoulder.Arc1, false), new(plus, false), new(cylinder.Arc1, true), new(minus, true)]], support, sameSense: false, sharedSurfaceId: supportId)]);}}diff --git a/docs/development/reports/2026-10/stl-integrity-and-volume-authority.md b/docs/development/reports/2026-10/stl-integrity-and-volume-authority.mdnew file mode 100644index 00000000..bd26a02a--- /dev/null+++ b/docs/development/reports/2026-10/stl-integrity-and-volume-authority.md@@ -0,0 +1,116 @@+# STL integrity and volume authority++Date: 2026-10-28++## Reproduction and repair++Claude's CTC-01 report reproduced on the production CLI. The original STL had+22,108 triangles and 1,444 unmatched directed edges despite `watertight: true`.+The validator counted undirected edge uses and accepted positive total signed+volume; neither proves consistent winding.++Independent integration of the actual float32 STL records:++| Reference origin (mm) | Before (mm�) | After (mm�) |+| --- | ---: | ---: |+| (0, 0, 0) | 15,439,826.734 | 14,646,106.929 |+| (1000, 2000, 3000) | 17,317,273.436 | 14,646,106.929 |+| (-1000, -2000, -3000) | 13,562,380.032 | 14,646,106.929 |++The repaired artifact has zero unmatched directed edges. The multiset of+unoriented triangles is identical before/after, including stored coordinates;+only winding/normals change. These are triangle+approximation measurements, not a claim of exact nominal NIST volume.++Repairs stay at the existing owners:++- SurfaceMeshIR publishes cell winding from the resolved BRep support and+ analytic chart orientation once, before display, OBJ and STL consume it.+ Approximate 3D chord normals are insufficient for thin curved trim ears;+ chart winding preserves their shared-edge traversal. No mesh welding or+ guessed global sign flip repairs the construction document.+- TriangleMeshValidator requires opposite directed uses, reports orientation+ conflicts, and qualifies signed volume only after closed/consistent incidence,+ connectedness and nondegeneracy checks. Positive algebraic volume alone no+ longer labels a mesh outward/watertight. Nearby-anchor compensated integration+ reduces cancellation for parts far from world zero.+- The exact coaxial materializer now marks concave root fillets opposite their+ torus support. Imported versions already derived the correct sign, exposing a+ direct-construction versus import disagreement under the stronger validator.+- The legacy Box/cylinder subtraction owner now declares cavity wall normals+ inward toward the removed cylinder. This construction metadata error was+ exposed by strict checking; coordinates and supports are unchanged.+- BinaryStlExporter validates the actual float32 representation with equal stored+ positions identified. Collapse or nonfinite coordinates reject before opening+ the destination. The CLI returns structured failure. Reported mesh volume is+ computed from the stored coordinates; existing report fields remain compatible.++Checks do not prove absence of self-intersection or complete design fidelity.+SDF cannot substitute for checking the artifact's triangles.++## SDF evaluation and decision++Use exact admitted measures first; use bounded SDF integration as the default+**numerical engineering measurement** only when a qualified field represents the+final exported body. Keep mesh mass explicitly diagnostic. FirmamentMeasurements+already implements that policy for `measure`/assertions, including rejection of+stock-only or display-only CIR mirrors.++Real CLI probes show the present boundary:++- The authored Box witness selects ExactVerticalLineArcPrismSectionIntegration:+ exactly 480 mm�, zero uncertainty and no field-region work.++- Authored radius-10 mm sphere: both default and explicit `--sdf --error 50`+ select SdfAdaptiveOccupiedVolumeInterval. They visit 1,000,001 regions and stop+ with [4109.301567, 4267.172813] mm�, midpoint 4188.237190 and �78.935623 mm�.+ `budgetExhausted: true` correctly discloses that �50 was not achieved. The+ exact nominal sphere value 4188.790205 lies inside the interval. This existing+ exact-volume recognizer set does not admit the loopless sphere; the field is+ the available qualified measurement here.+- Imported CTC-01: geometry builds, but explicit SDF volume is Unavailable.+ No retained analytic CIR field is qualified to represent that imported body.+ A display mesh or approximate point-cloud field is not an independent remedy.++Do not globally redirect kernel mass properties to SDF now. Core has no general+trimmed-BRep-to-qualified-field lowering, and Continuum already depends on Core;+adding the inverse dependency would be the wrong ownership boundary. Existing+Core numerical boundary integration is distinct from assertion authority.++The smallest useful next steps are to extend **final material-operation CIR**+coverage in the existing lowerers, preserving transforms, holes, edits and+provenance, and improve bounded integration's uncertainty reduction before+making tighter default precision promises. Imported bodies need an independently+qualified inside/outside/interval capability for their trimmed solid. Reuse the+existing high-level measurement owner; do not add another volume validator or+construct a supposedly independent SDF from the same suspect triangles.++## Qualification++The focused Core mesh lane passed 22 tests; the focused production CLI lane+passed nine, and the Firmament mesh/assertion/rib lane passed 39. The first full+run isolated the direct-construction root-fillet sign defect above; its log is+retained as `full-tests-superseded.log`.++Final qualification:++- Release solution build: zero errors.+- Fast Core lane: 1,168 passed.+- Full solution gate: 6,304 passed, zero failed, two optional external PDF-renderer+ skips across twenty test assemblies. Full Core: 1,356 passed.+- Managed/WASM SDK rebuilt; all nineteen JavaScript SDK tests passed.+- Production CTC-01 STL byte audit: zero unmatched directed edges, unchanged+ unoriented triangle geometry, volume stable across three origins.+- `git diff --check` passed; task-owned .NET/test hosts exited.++**Verdict: Success.** The motivating artifact and false watertight certificate+are repaired, the regression gate passes, and the SDF decision is grounded in+actual coverage/uncertainty probes. Broader imported-body field coverage and+faster tight interval integration remain explicit future work.++Generated evidence is under ignored+`artifacts/local/stl-integrity/`: before/after STL and JSON, independent byte+integration, SDF probe JSON, build and test logs. New tests check a reversed face+with positive total volume, entire inward winding, far-origin conditioning,+float32 precision collapse without overwriting a prior artifact, CTC-01 directed+incidence, and the actual production CLI's serialized STL at multiple origins.diff --git a/docs/public/reference/cli.md b/docs/public/reference/cli.mdindex a5244de1..8c1bf2c8 100644--- a/docs/public/reference/cli.md+++ b/docs/public/reference/cli.md@@ -48,6 +48,27 @@ Run `aetheris <command> --help` for exact options. JSON is a public automation sGeneric STEP analysis reports analytic placement and size information where it is present: planes include origin and normal; bounded cylinders and cones include axis, axial extent, and circular-boundary angular extent; spheres include center and radius; and circles include center, axis, radius, sweep, orientation, and their actual trimmed endpoints. Circular-edge bounds and section output are computed from those trims rather than from the supporting full circle. `analyze section` returns normalized closed loops with deterministic orientation and nesting metadata; `--out` is intended as compact geometry evidence, not a substitute for the JSON record.+## Part mesh exports++```sh+aetheris mesh part.step --format stl --output artifacts/local/part.stl --json+```++STL export checks paired opposite-direction edge uses, connectedness, nondegenerate+triangles and positive signed volume. It repeats those checks after converting to+STL's float32 coordinates and merging equal stored positions. Precision collapse+rejects before replacing the destination file. Build nearer the coordinate origin+or use a representation retaining greater coordinate precision if float32 cannot+preserve the part's detail.++JSON includes `orientationConflictEdgeCount`, `consistentlyOriented`,+`outwardOriented` and `meshSignedVolumeMm3`. The volume describes the stored+triangle approximation, not the exact engineering part. `maxChordalDeviation`+describes shared boundary sampling; it is not a bound on volume error. `watertight` reports the+mesh checks above; it does not prove freedom from self-intersection or fidelity+to a nominal design. OBJ reports the same directed-edge diagnostics while+retaining the structured polygon representation.+## Assembly display meshes`aetheris mesh <assembly.firmament|assembly.firmasm> --format assembly-json --output <file.mesh.json> --json` exports shared local definition meshes and stable world-space occurrences. Failed geometry is not omitted. The default destination is `artifacts/local/mesh/<name>.mesh.json`. See [editable mechanisms](../firmament/editable-mechanisms.md) for the schema and a working consumer.diff --git a/docs/public/reference/language/checks.md b/docs/public/reference/language/checks.mdindex baa54d22..77739503 100644--- a/docs/public/reference/language/checks.md+++ b/docs/public/reference/language/checks.md@@ -122,6 +122,19 @@ reported interval remains usable at its actual uncertainty. Suggested tolerancesdesign's acceptance range independently. `--compare-mesh` exposes the older massestimate for diagnosis, never as a substitute assertion authority.+The default engineering volume path prefers admitted exact BRep formulas, then+bounded SDF integration when the compiler retains a field qualified to represent+the **final exported body**. `--sdf` requests that field path explicitly. A field+for stock before holes or edits is insufficient. STEP imports without such a+field report volume unavailable; display meshes and sampled point-cloud fields+do not silently become volume authority.++SDF integration may be substantially more expensive and less precise than an+available exact formula. Use the returned interval and `budgetExhausted`, rather+than treating the midpoint as an exact value. Mesh export integrity remains a+separate check: a correct field volume does not prove that an STL is closed or+consistently wound.+For assembly values use `aetheris asm inspect assembly.firmament --json`; its`assemblyIr.toleranceStackups` contains nominal/minimum/maximum, requirement,pass/fail, and the signed contributor chain. Unlike `measure`, assembly inspection