Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add inward helical groove construction

Yuechen Lia8891bf7ea3a
diff --git a/Aetheris.Kernel.Core.Tests/Brep/Surgery/BrepSurgeryRecipeParityTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Surgery/BrepSurgeryRecipeParityTests.cs
index 56e61300..2d7e859c 100644
--- a/Aetheris.Kernel.Core.Tests/Brep/Surgery/BrepSurgeryRecipeParityTests.cs
+++ b/Aetheris.Kernel.Core.Tests/Brep/Surgery/BrepSurgeryRecipeParityTests.cs
@@ -18,7 +18,7 @@ public sealed class BrepSurgeryRecipeParityTests
new AxisAlignedBoxExtents(2d, 4d, 0d, 2d, 0d, 1d),
]).Value;
- AssertCanonical(body, 8, 12, 6, "90cfba06396e6d4ad535585b50b18a7e1fdfae6adb36b7e5a127b40a59a5d496", expectClosedManifold: true);
+ AssertCanonical(body, 8, 12, 6, "0a1e73060c516eb608c1aef10a4f669b988052d806da441d8fed39bff73d5aed", expectClosedManifold: true);
}
[Fact]
@@ -29,7 +29,7 @@ public sealed class BrepSurgeryRecipeParityTests
new AxisAlignedBoxExtents(5d, 15d, -3d, 3d, -45d, 45d)).Value;
var body = BrepBoolean.Subtract(shaft, tool).Value;
- AssertCanonical(body, 8, 12, 6, "97f5d035a1e77bb3f7d1580de2baabf47b534f0be432ab7e71cf5890d7af5ba9", expectClosedManifold: true);
+ AssertCanonical(body, 8, 12, 6, "3b5b0ee1132a27427365ec19e9c6973cd702d3a5d27e8f4c977ea745ee79b12e", expectClosedManifold: true);
}
[Fact]
@@ -39,7 +39,7 @@ public sealed class BrepSurgeryRecipeParityTests
var tool = StandardLibraryPrimitives.CreateSlotCut(10d, 4d, 24d, 2d).Value;
var body = BrepBoolean.Subtract(root, tool).Value;
- AssertCanonical(body, 128, 192, 66, "80825a006112e1b029ff520239f38ab366760a703c598fd96cd17bb771320349");
+ AssertCanonical(body, 128, 192, 66, "a7b0cbd24843291d472417b8f6b752dbd2b3f1f361149a853cb829b7de6915fc");
}
private static void AssertCanonical(BrepBody body, int vertices, int edges, int faces, string expectedStepSha256, bool expectClosedManifold = false)
diff --git a/Aetheris.Kernel.Core.Tests/Geometry/BSplineSurfaceWithKnotsTests.cs b/Aetheris.Kernel.Core.Tests/Geometry/BSplineSurfaceWithKnotsTests.cs
index a592a5f7..982764f3 100644
--- a/Aetheris.Kernel.Core.Tests/Geometry/BSplineSurfaceWithKnotsTests.cs
+++ b/Aetheris.Kernel.Core.Tests/Geometry/BSplineSurfaceWithKnotsTests.cs
@@ -1,10 +1,45 @@
using Aetheris.Kernel.Core.Geometry.Surfaces;
+using Aetheris.Kernel.Core.Geometry.Curves;
using Aetheris.Kernel.Core.Math;
namespace Aetheris.Kernel.Core.Tests.Geometry;
public sealed class BSplineSurfaceWithKnotsTests
{
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public void ActiveSpanMatchesIndependentTensorEvaluationAtKnotsAndClampedEnds(bool rational)
+ {
+ int[] mu = [4, 1, 2, 4], mv = [3, 2, 3];
+ double[] ku = [0, .2, .55, 1], kv = [0, .6, 1];
+ var net = Enumerable.Range(0, 7).Select(i => (IReadOnlyList<Point3D>)Enumerable.Range(0, 5)
+ .Select(j => new Point3D(i * .7, j * .3, System.Math.Sin(i + j * .5))).ToArray()).ToArray();
+ var weights = Enumerable.Range(0, 7).Select(i => (IReadOnlyList<double>)Enumerable.Range(0, 5)
+ .Select(j => 1d + (i + j) * .13).ToArray()).ToArray();
+ var surface = new BSplineSurfaceWithKnots(3, 2, net, "UNSPECIFIED", false, false, false,
+ mu, mv, ku, kv, "UNSPECIFIED", rational ? weights : null);
+ Point3D Tensor(IReadOnlyList<IReadOnlyList<Point3D>> controls, double u, double v)
+ {
+ var rows = controls.Select(row => new BSpline3Curve(2, row, mv, kv,
+ "UNSPECIFIED", false, false, "UNSPECIFIED").Evaluate(v)).ToArray();
+ return new BSpline3Curve(3, rows, mu, ku, "UNSPECIFIED", false, false, "UNSPECIFIED").Evaluate(u);
+ }
+ foreach (var u in new[] { -.1, 0, .199999, .2, .35, .55, .999999, 1, 1.1 })
+ foreach (var v in new[] { -.1, 0, .3, .6, .999999, 1, 1.1 })
+ {
+ var expected = Tensor(net, u, v);
+ if (rational)
+ {
+ var numerator = Tensor(net.Select((row, i) => (IReadOnlyList<Point3D>)row.Select((p, j) =>
+ new Point3D(p.X * weights[i][j], p.Y * weights[i][j], p.Z * weights[i][j])).ToArray()).ToArray(), u, v);
+ var weight = Tensor(weights.Select(row => (IReadOnlyList<Point3D>)row.Select(w => new Point3D(w, 0, 0)).ToArray()).ToArray(), u, v).X;
+ expected = new(numerator.X / weight, numerator.Y / weight, numerator.Z / weight);
+ }
+ Assert.Equal(expected, surface.Evaluate(u, v));
+ }
+ }
+
[Fact]
public void Evaluate_AtDomainCorners_ReturnsCornerControlPoints()
{
diff --git a/Aetheris.Kernel.Core.Tests/Geometry/HelicalRibGeometryTests.cs b/Aetheris.Kernel.Core.Tests/Geometry/HelicalRibGeometryTests.cs
index b111f896..dc3e3868 100644
--- a/Aetheris.Kernel.Core.Tests/Geometry/HelicalRibGeometryTests.cs
+++ b/Aetheris.Kernel.Core.Tests/Geometry/HelicalRibGeometryTests.cs
@@ -125,16 +125,22 @@ public sealed class HelicalRibGeometryTests
}
}
- [Fact]
- public void AllThreeRuledHelicalSidesRemainWithinCertifiedSurfaceBound()
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public void AllThreeRuledHelicalSidesRemainWithinCertifiedSurfaceBound(bool inward)
{
- var rib = HelicalRibGeometry.Create(Witness()).Value;
+ var p = Witness();
+ if (inward) p = p with { RootRadiusMm = p.CrestRadiusMm, CrestRadiusMm = p.RootRadiusMm, Intent = HelicalProfileIntent.RemoveGroove };
+ var rib = HelicalRibGeometry.Create(p).Value;
foreach (var role in Enum.GetValues<HelicalRibSideRole>())
{
var realized = HelicalRibSurfaceRealizer.Realize(rib, role);
Assert.True(realized.IsSuccess, string.Join("; ", realized.Diagnostics));
Assert.InRange(realized.Value.CertifiedDeviationBoundMm, 0d, 1e-6d);
Assert.False(realized.Value.Surface.IsRational);
+ Assert.Equal(3 * realized.Value.SegmentCount + 1, realized.Value.Surface.ControlPoints.Count);
+ Assert.All(realized.Value.Surface.KnotMultiplicitiesU.Skip(1).SkipLast(1), multiplicity => Assert.Equal(3, multiplicity));
for (var i = 0; i <= 40; i++)
{
var angle = rib.Parameters.StartAngleRadians
diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242ExporterTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242ExporterTests.cs
index 47ef6084..00198365 100644
--- a/Aetheris.Kernel.Core.Tests/Step242/Step242ExporterTests.cs
+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242ExporterTests.cs
@@ -254,13 +254,18 @@ END-ISO-10303-21;";
var sourceSemiAngles = ExtractConicalSurfaceSemiAngles(source);
var exportedSemiAngles = ExtractConicalSurfaceSemiAngles(export.Value);
- Assert.Equal(sourceSemiAngles.Count, exportedSemiAngles.Count);
Assert.NotEmpty(exportedSemiAngles);
-
- for (var i = 0; i < sourceSemiAngles.Count; i++)
- {
- Assert.Equal(sourceSemiAngles[i] * (double.Pi / 180d), exportedSemiAngles[i], 9);
- }
+ // Distinct faces may share an identical immutable conical support definition.
+ Assert.Equal(sourceSemiAngles.Select(angle => System.Math.Round(angle * (double.Pi / 180d), 9)).Distinct().Order(),
+ exportedSemiAngles.Select(angle => System.Math.Round(angle, 9)).Distinct().Order());
+ var reimport = Step242Importer.ImportBody(export.Value);
+ Assert.True(reimport.IsSuccess);
+ static double[] FaceAngles(BrepBody body) => body.Topology.Faces
+ .Select(face => body.Geometry.GetSurface(body.Bindings.GetFaceBinding(face.Id).SurfaceGeometryId))
+ .Where(surface => surface.Cone.HasValue)
+ .Select(surface => System.Math.Round(surface.Cone!.Value.SemiAngleRadians, 9)).Order().ToArray();
+ Assert.Equal(FaceAngles(import.Value), FaceAngles(reimport.Value));
+ Assert.Equal(import.Value.Topology.Faces.Count(), reimport.Value.Topology.Faces.Count());
}
[Fact]
diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242GeometryInterningTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242GeometryInterningTests.cs
new file mode 100644
index 00000000..5cf07930
--- /dev/null
+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242GeometryInterningTests.cs
@@ -0,0 +1,50 @@
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.Kernel.Core.Tests.Step242;
+
+public sealed class Step242GeometryInterningTests
+{
+ [Fact]
+ public void ExactGeometrySharesButNamesCoordinatesAndDimensionsRemainDistinct()
+ {
+ var writer = new Step242TextWriter();
+ var point = writer.AddEntity("CARTESIAN_POINT", "''", "(1,2,3)");
+ Assert.Equal(point, writer.AddEntity("CARTESIAN_POINT", "''", "(1,2,3)"));
+ Assert.NotEqual(point, writer.AddEntity("CARTESIAN_POINT", "'named'", "(1,2,3)"));
+ Assert.NotEqual(point, writer.AddEntity("CARTESIAN_POINT", "''", "(1,2,3.0000000000001)"));
+ Assert.NotEqual(point, writer.AddEntity("CARTESIAN_POINT", "''", "(1,2)"));
+ var direction = writer.AddEntity("DIRECTION", "''", "(1,0,0)");
+ var vector = writer.AddEntity("VECTOR", "''", direction, "1");
+ Assert.Equal(vector, writer.AddEntity("VECTOR", "''", writer.AddEntity("DIRECTION", "''", "(1,0,0)"), "1"));
+ }
+
+ [Theory]
+ [InlineData("VERTEX_POINT")]
+ [InlineData("EDGE_CURVE")]
+ [InlineData("ADVANCED_FACE")]
+ [InlineData("PCURVE")]
+ [InlineData("SURFACE_CURVE")]
+ [InlineData("DEFINITIONAL_REPRESENTATION")]
+ [InlineData("PRODUCT")]
+ public void TopologyAndAssociationsNeverShareBySerializedEquality(string type)
+ {
+ var writer = new Step242TextWriter();
+ Assert.NotEqual(writer.AddEntity(type, "''", "#1"), writer.AddEntity(type, "''", "#1"));
+ }
+
+ [Fact]
+ public void WritersOwnTheirCachesAndFirstOccurrenceOrderingIsDeterministic()
+ {
+ static string Write()
+ {
+ var writer = new Step242TextWriter();
+ var first = writer.AddEntity("CARTESIAN_POINT", "''", "(1,2,3)");
+ writer.AddEntity("DIRECTION", "''", "(1,0,0)");
+ Assert.Equal("#1", first);
+ Assert.Equal(first, writer.AddEntity("CARTESIAN_POINT", "''", "(1,2,3)"));
+ Assert.Equal("#3", writer.AddEntity("VERTEX_POINT", "''", first));
+ return writer.Build(Step242HeaderMetadata.Deterministic);
+ }
+ Assert.Equal(Write(), Write());
+ }
+}
diff --git a/Aetheris.Kernel.Core/Brep/Features/BrepHelicalRib.cs b/Aetheris.Kernel.Core/Brep/Features/BrepHelicalRib.cs
index 795c754a..ffd8fd97 100644
--- a/Aetheris.Kernel.Core/Brep/Features/BrepHelicalRib.cs
+++ b/Aetheris.Kernel.Core/Brep/Features/BrepHelicalRib.cs
@@ -17,15 +17,16 @@ public sealed record BrepHelicalRibResult(
int SeamSplits);
/// <summary>
-/// Direct known-topology construction for complete-turn, single-start ribs.
+/// Direct known-topology construction for complete-turn, single-start ribs or grooves.
/// The cylinder skin is partitioned into N+1 exposed bands; no support face
-/// remains beneath the rib. This does not invoke a sweep or Boolean operator.
+/// remains beneath the displaced profile. An inward law removes material from
+/// stock with the same certified helical machinery, without a general Boolean.
/// </summary>
public static class BrepHelicalRib
{
private readonly record struct Use(EdgeId Edge, bool Reverse, PcurveGeometry? Pcurve = null);
- public static KernelResult<BrepHelicalRibResult> Create(HelicalRibGeometry rib)
+ public static KernelResult<BrepHelicalRibResult> Create(HelicalRibGeometry rib, bool splitStockRims = false)
{
ArgumentNullException.ThrowIfNull(rib);
var turnsRounded = double.Round(rib.Turns);
@@ -35,14 +36,14 @@ public static class BrepHelicalRib
if (p.AxialStartMm - p.RootWidthMm / 2d - p.SupportAxialMinMm <= 1e-6d
|| p.SupportAxialMaxMm - p.AxialEndMm - p.RootWidthMm / 2d <= 1e-6d)
return Failure("support-end-contact-unsupported", "X1 requires exposed support-cylinder margins before and after the rib footprint.");
- try { return Build(rib, (int)turnsRounded); }
+ try { return Build(rib, (int)turnsRounded, splitStockRims); }
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or OverflowException)
{
return Failure("construction-failed", ex.Message);
}
}
- private static KernelResult<BrepHelicalRibResult> Build(HelicalRibGeometry rib, int turns)
+ private static KernelResult<BrepHelicalRibResult> Build(HelicalRibGeometry rib, int turns, bool splitStockRims)
{
var p = rib.Parameters;
var builder = new TopologyBuilder();
@@ -186,24 +187,33 @@ public static class BrepHelicalRib
gaps[k] = Straight(section[k - 1, 3], section[k, 0], $"RootGap.Seam[{k}]");
var lowerSeam = Straight(bottom, section[0, 0], "RootLower.Seam");
var upperSeam = Straight(section[turns, 3], top, "RootUpper.Seam");
- var bottomCircle = Edge(bottom, bottom,
- CurveGeometry.FromCircle(new Circle3Curve(p.AxisOrigin + p.Axis.ToVector() * p.SupportAxialMinMm,
- p.Axis, p.RootRadiusMm, seamRadial)), new(0d, 2d * double.Pi), "Support.BottomRim");
- var topCircle = Edge(top, top,
- CurveGeometry.FromCircle(new Circle3Curve(p.AxisOrigin + p.Axis.ToVector() * p.SupportAxialMaxMm,
- p.Axis, p.RootRadiusMm, seamRadial)), new(0d, 2d * double.Pi), "Support.TopRim");
var bottomUv = PcurveGeometry.Line(new(0d, 2d * double.Pi),
new(0d, p.SupportAxialMinMm), new(2d * double.Pi, p.SupportAxialMinMm));
var topUv = PcurveGeometry.Line(new(0d, 2d * double.Pi),
new(0d, p.SupportAxialMaxMm), new(2d * double.Pi, p.SupportAxialMaxMm));
- Face("RootCylinderSkin.Lower", cylinderId, Reversed(
+ // A composed stock body may expose two half-circle rim edges. Preserve
+ // that topology instead of inserting artificial annular shoulders.
+ Use[] RimUses(VertexId endpoint, double axial, string role, PcurveGeometry uv)
+ {
+ var circle = new Circle3Curve(p.AxisOrigin + p.Axis.ToVector() * axial, p.Axis, p.RootRadiusMm, seamRadial);
+ if (!splitStockRims) return [new Use(Edge(endpoint, endpoint, CurveGeometry.FromCircle(circle), new(0d, 2d * double.Pi), role), false, uv)];
+ var middle = Vertex(circle.Evaluate(double.Pi));
+ var first = Edge(endpoint, middle, CurveGeometry.FromCircle(circle), new(0d, double.Pi), role + ".Half[0]");
+ var second = Edge(middle, endpoint, CurveGeometry.FromCircle(circle), new(double.Pi, 2d * double.Pi), role + ".Half[1]");
+ return [new Use(first, false, PcurveGeometry.Line(new(0d, double.Pi), uv.Evaluate(0d), uv.Evaluate(double.Pi))),
+ new Use(second, false, PcurveGeometry.Line(new(double.Pi, 2d * double.Pi), uv.Evaluate(double.Pi), uv.Evaluate(2d * double.Pi)))];
+ }
+ var bottomRim = RimUses(bottom, p.SupportAxialMinMm, "Support.BottomRim", bottomUv);
+ var topRim = RimUses(top, p.SupportAxialMaxMm, "Support.TopRim", topUv);
+
+ Face("RootCylinderSkin.Lower", cylinderId, Reversed([
new Use(lowerSeam, false, CylinderVertical(lowerSeam, 0d)),
new Use(helical[0, 0], false, CylinderHelix(helical[0, 0], 0, false)),
new Use(gaps[1], true, CylinderVertical(gaps[1], 2d * double.Pi)),
new Use(startRoot, true, CylinderVertical(startRoot, 2d * double.Pi)),
new Use(lowerSeam, true, CylinderVertical(lowerSeam, 2d * double.Pi)),
- new Use(bottomCircle, true, bottomUv)));
+ .. Reversed(bottomRim)]));
for (var k = 1; k < turns; k++)
Face($"RootCylinderSkin.Gap[{k}]", cylinderId, Reversed(
@@ -212,13 +222,13 @@ public static class BrepHelicalRib
new Use(gaps[k + 1], true, CylinderVertical(gaps[k + 1], 2d * double.Pi)),
new Use(helical[k - 1, 3], true, CylinderHelix(helical[k - 1, 3], k - 1, true))));
- Face("RootCylinderSkin.Upper", cylinderId, Reversed(
+ Face("RootCylinderSkin.Upper", cylinderId, Reversed([
new Use(gaps[turns], false, CylinderVertical(gaps[turns], 0d)),
new Use(endRoot, false, CylinderVertical(endRoot, 0d)),
new Use(upperSeam, false, CylinderVertical(upperSeam, 0d)),
- new Use(topCircle, false, topUv),
+ .. topRim,
new Use(upperSeam, true, CylinderVertical(upperSeam, 2d * double.Pi)),
- new Use(helical[turns - 1, 3], true, CylinderHelix(helical[turns - 1, 3], turns - 1, true))));
+ new Use(helical[turns - 1, 3], true, CylinderHelix(helical[turns - 1, 3], turns - 1, true))]));
for (var k = 0; k < turns; k++)
{
@@ -240,7 +250,8 @@ public static class BrepHelicalRib
}
}
- var radialNormal = Direction3D.Create(p.Axis.ToVector().Cross(seamRadial.ToVector()));
+ var radialNormal = Direction3D.Create(p.Axis.ToVector().Cross(seamRadial.ToVector())
+ * (p.Intent == HelicalProfileIntent.RemoveGroove ? -1d : 1d));
var startPlaneId = new SurfaceGeometryId(nextSurface++);
geometry.AddSurface(startPlaneId, SurfaceGeometry.FromPlane(new PlaneSurface(points[section[0, 0]],
Direction3D.Create(-radialNormal.ToVector()), seamRadial)));
@@ -257,11 +268,11 @@ public static class BrepHelicalRib
geometry.AddSurface(bottomPlaneId, SurfaceGeometry.FromPlane(new PlaneSurface(
p.AxisOrigin + p.Axis.ToVector() * p.SupportAxialMinMm,
Direction3D.Create(-p.Axis.ToVector()), seamRadial)));
- Face("Support.BottomCap", bottomPlaneId, new Use(bottomCircle, true));
+ Face("Support.BottomCap", bottomPlaneId, Reversed(bottomRim.Select(use => use with { Pcurve = null }).ToArray()));
var topPlaneId = new SurfaceGeometryId(nextSurface++);
geometry.AddSurface(topPlaneId, SurfaceGeometry.FromPlane(new PlaneSurface(
p.AxisOrigin + p.Axis.ToVector() * p.SupportAxialMaxMm, p.Axis, seamRadial)));
- Face("Support.TopCap", topPlaneId, new Use(topCircle, false));
+ Face("Support.TopCap", topPlaneId, topRim.Select(use => use with { Pcurve = null }).ToArray());
var shell = builder.AddShell(faces);
builder.AddBody([shell]);
diff --git a/Aetheris.Kernel.Core/Geometry/Curves/HelicalRibBoundaryRealizer.cs b/Aetheris.Kernel.Core/Geometry/Curves/HelicalRibBoundaryRealizer.cs
index 74b4eead..776ed095 100644
--- a/Aetheris.Kernel.Core/Geometry/Curves/HelicalRibBoundaryRealizer.cs
+++ b/Aetheris.Kernel.Core/Geometry/Curves/HelicalRibBoundaryRealizer.cs
@@ -46,7 +46,7 @@ public static class HelicalRibBoundaryRealizer
var segmentCount = (int)segmentCountReal;
var h = angleRange / segmentCount;
var error = authority.RadiusMm * double.Pow(h, 4d) / 384d;
- var controls = new List<Point3D>(4 * segmentCount);
+ var controls = new List<Point3D>(3 * segmentCount + 1);
var knots = new List<double>(segmentCount + 1);
var multiplicities = new List<int>(segmentCount + 1);
knots.Add(authority.StartAngleRadians);
@@ -59,12 +59,12 @@ public static class HelicalRibBoundaryRealizer
var width = b - a;
var p0 = authority.Evaluate(a);
var p3 = authority.Evaluate(b);
- controls.Add(p0);
+ if (i == 0) controls.Add(p0);
controls.Add(p0 + authority.Derivative(a) * (width / 3d));
controls.Add(p3 - authority.Derivative(b) * (width / 3d));
controls.Add(p3);
knots.Add(b);
- multiplicities.Add(4);
+ multiplicities.Add(i == segmentCount - 1 ? 4 : 3);
}
var curve = new BSpline3Curve(3, controls, multiplicities, knots,
"UNSPECIFIED", false, false, "UNSPECIFIED");
diff --git a/Aetheris.Kernel.Core/Geometry/HelicalRibGeometry.cs b/Aetheris.Kernel.Core/Geometry/HelicalRibGeometry.cs
index b6a9979e..7277aa40 100644
--- a/Aetheris.Kernel.Core/Geometry/HelicalRibGeometry.cs
+++ b/Aetheris.Kernel.Core/Geometry/HelicalRibGeometry.cs
@@ -6,7 +6,10 @@ using Aetheris.Kernel.Core.Results;
namespace Aetheris.Kernel.Core.Geometry;
-/// <summary>Exact intent for one additive, right-hand, single-start rib on finite cylindrical stock.</summary>
+public enum HelicalProfileIntent { AddRib, RemoveGroove }
+
+/// <summary>Exact intent for one right-hand, single-start trapezoidal rib or groove on finite cylindrical stock.
+/// Root denotes the stock attachment and Crest the displaced profile, including for an inward groove.</summary>
public sealed record HelicalRibParameters(
Point3D AxisOrigin,
Direction3D Axis,
@@ -20,7 +23,8 @@ public sealed record HelicalRibParameters(
double AxialEndMm,
double RootWidthMm,
double CrestWidthMm,
- double StartAngleRadians = 0d);
+ double StartAngleRadians = 0d,
+ HelicalProfileIntent Intent = HelicalProfileIntent.AddRib);
public enum HelicalRibBoundaryRole { LeadingRoot, LeadingCrest, TrailingCrest, TrailingRoot }
public enum HelicalRibSideRole { LeadingFlank, Crest, TrailingFlank }
@@ -48,6 +52,7 @@ public sealed class HelicalRibGeometry
{
ArgumentNullException.ThrowIfNull(p);
var linear = (tolerance ?? ToleranceContext.Default).Linear;
+ if (!Enum.IsDefined(p.Intent)) return Failure("intent", "Unknown helical profile intent.");
if (!Finite(p.SupportAxialMinMm, p.SupportAxialMaxMm, p.RootRadiusMm,
p.CrestRadiusMm, p.PitchMm, p.AxialStartMm, p.AxialEndMm,
p.RootWidthMm, p.CrestWidthMm, p.StartAngleRadians,
@@ -55,8 +60,9 @@ public sealed class HelicalRibGeometry
return Failure("nonfinite", "All rib dimensions and placement coordinates must be finite.");
if (p.SupportAxialMaxMm <= p.SupportAxialMinMm)
return Failure("support-bounds", "Support axial maximum must exceed minimum.");
- if (p.RootRadiusMm <= 0d || p.CrestRadiusMm <= p.RootRadiusMm)
- return Failure("radii", "Crest radius must exceed a positive root/support radius.");
+ if (p.RootRadiusMm <= 0d || p.CrestRadiusMm <= 0d ||
+ (p.Intent == HelicalProfileIntent.AddRib ? p.CrestRadiusMm <= p.RootRadiusMm : p.CrestRadiusMm >= p.RootRadiusMm))
+ return Failure("radii", "Both radii must be positive; the profile must extend outward for a rib or inward for a groove.");
if (p.PitchMm <= 0d) return Failure("pitch", "Pitch must be positive.");
if (p.AxialEndMm <= p.AxialStartMm)
return Failure("span", "Rib axial end must exceed start.");
diff --git a/Aetheris.Kernel.Core/Geometry/Surfaces/BSplineSurfaceWithKnots.cs b/Aetheris.Kernel.Core/Geometry/Surfaces/BSplineSurfaceWithKnots.cs
index 0e447feb..586dd837 100644
--- a/Aetheris.Kernel.Core/Geometry/Surfaces/BSplineSurfaceWithKnots.cs
+++ b/Aetheris.Kernel.Core/Geometry/Surfaces/BSplineSurfaceWithKnots.cs
@@ -182,11 +182,17 @@ public sealed record BSplineSurfaceWithKnots
return net[^1][^1];
}
- var rowPoints = new Point3D[net.Count];
- for (var i = 0; i < net.Count; i++)
+ // Tensor-product locality: de Boor in U consumes only DegreeU + 1
+ // rows. Evaluating the whole net makes long helical supports needlessly
+ // expensive, especially in the browser interpreter.
+ if (double.Abs(uClamped - DomainEndU) <= 1e-12d)
+ return EvaluateCurve(net[^1], DegreeV, FullKnotsV, DomainStartV, DomainEndV, vClamped);
+ var span = FindSpan(net.Count, DegreeU, FullKnotsU, uClamped);
+ var rowPoints = new Point3D[DegreeU + 1];
+ for (var i = 0; i <= DegreeU; i++)
{
rowPoints[i] = EvaluateCurve(
- net[i],
+ net[span - DegreeU + i],
DegreeV,
FullKnotsV,
DomainStartV,
@@ -194,13 +200,7 @@ public sealed record BSplineSurfaceWithKnots
vClamped);
}
- return EvaluateCurve(
- rowPoints,
- DegreeU,
- FullKnotsU,
- DomainStartU,
- DomainEndU,
- uClamped);
+ return BlendActiveSpan(rowPoints, span, DegreeU, FullKnotsU, uClamped);
}
private static IReadOnlyList<double> ExpandKnots(IReadOnlyList<int> multiplicities, IReadOnlyList<double> values)
@@ -259,6 +259,12 @@ public sealed record BSplineSurfaceWithKnots
d[j] = controlPoints[span - degree + j];
}
+ return BlendActiveSpan(d, span, degree, fullKnots, u);
+ }
+
+ private static Point3D BlendActiveSpan(Point3D[] d, int span, int degree,
+ IReadOnlyList<double> fullKnots, double u)
+ {
for (var r = 1; r <= degree; r++)
{
for (var j = degree; j >= r; j--)
diff --git a/Aetheris.Kernel.Core/Geometry/Surfaces/HelicalRibSurfaceRealizer.cs b/Aetheris.Kernel.Core/Geometry/Surfaces/HelicalRibSurfaceRealizer.cs
index d68e52ed..58b47c23 100644
--- a/Aetheris.Kernel.Core/Geometry/Surfaces/HelicalRibSurfaceRealizer.cs
+++ b/Aetheris.Kernel.Core/Geometry/Surfaces/HelicalRibSurfaceRealizer.cs
@@ -39,7 +39,7 @@ public static class HelicalRibSurfaceRealizer
var second = rib.Boundary(secondRole);
var requested = (tolerance ?? ToleranceContext.Default).Linear;
var p = rib.Parameters;
- var scale = double.Max(1d, double.Max(p.CrestRadiusMm,
+ var scale = double.Max(1d, double.Max(double.Max(p.CrestRadiusMm, p.RootRadiusMm),
double.Max(double.Abs(p.SupportAxialMinMm),
double.Max(double.Abs(p.SupportAxialMaxMm),
double.Max(double.Abs(p.AxisOrigin.X),
@@ -59,7 +59,7 @@ public static class HelicalRibSurfaceRealizer
var count = (int)countReal;
var h = angleRange / count;
var analyticError = maximumRadius * double.Pow(h, 4d) / 384d;
- var rows = new List<IReadOnlyList<Point3D>>(count * 4);
+ var rows = new List<IReadOnlyList<Point3D>>(count * 3 + 1);
var knots = new List<double>(count + 1) { p.StartAngleRadians };
var multiplicities = new List<int>(count + 1) { 4 };
for (var i = 0; i < count; i++)
@@ -71,14 +71,16 @@ public static class HelicalRibSurfaceRealizer
var b0 = first.Evaluate(b);
var a1 = second.Evaluate(a);
var b1 = second.Evaluate(b);
- rows.Add([a0, a1]);
+ // Adjacent Hermite spans share their endpoint. Interior multiplicity
+ // is degree (C0), not degree+1, which external CAD kernels reject.
+ if (i == 0) rows.Add([a0, a1]);
rows.Add([a0 + first.Derivative(a) * (width / 3d),
a1 + second.Derivative(a) * (width / 3d)]);
rows.Add([b0 - first.Derivative(b) * (width / 3d),
b1 - second.Derivative(b) * (width / 3d)]);
rows.Add([b0, b1]);
knots.Add(b);
- multiplicities.Add(4);
+ multiplicities.Add(i == count - 1 ? 4 : 3);
}
var surface = new BSplineSurfaceWithKnots(3, 1, rows,
"UNSPECIFIED", false, false, false,
diff --git a/Aetheris.Kernel.Core/Step242/Step242TextWriter.cs b/Aetheris.Kernel.Core/Step242/Step242TextWriter.cs
index a60567d0..e2498993 100644
--- a/Aetheris.Kernel.Core/Step242/Step242TextWriter.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242TextWriter.cs
@@ -6,14 +6,30 @@ namespace Aetheris.Kernel.Core.Step242;
internal sealed class Step242TextWriter
{
private readonly List<string> _entities = [];
+ // Export-local, exact serialized equality: no tolerance matching or topology coalescing.
+ // Names and references participate in the key; child geometry is interned first.
+ private readonly Dictionary<string, string> _immutableGeometry = new(StringComparer.Ordinal);
public string AddEntity(string entityName, params string[] arguments)
{
+ var instance = $"{entityName}({string.Join(",", arguments)})";
+ var share = IsImmutableGeometry(entityName);
+ if (share && _immutableGeometry.TryGetValue(instance, out var existing)) return existing;
var id = $"#{_entities.Count + 1}";
- _entities.Add($"{id}={entityName}({string.Join(",", arguments)});");
+ _entities.Add($"{id}={instance};");
+ if (share) _immutableGeometry.Add(instance, id);
return id;
}
+ // PCURVE/SURFACE_CURVE and representation entities carry associations, not just support
+ // geometry. Keep them, all topology, and complex/raw entities independently authored.
+ private static bool IsImmutableGeometry(string name) => name is
+ "CARTESIAN_POINT" or "DIRECTION" or "VECTOR" or
+ "AXIS2_PLACEMENT_2D" or "AXIS2_PLACEMENT_3D" or
+ "LINE" or "CIRCLE" or "ELLIPSE" or "PLANE" or
+ "CYLINDRICAL_SURFACE" or "CONICAL_SURFACE" or "SPHERICAL_SURFACE" or "TOROIDAL_SURFACE" or
+ "B_SPLINE_CURVE_WITH_KNOTS" or "B_SPLINE_SURFACE_WITH_KNOTS";
+
public string AddRawEntity(string entityInstance)
{
var id = $"#{_entities.Count + 1}";
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentThreadX1Tests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentThreadX1Tests.cs
index 815edc33..8bd5bcc6 100644
--- a/Aetheris.Kernel.Firmament.Tests/FirmamentThreadX1Tests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentThreadX1Tests.cs
@@ -112,7 +112,7 @@ public sealed class FirmamentThreadX1Tests
var source = CylinderThread().Replace("StartOffset: 1mm", "", StringComparison.Ordinal);
var result = FirmamentBuildAndExport.CompileSource(source);
Assert.True(result.IsSuccess, string.Join(" | ", result.Diagnostics.Select(d => d.Message)));
- Assert.Equal(1 + 5d * 1.25d / 12d, result.Value.Thread!.StartOffsetMm, 9);
+ Assert.Equal(1 + 7d * 1.25d / 16d, result.Value.Thread!.StartOffsetMm, 9);
}
[Theory]
@@ -169,9 +169,9 @@ public sealed class FirmamentThreadX1Tests
Assert.Equal(47.5, report.LengthMm);
Assert.Equal(0.75, report.StartOffsetMm, 9);
Assert.Equal(0.95, report.AxialStartMm, 9);
- Assert.Equal(176, report.Faces);
- Assert.Equal(355, report.Edges);
- Assert.Equal(184, report.Vertices);
+ Assert.Equal(174, report.Faces);
+ Assert.Equal(353, report.Edges);
+ Assert.Equal(182, report.Vertices);
var standardPart = Assert.IsType<FirmamentStandardPartReport>(result.Value.StandardPart);
Assert.Equal("HexBolt", standardPart.Family);
Assert.Contains(standardPart.SemanticDescendants, item => item.StableId.EndsWith(".Head.TopFlat", StringComparison.Ordinal) && item.FaceId.HasValue);
diff --git a/Aetheris.Kernel.Firmament.Tests/ThreadShowcaseRepairTests.cs b/Aetheris.Kernel.Firmament.Tests/ThreadShowcaseRepairTests.cs
new file mode 100644
index 00000000..fdfc08b5
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/ThreadShowcaseRepairTests.cs
@@ -0,0 +1,149 @@
+using System.Text.Json;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Brep.Verification;
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class ThreadShowcaseRepairTests
+{
+ [Fact]
+ public void RecordCompactnessBenchmarkWhenRequested()
+ {
+ if (Environment.GetEnvironmentVariable("AETHERIS_STEP_COMPACTNESS_DIR") is not { Length: > 0 } output) return;
+ var root = new DirectoryInfo(AppContext.BaseDirectory);
+ while (root is not null && !File.Exists(Path.Combine(root.FullName, "Aetheris.slnx"))) root = root.Parent;
+ Assert.NotNull(root);
+ output = Path.GetFullPath(output, root.FullName);
+ Directory.CreateDirectory(output);
+ var source = File.ReadAllText(Path.Combine(root.FullName, "fixtures", "Thread", "hexbolt-showcase.firmament"));
+ foreach (var threaded in new[] { true, false })
+ {
+ var ordinary = source[..source.IndexOf(" Thread MainThread", StringComparison.Ordinal)] + "}\n";
+ ordinary = System.Text.RegularExpressions.Regex.Replace(ordinary, @"^.*MakerMark.*\r?\n", "", System.Text.RegularExpressions.RegexOptions.Multiline);
+ var compiled = FirmamentBuildAndExport.CompileSource(threaded ? source : ordinary);
+ Assert.True(compiled.IsSuccess, string.Join(" | ", compiled.Diagnostics.Select(d => d.Message)));
+ var body = compiled.Value.RuntimeBody!;
+ var options = threaded ? new Step242ExportOptions
+ {
+ ProductName = "ThreadedHexBoltMakerMark", ApplicationName = "Aetheris.Firmament.MakerMark.X2",
+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce
+ } : new Step242ExportOptions();
+ var exports = new List<double>();
+ var imports = new List<double>();
+ for (var repeat = 0; repeat < 4; repeat++)
+ {
+ var timer = System.Diagnostics.Stopwatch.StartNew();
+ var exported = Step242Exporter.ExportBody(body, options);
+ timer.Stop();
+ Assert.True(exported.IsSuccess);
+ Assert.Equal(compiled.Value.StepText, exported.Value);
+ if (repeat > 0) exports.Add(timer.Elapsed.TotalMilliseconds);
+ timer.Restart();
+ var imported = Step242Importer.ImportBody(exported.Value);
+ timer.Stop();
+ Assert.True(imported.IsSuccess);
+ Assert.Equal(body.Topology.Faces.Count(), imported.Value.Topology.Faces.Count());
+ Assert.Equal(body.Topology.Edges.Count(), imported.Value.Topology.Edges.Count());
+ Assert.Equal(body.Topology.Vertices.Count(), imported.Value.Topology.Vertices.Count());
+ if (repeat > 0) imports.Add(timer.Elapsed.TotalMilliseconds);
+ }
+ var name = threaded ? "threaded" : "ordinary";
+ File.WriteAllText(Path.Combine(output, name + ".step"), compiled.Value.StepText);
+ File.WriteAllText(Path.Combine(output, name + ".json"), JsonSerializer.Serialize(new
+ {
+ bytes = System.Text.Encoding.UTF8.GetByteCount(compiled.Value.StepText),
+ exportMilliseconds = exports, importMilliseconds = imports,
+ solids = body.Topology.Bodies.Count(), faces = body.Topology.Faces.Count(),
+ edges = body.Topology.Edges.Count(), vertices = body.Topology.Vertices.Count(),
+ compiled.Value.Thread, compiled.Value.MakerMark
+ }, new JsonSerializerOptions { WriteIndented = true }));
+ }
+ }
+
+ [Fact]
+ public void ReusablePartPathRejectsAnEngravingItCannotApply()
+ {
+ var path = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..",
+ "fixtures", "Thread", "hexbolt-showcase.firmament"));
+ var parsed = FirmamentV2.FirmamentV2Parser.Parse(File.ReadAllText(path));
+ var authored = parsed.Document!.Solid.StandardPart!;
+ var stock = StandardLibrary.StandardLibraryReusableParts.TryCreate(authored.Family, authored.Parameters);
+ Assert.False(stock.IsSuccess);
+ Assert.Contains(stock.Diagnostics, d => d.Message.Contains("assembly engraving is not yet supported", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void CanonicalThreadDisplayAudit()
+ {
+ var root = new DirectoryInfo(AppContext.BaseDirectory);
+ while (root is not null && !File.Exists(Path.Combine(root.FullName, "Aetheris.slnx"))) root = root.Parent;
+ Assert.NotNull(root);
+ var source = File.ReadAllText(Path.Combine(root.FullName, "fixtures", "Thread", "hexbolt-showcase.firmament"));
+ var compiled = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(compiled.IsSuccess, string.Join(" | ", compiled.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(2, compiled.Value.MakerMark!.CounterCount);
+ Assert.Equal("stock-minus-groove", compiled.Value.Thread!.Construction);
+ Assert.Equal(38, compiled.Value.Thread.Turns);
+ Assert.Equal(1.25, compiled.Value.Thread.PitchMm);
+ Assert.Equal(.953125, compiled.Value.Thread.HeadSideLandMm, 8);
+ Assert.Equal(1.315625, compiled.Value.Thread.TipSideLandMm, 8);
+ var imported = Step242Importer.ImportBody(compiled.Value.StepText);
+ Assert.True(imported.IsSuccess, string.Join(" | ", imported.Diagnostics.Select(d => d.Message)));
+ Assert.Single(imported.Value.Topology.Bodies);
+ Assert.Single(imported.Value.Topology.Shells);
+ Assert.Equal(compiled.Value.RuntimeBody!.Topology.Faces.Count(), imported.Value.Topology.Faces.Count());
+ var display = BrepDisplayTessellator.TessellateBounded(imported.Value, executionTimeout: TimeSpan.FromSeconds(60));
+ Assert.True(display.IsSuccess, string.Join(" | ", display.Diagnostics.Select(d => d.Message)));
+ var shaded = display.Value.FacePatches.Where(p => p.TriangleIndices.Count > 0).Select(p => p.FaceId).ToHashSet();
+ var missing = imported.Value.Topology.Faces.Where(f => !shaded.Contains(f.Id)).Select(f => new
+ {
+ face = f.Id.Value,
+ surface = imported.Value.Geometry.GetSurface(imported.Value.Bindings.GetFaceBinding(f.Id).SurfaceGeometryId).Kind.ToString(),
+ diagnostic = display.Value.FaceDiagnostics?.Where(d => d.FaceId == f.Id).ToArray()
+ }).ToArray();
+ if (Environment.GetEnvironmentVariable("AETHERIS_THREAD_REPAIR_ARTIFACT_DIR") is { Length: > 0 } output)
+ {
+ Directory.CreateDirectory(output);
+ File.WriteAllText(Path.Combine(output, "bolt.step"), compiled.Value.StepText);
+ File.WriteAllText(Path.Combine(output, "audit.json"), JsonSerializer.Serialize(new
+ {
+ compiled.Value.Thread,
+ compiled.Value.MakerMark,
+ mass = BrepMassProperties.Evaluate(imported.Value),
+ wireOnlyFaces = missing,
+ diagnostics = display.Diagnostics.Select(d => d.Message).ToArray()
+ }, new JsonSerializerOptions { WriteIndented = true }));
+ }
+ Assert.Empty(missing);
+ var mass = BrepMassProperties.Evaluate(imported.Value);
+ Assert.True(mass.IsEnclosed);
+ Assert.True(mass.IsOrientationConsistent);
+ Assert.All(imported.Value.Topology.Coedges.GroupBy(c => c.EdgeId), uses =>
+ {
+ Assert.Equal(2, uses.Count());
+ });
+ }
+
+ [Fact]
+ public void RecordOriginalProductDisplayBudgetWhenRequested()
+ {
+ if (Environment.GetEnvironmentVariable("AETHERIS_THREAD_REPAIR_BASELINE") is not { Length: > 0 } path) return;
+ var imported = Step242Importer.ImportBody(File.ReadAllText(path));
+ Assert.True(imported.IsSuccess);
+ var complete = DisplayPreparationFallbackBuilder.Build(imported.Value);
+ var display = complete.IsSuccess ? complete.Value : BrepDisplayTessellator.TessellateBoundedPartial(imported.Value);
+ var shaded = display.FacePatches.Where(p => p.TriangleIndices.Count > 0).Select(p => p.FaceId).ToHashSet();
+ File.WriteAllText(Path.ChangeExtension(path, "product-display.json"), JsonSerializer.Serialize(new
+ {
+ complete.IsSuccess,
+ missing = imported.Value.Topology.Faces.Where(f => !shaded.Contains(f.Id)).Select(f => new
+ {
+ face = f.Id.Value,
+ surface = imported.Value.Geometry.GetSurface(imported.Value.Bindings.GetFaceBinding(f.Id).SurfaceGeometryId).Kind.ToString(),
+ diagnostics = display.FaceDiagnostics?.Where(d => d.FaceId == f.Id).ToArray()
+ }).ToArray(),
+ diagnostics = complete.Diagnostics.Select(d => d.Message).ToArray()
+ }, new JsonSerializerOptions { WriteIndented = true }));
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
index c73bea4b..e1bbed8d 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
@@ -780,7 +780,7 @@ public static class FirmamentBuildAndExport
private static KernelResult<FirmamentStepExportResult>? TryExportV2StandardPart(FirmamentV2Document document)
{
if (document.Solids.Count != 1 || document.Solid.StandardPart is not { } authored) return null;
- var definition = StandardLibraryReusableParts.TryCreate(authored.Family, authored.Parameters);
+ var definition = StandardLibraryReusableParts.TryCreate(authored.Family, authored.Parameters, deferMakerMarkToCompiler: true);
if (!definition.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(definition.Diagnostics);
if (definition.Value.HexBolt is not { } bolt)
{
@@ -805,14 +805,14 @@ public static class FirmamentBuildAndExport
bolt.DeterministicSignature,
authored.Parameters,
semantics);
- return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(
+ return ApplyHexBoltMakerMark(new FirmamentStepExportResult(
step.Value,
bolt.Semantics.BodyStableId,
0,
"standard-part",
authored.Family,
ConceptIr: document.ConceptIr,
- StandardPart: report));
+ StandardPart: report) { RuntimeBody = bolt.Body });
}
private static KernelResult<FirmamentStepExportResult>? TryExportV2ThreadBody(FirmamentV2Document document)
@@ -850,15 +850,17 @@ public static class FirmamentBuildAndExport
var rootRadius = feature.MajorDiameterMm / 2d - depth;
if (rootRadius <= 0d)
return Failure("profile-self-intersection", "The 60-degree profile depth consumes the support radius.");
- var start = feature.StartOffsetMm ?? rootWidth / 2d + 1d;
+ var grooveWidth = feature.PitchMm - crestWidth;
+ var grooveBottomWidth = feature.PitchMm - rootWidth;
+ var start = feature.StartOffsetMm ?? grooveWidth / 2d + 1d;
var end = start + feature.LengthMm;
- if (start - rootWidth / 2d <= 1e-6d || end + rootWidth / 2d >= support.Height - 1e-6d)
+ if (start - grooveWidth / 2d <= 1e-6d || end + grooveWidth / 2d >= support.Height - 1e-6d)
return Failure("support-bounds", "Thread footprint requires exposed cylindrical stock before and after its finite span.");
var buildStart = Stopwatch.GetTimestamp();
var rib = HelicalRibGeometry.Create(new HelicalRibParameters(Point3D.Origin,
Direction3D.Create(new Vector3D(0d, 0d, 1d)), Direction3D.Create(new Vector3D(1d, 0d, 0d)),
- 0d, support.Height, rootRadius, feature.MajorDiameterMm / 2d, feature.PitchMm,
- start, end, rootWidth, crestWidth));
+ 0d, support.Height, feature.MajorDiameterMm / 2d, rootRadius, feature.PitchMm,
+ start, end, grooveWidth, grooveBottomWidth, Intent: HelicalProfileIntent.RemoveGroove));
if (!rib.IsSuccess) return Failure("geometry-invalid", string.Join(" | ", rib.Diagnostics.Select(d => d.Message)));
var built = BrepHelicalRib.Create(rib.Value);
if (!built.IsSuccess) return Failure("brep-invalid", string.Join(" | ", built.Diagnostics.Select(d => d.Message)));
@@ -878,7 +880,8 @@ public static class FirmamentBuildAndExport
{
var role when role.StartsWith("LeadingFlank", StringComparison.Ordinal) => SemanticTopologyRole.ThreadLeadingFlank,
var role when role.StartsWith("TrailingFlank", StringComparison.Ordinal) => SemanticTopologyRole.ThreadTrailingFlank,
- var role when role.StartsWith("Crest", StringComparison.Ordinal) => SemanticTopologyRole.ThreadCrest,
+ var role when role.StartsWith("Crest", StringComparison.Ordinal) => SemanticTopologyRole.ThreadRootFace,
+ var role when role.StartsWith("RootCylinderSkin", StringComparison.Ordinal) => SemanticTopologyRole.ThreadCrest,
"StartCap" => SemanticTopologyRole.ThreadStartCap,
"EndCap" => SemanticTopologyRole.ThreadEndCap,
_ => SemanticTopologyRole.ThreadRootFace
@@ -897,7 +900,8 @@ public static class FirmamentBuildAndExport
start, start, feature.Hand, "metric-60-degree-truncated", (int)double.Round(rib.Value.Turns), built.Value.Body.Topology.Faces.Count(),
built.Value.Body.Topology.Edges.Count(), built.Value.Body.Topology.Vertices.Count(),
built.Value.SeamSplits, constructionMs, exportMs,
- Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))));
+ Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))))
+ { HeadSideLandMm = start - grooveWidth / 2d, TipSideLandMm = support.Height - end - grooveWidth / 2d };
return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(
step.Value, featureId, 0, "thread-external", "metric-60-degree", Thread: report)
{ RuntimeBody = built.Value.Body, RuntimeCorrespondence = correspondence });
@@ -912,7 +916,7 @@ public static class FirmamentBuildAndExport
$"thread-{code}: {message}", "FirmamentV2.Thread")]);
if (authoredPart.Family != "HexBolt")
return Failure("support-not-hexbolt", "face(Bolt.Shank) is admitted only for the HexBolt standard part.");
- var definition = StandardLibraryReusableParts.TryCreate(authoredPart.Family, authoredPart.Parameters);
+ var definition = StandardLibraryReusableParts.TryCreate(authoredPart.Family, authoredPart.Parameters, deferMakerMarkToCompiler: true);
if (!definition.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(definition.Diagnostics);
var bolt = definition.Value.HexBolt!;
if (!double.IsFinite(feature.MajorDiameterMm) || feature.MajorDiameterMm <= 0d ||
@@ -932,20 +936,22 @@ public static class FirmamentBuildAndExport
return Failure("profile-self-intersection", "The 60-degree profile depth consumes the support radius.");
var supportStart = bolt.Spec.UnderHeadRadius;
var supportEnd = bolt.Dimensions.TipChamferStartX;
- var start = supportStart + (feature.StartOffsetMm ?? rootWidth / 2d + 1d);
+ var grooveWidth = feature.PitchMm - crestWidth;
+ var grooveBottomWidth = feature.PitchMm - rootWidth;
+ var start = supportStart + (feature.StartOffsetMm ?? grooveWidth / 2d + 1d);
var end = start + feature.LengthMm;
- if (start - rootWidth / 2d <= supportStart + 1e-6d || end + rootWidth / 2d >= supportEnd - 1e-6d)
+ if (start - grooveWidth / 2d <= supportStart + 1e-6d || end + grooveWidth / 2d >= supportEnd - 1e-6d)
return Failure("support-bounds", "Thread footprint requires stock margins inside the HexBolt shank, before the tip chamfer.");
var buildStart = Stopwatch.GetTimestamp();
var rib = HelicalRibGeometry.Create(new HelicalRibParameters(Point3D.Origin,
Direction3D.Create(new Vector3D(1d, 0d, 0d)), Direction3D.Create(new Vector3D(0d, 1d, 0d)),
- supportStart, supportEnd, rootRadius, feature.MajorDiameterMm / 2d, feature.PitchMm,
- start, end, rootWidth, crestWidth));
+ supportStart, supportEnd, feature.MajorDiameterMm / 2d, rootRadius, feature.PitchMm,
+ start, end, grooveWidth, grooveBottomWidth, Intent: HelicalProfileIntent.RemoveGroove));
if (!rib.IsSuccess) return Failure("geometry-invalid", string.Join(" | ", rib.Diagnostics.Select(d => d.Message)));
- var built = BrepHelicalRib.Create(rib.Value);
+ var built = BrepHelicalRib.Create(rib.Value, splitStockRims: true);
if (!built.IsSuccess) return Failure("brep-invalid", string.Join(" | ", built.Diagnostics.Select(d => d.Message)));
- HexBoltThreadStitch.Result stitched;
- try { stitched = HexBoltThreadStitch.Create(bolt, built.Value); }
+ HexBoltThreadComposition.Result stitched;
+ try { stitched = HexBoltThreadComposition.Create(bolt, built.Value); }
catch (InvalidOperationException ex) { return Failure("hexbolt-stitch-invalid", ex.Message); }
var constructionMs = Stopwatch.GetElapsedTime(buildStart).TotalMilliseconds;
var featureId = $"{document.Solid.Name}.{feature.Name}";
@@ -965,7 +971,8 @@ public static class FirmamentBuildAndExport
{
var role when role.StartsWith("LeadingFlank", StringComparison.Ordinal) => SemanticTopologyRole.ThreadLeadingFlank,
var role when role.StartsWith("TrailingFlank", StringComparison.Ordinal) => SemanticTopologyRole.ThreadTrailingFlank,
- var role when role.StartsWith("Crest", StringComparison.Ordinal) => SemanticTopologyRole.ThreadCrest,
+ var role when role.StartsWith("Crest", StringComparison.Ordinal) => SemanticTopologyRole.ThreadRootFace,
+ var role when role.StartsWith("RootCylinderSkin", StringComparison.Ordinal) => SemanticTopologyRole.ThreadCrest,
"StartCap" => SemanticTopologyRole.ThreadStartCap,
"EndCap" => SemanticTopologyRole.ThreadEndCap,
_ => SemanticTopologyRole.ThreadRootFace
@@ -977,7 +984,7 @@ public static class FirmamentBuildAndExport
featureId, Edge: stitched.ThreadEdges[pair.Key], ParentStableId: featureId,
Addressability: SemanticTopologyAddressability.DerivedStable))).ToArray();
var correspondence = new SemanticTopologyCorrespondence(featureId, descendants,
- ["Thread", "HelicalRib", "HexBoltThreadStitch"],
+ ["Thread", "HelicalRib", "HexBoltThreadComposition"],
new Dictionary<string, FirmamentV2SourceSpan> { [featureId] = feature.SourceSpan });
var boltSemantics = bolt.Semantics.Descendants
.Where(item => !item.StableId.Contains(".ThreadRegion", StringComparison.Ordinal)
@@ -993,13 +1000,61 @@ public static class FirmamentBuildAndExport
start - supportStart, start, feature.Hand, "metric-60-degree-truncated", (int)Math.Round(rib.Value.Turns),
stitched.Body.Topology.Faces.Count(), stitched.Body.Topology.Edges.Count(),
stitched.Body.Topology.Vertices.Count(), built.Value.SeamSplits, constructionMs, exportMs,
- Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))));
- return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(
+ Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))))
+ { HeadSideLandMm = start - supportStart - grooveWidth / 2d, TipSideLandMm = supportEnd - end - grooveWidth / 2d };
+ return ApplyHexBoltMakerMark(new FirmamentStepExportResult(
step.Value, featureId, 0, "thread-external-hexbolt", "metric-60-degree",
StandardPart: boltReport, Thread: report)
{ RuntimeBody = stitched.Body, RuntimeCorrespondence = correspondence });
}
+ private static KernelResult<FirmamentStepExportResult> ApplyHexBoltMakerMark(FirmamentStepExportResult result)
+ {
+ var part = result.StandardPart!;
+ if (!part.Parameters.TryGetValue("MakerMark", out var content))
+ return KernelResult<FirmamentStepExportResult>.Success(result);
+ try
+ {
+ var top = part.SemanticDescendants.Single(d => d.StableId.EndsWith(".Head.TopFlat", StringComparison.Ordinal)).FaceId!.Value;
+ var height = double.Parse(part.Parameters["MakerMarkHeight"].Trim()[..^2], System.Globalization.CultureInfo.InvariantCulture);
+ var depth = double.Parse(part.Parameters["MakerMarkDepth"].Trim()[..^2], System.Globalization.CultureInfo.InvariantCulture);
+ var mark = PlanarCapEngraving.Engrave(result.RuntimeBody!, new FaceId(top),
+ HexBoltParameterBinding.Text(content), height, depth);
+ var composition = mark.Composition!;
+ var semantics = part.SemanticDescendants.Select(d => d.FaceId is { } id
+ ? d with { FaceId = id == top ? composition.ReplacementCap.Value : composition.HostFaces[new FaceId(id)].Value }
+ : d).ToArray();
+ var correspondence = result.RuntimeCorrespondence;
+ if (correspondence is not null)
+ correspondence = correspondence with
+ {
+ Descendants = correspondence.Descendants.Select(d => d with
+ {
+ Face = d.Face is { } face ? composition.HostFaces[face] : null,
+ Edge = d.Edge is { } edge ? composition.HostEdges[edge] : null
+ }).ToArray()
+ };
+ var thread = result.Thread is { } t ? t with
+ {
+ Faces = mark.Body.Topology.Faces.Count(), Edges = mark.Body.Topology.Edges.Count(),
+ Vertices = mark.Body.Topology.Vertices.Count(),
+ StepSha256 = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(mark.StepText)))
+ } : null;
+ return KernelResult<FirmamentStepExportResult>.Success(result with
+ {
+ RuntimeBody = mark.Body, RuntimeCorrespondence = correspondence, StepText = mark.StepText,
+ Thread = thread, StandardPart = part with { SemanticDescendants = semantics },
+ MakerMark = new(HexBoltParameterBinding.Text(content), height, depth, mark.Text.CounterCount)
+ });
+ }
+ catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
+ {
+ return KernelResult<FirmamentStepExportResult>.Failure([new KernelDiagnostic(
+ KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,
+ "hexbolt-maker-mark-invalid: " + ex.Message, "FirmamentV2.StandardPart")]);
+ }
+ }
+
private static KernelResult<FirmamentStepExportResult>? TryExportV2ExactCoaxialPart(FirmamentV2Document document)
{
if (document.Solids.Count != 1 || document.Solid.ExactCoaxialPart is not { } authored) return null;
diff --git a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs
index 8b7deced..f5c72400 100644
--- a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs
@@ -42,14 +42,22 @@ public sealed record FirmamentStepExportResult(
[JsonIgnore] public BrepBody? RuntimeBody { get; init; }
[JsonIgnore] public SemanticTopologyCorrespondence? RuntimeCorrespondence { get; init; }
public FirmamentCirRetention? Cir { get; init; }
+ public FirmamentMakerMarkReport? MakerMark { get; init; }
}
+public sealed record FirmamentMakerMarkReport(string Content, double HeightMm, double DepthMm, int CounterCount);
+
public sealed record FirmamentThreadReport(
string FeatureId, string Support, double MajorDiameterMm, double RootDiameterMm,
double PitchMm, double LeadMm, double LengthMm, double StartOffsetMm, double AxialStartMm,
string Hand, string ProfileFamily, int Turns,
int Faces, int Edges, int Vertices, int SeamSplits,
- double ConstructionMilliseconds, double StepExportMilliseconds, string StepSha256);
+ double ConstructionMilliseconds, double StepExportMilliseconds, string StepSha256)
+{
+ public string Construction { get; init; } = "stock-minus-groove";
+ public double HeadSideLandMm { get; init; }
+ public double TipSideLandMm { get; init; }
+}
public sealed record FirmamentPerforationReport(
string FeatureId, string Support, string Layout, double Diameter, double Pitch,
diff --git a/Aetheris.Kernel.Firmament/Materializer/HexBoltThreadStitch.cs b/Aetheris.Kernel.Firmament/Materializer/HexBoltThreadComposition.cs
similarity index 68%
rename from Aetheris.Kernel.Firmament/Materializer/HexBoltThreadStitch.cs
rename to Aetheris.Kernel.Firmament/Materializer/HexBoltThreadComposition.cs
index 70d7bc72..844e1cd7 100644
--- a/Aetheris.Kernel.Firmament/Materializer/HexBoltThreadStitch.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/HexBoltThreadComposition.cs
@@ -10,18 +10,21 @@ using Aetheris.Kernel.StandardLibrary;
namespace Aetheris.Kernel.Firmament.Materializer;
/// <summary>
-/// Replaces exactly the two HexBolt shank skin faces with a helical root-stock skin.
-/// The original head and tip, the rib skin, and two planar annular shoulders share
-/// one shell. This bounded construction does not perform a Boolean union.
+/// Composes the ordinary HexBolt head and tip with its bounded stock-minus-groove
+/// shank. The major-radius rims are shared directly: no replacement root-stock
+/// rod, annular shoulders, or overlapping volumes are introduced.
/// </summary>
-internal static class HexBoltThreadStitch
+internal static class HexBoltThreadComposition
{
internal sealed record Result(BrepBody Body, IReadOnlyDictionary<FaceId, FaceId> BoltFaces,
IReadOnlyDictionary<FaceId, FaceId> ThreadFaces,
IReadOnlyDictionary<EdgeId, EdgeId> ThreadEdges);
+ internal sealed record PatchResult(BrepBody Body, IReadOnlyDictionary<FaceId, FaceId> HostFaces,
+ IReadOnlyDictionary<EdgeId, EdgeId> HostEdges, IReadOnlyDictionary<FaceId, FaceId> PatchFaces,
+ FaceId ReplacementCap);
/// <summary>Replaces only the planar head cap with section-stack pocket faces.</summary>
- internal static BrepBody ImprintTop(BrepBody threaded, FaceId topCap,
+ internal static PatchResult ImprintTop(BrepBody threaded, FaceId topCap,
BrepBody patch, IReadOnlyCollection<FaceId> patchFaces)
{
var retained = threaded.Topology.Faces.Where(face => face.Id != topCap).Select(face => face.Id).ToArray();
@@ -34,7 +37,7 @@ internal static class HexBoltThreadStitch
throw new InvalidOperationException($"Maker mark rim mismatch: patch={patchRim.Length}, head={hostRim.Length}.");
var shared = patchRim.ToDictionary(edge => edge,
edge => copied.Edges[hostRim.Single(host => SameEdge(threaded, host, patch, edge))]);
- shell.CopyFaces(patch, patchFaces, shared);
+ var patchCopy = shell.CopyFaces(patch, patchFaces, shared);
var body = shell.Complete();
var nonManifold = body.Topology.Coedges.GroupBy(x => x.EdgeId).Where(x => x.Count() != 2).ToArray();
if (nonManifold.Length != 0)
@@ -42,7 +45,9 @@ internal static class HexBoltThreadStitch
var mass = BrepMassProperties.Evaluate(body);
if (!mass.IsEnclosed || !mass.IsOrientationConsistent)
throw new InvalidOperationException("Maker mark shell is not enclosed and oriented: " + string.Join(" | ", mass.Diagnostics));
- return body;
+ var cap = patchCopy.Faces.Values.Single(face => shared.Values.All(edge =>
+ EdgesOfFaces(body, [face]).Contains(edge)));
+ return new(body, copied.Faces, copied.Edges, patchCopy.Faces, cap);
}
private static bool SameEdge(BrepBody firstBody, EdgeId firstId, BrepBody secondBody, EdgeId secondId)
@@ -54,57 +59,60 @@ internal static class HexBoltThreadStitch
secondBody.TryGetVertexPoint(second.StartVertexId, out var c);
secondBody.TryGetVertexPoint(second.EndVertexId, out var d);
static bool Near(Point3D x, Point3D y) => (x - y).Length < 1e-5d;
- return (Near(a, c) && Near(b, d)) || (Near(a, d) && Near(b, c));
+ if (!((Near(a, c) && Near(b, d)) || (Near(a, d) && Near(b, c)))) return false;
+ var firstBinding = firstBody.Bindings.GetEdgeBinding(firstId);
+ var secondBinding = secondBody.Bindings.GetEdgeBinding(secondId);
+ var firstTrim = firstBinding.TrimInterval!.Value;
+ var secondTrim = secondBinding.TrimInterval!.Value;
+ var firstCircle = firstBody.Geometry.GetCurve(firstBinding.CurveGeometryId).Circle3;
+ var secondCircle = secondBody.Geometry.GetCurve(secondBinding.CurveGeometryId).Circle3;
+ return firstCircle is { } circleA && secondCircle is { } circleB &&
+ Near(circleA.Evaluate((firstTrim.Start + firstTrim.End) / 2d),
+ circleB.Evaluate((secondTrim.Start + secondTrim.End) / 2d));
}
internal static Result Create(HexBoltDefinition bolt, BrepHelicalRibResult rib)
{
+ if (rib.Authority.Parameters.Intent != HelicalProfileIntent.RemoveGroove ||
+ Math.Abs(rib.Authority.Parameters.RootRadiusMm - bolt.Spec.NominalDiameter / 2d) > 1e-7d)
+ throw new InvalidOperationException("HexBolt threads require a groove cut into major-diameter stock.");
var shank = bolt.Semantics.Descendants
.Where(item => item.StableId.StartsWith(bolt.Semantics.BodyStableId + ".Shank.Face[", StringComparison.Ordinal)
&& item.Face.HasValue)
.Select(item => item.Face!.Value).ToHashSet();
- if (shank.Count != 2) throw new InvalidOperationException("HexBolt thread stitch requires exactly two cylindrical shank faces.");
+ if (shank.Count != 2) throw new InvalidOperationException("HexBolt thread composition requires exactly two cylindrical shank faces.");
var retainedBolt = bolt.Body.Topology.Faces.Where(face => !shank.Contains(face.Id)).Select(face => face.Id).ToArray();
var retainedRib = rib.FaceRoles.Where(item => item.Value is not ("Support.BottomCap" or "Support.TopCap"))
.Select(item => item.Key).ToArray();
var shell = new ShellCopy();
var boltCopy = shell.CopyFaces(bolt.Body, retainedBolt);
- var ribCopy = shell.CopyFaces(rib.Body, retainedRib);
-
var shankEdges = EdgesOfFaces(bolt.Body, shank).ToHashSet();
var retainedEdges = EdgesOfFaces(bolt.Body, retainedBolt).ToHashSet();
var sharedRings = shankEdges.Intersect(retainedEdges).ToArray();
if (sharedRings.Length != 4) throw new InvalidOperationException("HexBolt shank must meet head and tip at two half-circle rings.");
- var startX = bolt.Spec.UnderHeadRadius;
- var endX = bolt.Dimensions.TipChamferStartX;
- var lowerArcs = sharedRings.Where(edge => AtX(bolt.Body, edge, startX)).Select(edge => boltCopy.Edges[edge]).ToArray();
- var upperArcs = sharedRings.Where(edge => AtX(bolt.Body, edge, endX)).Select(edge => boltCopy.Edges[edge]).ToArray();
- if (lowerArcs.Length != 2 || upperArcs.Length != 2)
- throw new InvalidOperationException("HexBolt shank boundary rings do not match the planned axial interval.");
- var lowerRoot = ribCopy.Edges[AssertRole(rib, "Support.BottomRim")];
- var upperRoot = ribCopy.Edges[AssertRole(rib, "Support.TopRim")];
- shell.Annulus(startX, lowerArcs, lowerRoot, outwardPositive: true);
- shell.Annulus(endX, upperArcs, upperRoot, outwardPositive: false);
+ var rims = rib.EdgeRoles.Where(pair => pair.Value.StartsWith("Support.BottomRim", StringComparison.Ordinal)
+ || pair.Value.StartsWith("Support.TopRim", StringComparison.Ordinal)).Select(pair => pair.Key).ToArray();
+ if (rims.Length != 4) throw new InvalidOperationException("Grooved stock requires split major-radius rims.");
+ var shared = rims.ToDictionary(edge => edge, edge => boltCopy.Edges[
+ sharedRings.Single(host => SameEdge(bolt.Body, host, rib.Body, edge))]);
+ var ribCopy = shell.CopyFaces(rib.Body, retainedRib, shared);
var body = shell.Complete();
var bindings = BrepBindingValidator.Validate(body, true);
if (!bindings.IsSuccess)
- throw new InvalidOperationException("HexBolt thread stitch failed geometry bindings: " + string.Join(" | ",
+ throw new InvalidOperationException("HexBolt thread composition failed geometry bindings: " + string.Join(" | ",
bindings.Diagnostics.Take(8).Select(item => item.Message)));
var preflight = BrepExportPreflight.Validate(body);
if (!preflight.IsValid)
- throw new InvalidOperationException("HexBolt thread stitch failed BRep preflight: " + string.Join(" | ",
+ throw new InvalidOperationException("HexBolt thread composition failed BRep preflight: " + string.Join(" | ",
preflight.Diagnostics.Where(item => item.Severity == BrepExportPreflightSeverity.Error)
.Take(8).Select(item => item.Code + ": " + item.Message)));
var mass = BrepMassProperties.Evaluate(body);
if (!mass.IsEnclosed || !mass.IsOrientationConsistent)
- throw new InvalidOperationException("HexBolt thread stitch did not produce an enclosed, consistently oriented body: "
+ throw new InvalidOperationException("HexBolt thread composition did not produce an enclosed, consistently oriented body: "
+ string.Join(" | ", mass.Diagnostics));
return new(body, boltCopy.Faces, ribCopy.Faces, ribCopy.Edges);
}
- private static EdgeId AssertRole(BrepHelicalRibResult rib, string role) =>
- rib.EdgeRoles.Single(item => item.Value == role).Key;
-
private static IEnumerable<EdgeId> EdgesOfFaces(BrepBody body, IEnumerable<FaceId> faces)
{
foreach (var faceId in faces)
@@ -113,14 +121,6 @@ internal static class HexBoltThreadStitch
yield return body.Topology.GetCoedge(coedgeId).EdgeId;
}
- private static bool AtX(BrepBody body, EdgeId edgeId, double x)
- {
- var edge = body.Topology.GetEdge(edgeId);
- return body.TryGetVertexPoint(edge.StartVertexId, out var a)
- && body.TryGetVertexPoint(edge.EndVertexId, out var b)
- && Math.Abs(a.X - x) < 1e-7d && Math.Abs(b.X - x) < 1e-7d;
- }
-
private sealed class ShellCopy
{
private readonly TopologyBuilder topology = new();
@@ -143,10 +143,23 @@ internal static class HexBoltThreadStitch
var surfaceMap = new Dictionary<SurfaceGeometryId, SurfaceGeometryId>();
var faceMap = new Dictionary<FaceId, FaceId>();
+ // Seed shared endpoints before copying any other edge. Equal points
+ // must be the same topological vertex at a composed boundary.
+ if (sharedEdges is not null)
+ foreach (var (oldId, newId) in sharedEdges)
+ {
+ var oldEdge = source.Topology.GetEdge(oldId);
+ var newEdge = topology.Model.GetEdge(newId);
+ source.TryGetVertexPoint(oldEdge.StartVertexId, out var start);
+ var reverse = (start - points[newEdge.StartVertexId]).Length > 1e-5d;
+ vertexMap[oldEdge.StartVertexId] = reverse ? newEdge.EndVertexId : newEdge.StartVertexId;
+ vertexMap[oldEdge.EndVertexId] = reverse ? newEdge.StartVertexId : newEdge.EndVertexId;
+ }
+
VertexId Vertex(VertexId old)
{
if (vertexMap.TryGetValue(old, out var mapped)) return mapped;
- if (!source.TryGetVertexPoint(old, out var point)) throw new InvalidOperationException("Unbound stitch vertex.");
+ if (!source.TryGetVertexPoint(old, out var point)) throw new InvalidOperationException("Unbound composition vertex.");
mapped = topology.AddVertex();
vertexMap.Add(old, mapped);
points.Add(mapped, point);
@@ -197,7 +210,7 @@ internal static class HexBoltThreadStitch
foreach (var oldLoop in face.LoopIds)
{
var loop = source.Topology.GetLoop(oldLoop);
- if (loop.Kind != LoopKind.Edge) throw new InvalidOperationException("HexBolt thread stitch requires edge loops.");
+ if (loop.Kind != LoopKind.Edge) throw new InvalidOperationException("HexBolt thread composition requires edge loops.");
var loopId = topology.AllocateLoopId();
var coedgeIds = loop.CoedgeIds.Select(_ => topology.AllocateCoedgeId()).ToArray();
for (var i = 0; i < coedgeIds.Length; i++)
@@ -223,74 +236,29 @@ internal static class HexBoltThreadStitch
bindings.AddFaceBoundaryRoleBinding(role with { FaceId = newFace, LoopId = loop.Value });
foreach (var oldCoedge in oldToNewCoedges)
if (source.Bindings.TryGetPcurveBinding(oldCoedge.Key, out var pcurve))
+ {
+ var oldEdge = source.Topology.GetCoedge(oldCoedge.Key).EdgeId;
+ if (sharedEdges is not null && sharedEdges.TryGetValue(oldEdge, out var newEdge))
+ {
+ if (pcurve.Pcurve.Kind != PcurveGeometryKind.Line)
+ throw new InvalidOperationException("Shared rim requires a linear pcurve.");
+ var uv = pcurve.Pcurve;
+ var reverse = reversedShared.Contains(oldEdge);
+ var trim = bindings.GetEdgeBinding(newEdge).TrimInterval!.Value;
+ pcurve = pcurve with { Pcurve = PcurveGeometry.Line(trim,
+ uv.Evaluate(reverse ? uv.Domain.End : uv.Domain.Start),
+ uv.Evaluate(reverse ? uv.Domain.Start : uv.Domain.End)) };
+ }
bindings.AddPcurveBinding(pcurve with { CoedgeId = oldCoedge.Value, FaceId = newFace,
SurfaceGeometryId = Surface(pcurve.SurfaceGeometryId) });
+ }
foreach (var oldLoop in face.LoopIds)
if (source.Bindings.TryGetVertexLoopParameterBinding(oldLoop, out var parameter))
- throw new InvalidOperationException("HexBolt thread stitch does not admit vertex-loop faces.");
+ throw new InvalidOperationException("HexBolt thread composition does not admit vertex-loop faces.");
}
return new(faceMap, edgeMap);
}
- internal void Annulus(double x, IReadOnlyList<EdgeId> outerArcs, EdgeId innerCircle, bool outwardPositive)
- {
- var normal = Direction3D.Create(new Vector3D(outwardPositive ? 1d : -1d, 0d, 0d));
- var radial = Direction3D.Create(new Vector3D(0d, 1d, 0d));
- var surfaceId = new SurfaceGeometryId(nextSurface++);
- geometry.AddSurface(surfaceId, SurfaceGeometry.FromPlane(new PlaneSurface(new Point3D(x, 0d, 0d), normal, radial)));
- var outer = OrderOppositeUses(outerArcs);
- var inner = OrderOppositeUses([innerCircle]);
- var outerLoop = Loop(outer);
- var innerLoop = Loop(inner);
- var face = topology.AddFace([outerLoop, innerLoop]);
- faces.Add(face);
- bindings.AddFaceBinding(new FaceGeometryBinding(face, surfaceId));
- bindings.AddFaceBoundaryRoleBinding(new(face, outerLoop, FaceBoundaryRole.Outer));
- bindings.AddFaceBoundaryRoleBinding(new(face, innerLoop, FaceBoundaryRole.Inner));
- }
-
- private (EdgeId Edge, bool Reverse)[] OrderOppositeUses(IReadOnlyList<EdgeId> edges)
- {
- var uses = edges.Select(edge => (Edge: edge, Reverse: !ExistingUse(edge))).ToArray();
- if (uses.Length == 1) return uses;
- var first = uses[0];
- var second = uses[1];
- if (End(first) != Start(second)) (first, second) = (second, first);
- if (End(first) != Start(second) || End(second) != Start(first))
- throw new InvalidOperationException("HexBolt stitch boundary arcs do not form a closed ring.");
- return [first, second];
- }
-
- private bool ExistingUse(EdgeId edge)
- {
- var uses = topology.Model.Coedges.Where(item => item.EdgeId == edge).ToArray();
- if (uses.Length != 1) throw new InvalidOperationException("Stitch boundary must have one retained coedge use.");
- return uses[0].IsReversed;
- }
-
- private VertexId Start((EdgeId Edge, bool Reverse) use)
- {
- var edge = topology.Model.GetEdge(use.Edge);
- return use.Reverse ? edge.EndVertexId : edge.StartVertexId;
- }
-
- private VertexId End((EdgeId Edge, bool Reverse) use)
- {
- var edge = topology.Model.GetEdge(use.Edge);
- return use.Reverse ? edge.StartVertexId : edge.EndVertexId;
- }
-
- private LoopId Loop(IReadOnlyList<(EdgeId Edge, bool Reverse)> uses)
- {
- var loopId = topology.AllocateLoopId();
- var ids = uses.Select(_ => topology.AllocateCoedgeId()).ToArray();
- for (var i = 0; i < ids.Length; i++)
- topology.AddCoedge(new Coedge(ids[i], uses[i].Edge, loopId,
- ids[(i + 1) % ids.Length], ids[(i + ids.Length - 1) % ids.Length], uses[i].Reverse));
- topology.AddLoop(new Loop(loopId, ids));
- return loopId;
- }
-
internal BrepBody Complete()
{
var shell = topology.AddShell(faces);
diff --git a/Aetheris.Kernel.Firmament/Materializer/PlanarCapEngraving.cs b/Aetheris.Kernel.Firmament/Materializer/PlanarCapEngraving.cs
new file mode 100644
index 00000000..1f1f593d
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Materializer/PlanarCapEngraving.cs
@@ -0,0 +1,101 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Core.Topology;
+
+namespace Aetheris.Kernel.Firmament.Materializer;
+
+/// <summary>Bounded engraving on a circular YZ cap, using the existing text profiles and section-stack emitter.</summary>
+public static class PlanarCapEngraving
+{
+ public sealed record Result(BrepBody Body, string StepText, PrismaticSectionStackConstruction Section,
+ PlanarTextProfileResult Text, double Depth, FaceId OriginalTopFace)
+ {
+ internal HexBoltThreadComposition.PatchResult? Composition { get; init; }
+ }
+
+ public static Result Build(string threadedHexBoltSource, string content, double heightMm, double depthMm)
+ {
+ var compiled = FirmamentBuildAndExport.CompileSource(threadedHexBoltSource);
+ if (!compiled.IsSuccess || compiled.Value.RuntimeBody is null || compiled.Value.Thread is null ||
+ compiled.Value.StandardPart?.Family != "HexBolt")
+ throw new InvalidOperationException("Maker mark requires a compiled threaded HexBolt: " +
+ string.Join(" | ", compiled.Diagnostics.Select(x => x.Message)));
+ var host = compiled.Value.RuntimeBody;
+ var topId = compiled.Value.StandardPart.SemanticDescendants.Single(x =>
+ x.StableId.EndsWith(".Head.TopFlat", StringComparison.Ordinal)).FaceId;
+ if (topId is null) throw new InvalidOperationException("Threaded HexBolt top face is missing.");
+ var topFace = new FaceId(topId.Value);
+ return Engrave(host, topFace, content, heightMm, depthMm);
+ }
+
+ internal static Result Engrave(BrepBody host, FaceId topFace, string content, double heightMm, double depthMm)
+ {
+ if (!double.IsFinite(depthMm) || depthMm <= 0d || depthMm > .3d)
+ throw new ArgumentOutOfRangeException(nameof(depthMm));
+ var (disk, topX) = DiskFromTopRim(host, topFace);
+ var text = PlanarTextProfiles.Build(content, heightMm, PlanarTextAlignment.Center);
+ if (!text.Succeeded) throw new InvalidOperationException(string.Join(" | ", text.Diagnostics));
+ var profiles = text.Regions.Select(region => region with { PlaneFrame = "YZ" }).Append(disk)
+ .ToDictionary(x => x.Name, StringComparer.Ordinal);
+ var operations = new List<PrismaticProfileOperation>
+ {
+ new("HeadCap", PrismaticProfileIntent.Base, disk.Name, -2d * depthMm, 0d, "Stock", "maker-mark")
+ };
+ operations.AddRange(text.Regions.Select((region, index) => new PrismaticProfileOperation(
+ $"Mark{index}", PrismaticProfileIntent.Remove, region.Name, -depthMm, 0d,
+ "Pocket", "maker-mark")));
+ var feature = new PrismaticProfileCompositionFeature("MakerMark", "YZ", "-X",
+ new PrismaticProfilePlacement("HeadTop", topX, 0d, 0d, "YZ", "-X", "+Y", true),
+ operations, [-2d * depthMm, -depthMm, 0d], "maker-mark");
+ var section = PrismaticSectionStackCompiler.Normalize(new(feature, profiles, []), out var diagnostics);
+ if (section is null) throw new InvalidOperationException("Maker mark section: " + string.Join(" | ", diagnostics));
+ var planned = PrismaticSectionStackEmitter.Emit(section);
+ if (planned.Body is null || planned.Plan?.TopologyPlan is null)
+ throw new InvalidOperationException("Maker mark BRep: " + string.Join(" | ", planned.Diagnostics));
+ var patchFaces = planned.Plan.TopologyPlan.FaceMappings.Where(mapping =>
+ (mapping.Kind == "TransitionCap" && mapping.ConstructionStableId != $"transition:{-2d * depthMm:R}") ||
+ (mapping.Kind == "PrismaticSide" && mapping.SourceStableId.Contains("Text.Glyph[", StringComparison.Ordinal)))
+ .Select(mapping => mapping.FaceId).ToArray();
+ var composition = HexBoltThreadComposition.ImprintTop(host, topFace, planned.Body, patchFaces);
+ var body = composition.Body;
+ var step = Step242Exporter.ExportBody(body, new Step242ExportOptions
+ {
+ ProductName = "ThreadedHexBoltMakerMark",
+ ApplicationName = "Aetheris.Firmament.MakerMark.X2",
+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce
+ });
+ if (!step.IsSuccess) throw new InvalidOperationException("Maker mark STEP: " +
+ string.Join(" | ", step.Diagnostics.Select(x => x.Message)));
+ return new(body, step.Value, section, text, depthMm, topFace) { Composition = composition };
+ }
+
+ private static (ResolvedProfile2D Profile, double TopX) DiskFromTopRim(BrepBody body, FaceId topFace)
+ {
+ var face = body.Topology.GetFace(topFace);
+ if (face.LoopIds.Count != 1) throw new InvalidOperationException("Maker mark head cap requires one circular outer loop.");
+ var coedges = body.Topology.GetLoop(face.LoopIds[0]).CoedgeIds;
+ var segments = new List<ResolvedProfileSegment2D>();
+ double? topX = null;
+ foreach (var (coedgeId, index) in coedges.Reverse().Select((id, i) => (id, i)))
+ {
+ var coedge = body.Topology.GetCoedge(coedgeId);
+ var edge = body.Topology.GetEdge(coedge.EdgeId);
+ var startVertex = coedge.IsReversed ? edge.StartVertexId : edge.EndVertexId;
+ var endVertex = coedge.IsReversed ? edge.EndVertexId : edge.StartVertexId;
+ body.TryGetVertexPoint(startVertex, out var start);
+ body.TryGetVertexPoint(endVertex, out var end);
+ topX ??= start.X;
+ if (Math.Abs(start.X - topX.Value) > 1e-7d || Math.Abs(end.X - topX.Value) > 1e-7d)
+ throw new InvalidOperationException("Maker mark head cap is not planar on X.");
+ var radius = Math.Sqrt(start.Y * start.Y + start.Z * start.Z);
+ var angle = Math.Atan2(-start.Z, start.Y);
+ var finish = Math.Atan2(-end.Z, end.Y);
+ var sweep = finish - angle;
+ while (sweep <= 0d) sweep += 2d * Math.PI;
+ if (sweep >= Math.PI) throw new InvalidOperationException("Maker mark rim arc is not bounded below 180 degrees.");
+ segments.Add(new($"Rim{index}", new LineArcCircularArc2D((0d, 0d), radius, angle, sweep),
+ new ProfileSegmentProvenance($"profile:HeadTop.Rim{index}", "HeadTop", "head-cap", "bolt-top-rim", "YZ")));
+ }
+ return (new ResolvedProfile2D("HeadTop", "YZ", [new ResolvedProfileLoop2D("Outer", true, segments)]), topX!.Value);
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/Materializer/ThreadedHexBoltMakerMark.cs b/Aetheris.Kernel.Firmament/Materializer/ThreadedHexBoltMakerMark.cs
index 6d83c0f1..ae353f93 100644
--- a/Aetheris.Kernel.Firmament/Materializer/ThreadedHexBoltMakerMark.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/ThreadedHexBoltMakerMark.cs
@@ -1,92 +1,9 @@
-using Aetheris.Kernel.Core.Brep;
-using Aetheris.Kernel.Core.Step242;
-using Aetheris.Kernel.Core.Topology;
-
namespace Aetheris.Kernel.Firmament.Materializer;
-/// <summary>A planar maker mark on the existing threaded HexBolt head cap.</summary>
+/// <summary>Compatibility entry point. Canonical witnesses author MakerMark in StandardPart.</summary>
+[Obsolete("Author MakerMark, MakerMarkHeight and MakerMarkDepth on the HexBolt StandardPart instead.")]
public static class ThreadedHexBoltMakerMark
{
- public sealed record Result(BrepBody Body, string StepText, PrismaticSectionStackConstruction Section,
- PlanarTextProfileResult Text, double Depth, FaceId OriginalTopFace);
-
- public static Result Build(string threadedHexBoltSource, string content, double heightMm, double depthMm)
- {
- if (!double.IsFinite(depthMm) || depthMm <= 0d || depthMm > .3d)
- throw new ArgumentOutOfRangeException(nameof(depthMm));
- var compiled = FirmamentBuildAndExport.CompileSource(threadedHexBoltSource);
- if (!compiled.IsSuccess || compiled.Value.RuntimeBody is null || compiled.Value.Thread is null ||
- compiled.Value.StandardPart?.Family != "HexBolt")
- throw new InvalidOperationException("Maker mark requires a compiled threaded HexBolt: " +
- string.Join(" | ", compiled.Diagnostics.Select(x => x.Message)));
- var host = compiled.Value.RuntimeBody;
- var topId = compiled.Value.StandardPart.SemanticDescendants.Single(x =>
- x.StableId.EndsWith(".Head.TopFlat", StringComparison.Ordinal)).FaceId;
- if (topId is null) throw new InvalidOperationException("Threaded HexBolt top face is missing.");
- var topFace = new FaceId(topId.Value);
- var (disk, topX) = DiskFromTopRim(host, topFace);
- var text = PlanarTextProfiles.Build(content, heightMm, PlanarTextAlignment.Center);
- if (!text.Succeeded) throw new InvalidOperationException(string.Join(" | ", text.Diagnostics));
- var profiles = text.Regions.Select(region => region with { PlaneFrame = "YZ" }).Append(disk)
- .ToDictionary(x => x.Name, StringComparer.Ordinal);
- var operations = new List<PrismaticProfileOperation>
- {
- new("HeadCap", PrismaticProfileIntent.Base, disk.Name, -2d * depthMm, 0d, "Stock", "maker-mark")
- };
- operations.AddRange(text.Regions.Select((region, index) => new PrismaticProfileOperation(
- $"Mark{index}", PrismaticProfileIntent.Remove, region.Name, -depthMm, 0d,
- "Pocket", "maker-mark")));
- var feature = new PrismaticProfileCompositionFeature("MakerMark", "YZ", "-X",
- new PrismaticProfilePlacement("HeadTop", topX, 0d, 0d, "YZ", "-X", "+Y", true),
- operations, [-2d * depthMm, -depthMm, 0d], "maker-mark");
- var section = PrismaticSectionStackCompiler.Normalize(new(feature, profiles, []), out var diagnostics);
- if (section is null) throw new InvalidOperationException("Maker mark section: " + string.Join(" | ", diagnostics));
- var planned = PrismaticSectionStackEmitter.Emit(section);
- if (planned.Body is null || planned.Plan?.TopologyPlan is null)
- throw new InvalidOperationException("Maker mark BRep: " + string.Join(" | ", planned.Diagnostics));
- var patchFaces = planned.Plan.TopologyPlan.FaceMappings.Where(mapping =>
- (mapping.Kind == "TransitionCap" && mapping.ConstructionStableId != $"transition:{-2d * depthMm:R}") ||
- (mapping.Kind == "PrismaticSide" && mapping.SourceStableId.Contains("Text.Glyph[", StringComparison.Ordinal)))
- .Select(mapping => mapping.FaceId).ToArray();
- var body = HexBoltThreadStitch.ImprintTop(host, topFace, planned.Body, patchFaces);
- var step = Step242Exporter.ExportBody(body, new Step242ExportOptions
- {
- ProductName = "ThreadedHexBoltMakerMark",
- ApplicationName = "Aetheris.Firmament.MakerMark.X2",
- BrepExportPreflightMode = BrepExportPreflightMode.Enforce
- });
- if (!step.IsSuccess) throw new InvalidOperationException("Maker mark STEP: " +
- string.Join(" | ", step.Diagnostics.Select(x => x.Message)));
- return new(body, step.Value, section, text, depthMm, topFace);
- }
-
- private static (ResolvedProfile2D Profile, double TopX) DiskFromTopRim(BrepBody body, FaceId topFace)
- {
- var face = body.Topology.GetFace(topFace);
- if (face.LoopIds.Count != 1) throw new InvalidOperationException("Maker mark head cap requires one circular outer loop.");
- var coedges = body.Topology.GetLoop(face.LoopIds[0]).CoedgeIds;
- var segments = new List<ResolvedProfileSegment2D>();
- double? topX = null;
- foreach (var (coedgeId, index) in coedges.Reverse().Select((id, i) => (id, i)))
- {
- var coedge = body.Topology.GetCoedge(coedgeId);
- var edge = body.Topology.GetEdge(coedge.EdgeId);
- var startVertex = coedge.IsReversed ? edge.StartVertexId : edge.EndVertexId;
- var endVertex = coedge.IsReversed ? edge.EndVertexId : edge.StartVertexId;
- body.TryGetVertexPoint(startVertex, out var start);
- body.TryGetVertexPoint(endVertex, out var end);
- topX ??= start.X;
- if (Math.Abs(start.X - topX.Value) > 1e-7d || Math.Abs(end.X - topX.Value) > 1e-7d)
- throw new InvalidOperationException("Maker mark head cap is not planar on X.");
- var radius = Math.Sqrt(start.Y * start.Y + start.Z * start.Z);
- var angle = Math.Atan2(-start.Z, start.Y);
- var finish = Math.Atan2(-end.Z, end.Y);
- var sweep = finish - angle;
- while (sweep <= 0d) sweep += 2d * Math.PI;
- if (sweep >= Math.PI) throw new InvalidOperationException("Maker mark rim arc is not bounded below 180 degrees.");
- segments.Add(new($"Rim{index}", new LineArcCircularArc2D((0d, 0d), radius, angle, sweep),
- new ProfileSegmentProvenance($"profile:HeadTop.Rim{index}", "HeadTop", "head-cap", "bolt-top-rim", "YZ")));
- }
- return (new ResolvedProfile2D("HeadTop", "YZ", [new ResolvedProfileLoop2D("Outer", true, segments)]), topX!.Value);
- }
+ public static PlanarCapEngraving.Result Build(string source, string content, double heightMm, double depthMm)
+ => PlanarCapEngraving.Build(source, content, heightMm, depthMm);
}
diff --git a/Aetheris.Kernel.StandardLibrary/HexBoltParameterBinding.cs b/Aetheris.Kernel.StandardLibrary/HexBoltParameterBinding.cs
index 4b91eb70..d8fa4ff0 100644
--- a/Aetheris.Kernel.StandardLibrary/HexBoltParameterBinding.cs
+++ b/Aetheris.Kernel.StandardLibrary/HexBoltParameterBinding.cs
@@ -19,9 +19,23 @@ public static class HexBoltParameterBinding
var missing = RequiredFields.Where(field => !fields.TryGetValue(field, out var value) || string.IsNullOrWhiteSpace(value)).ToArray();
if (missing.Length > 0) return Failure($"Missing required HexBolt parameter(s): {string.Join(", ", missing)}.", "MissingField");
- var allowed = RequiredFields.Append("StableId").ToHashSet(StringComparer.Ordinal);
+ var allowed = RequiredFields.Concat(["StableId", "MakerMark", "MakerMarkHeight", "MakerMarkDepth"]).ToHashSet(StringComparer.Ordinal);
var unknown = fields.Keys.Where(field => !allowed.Contains(field)).ToArray();
if (unknown.Length > 0) return Failure($"Unknown HexBolt parameter(s): {string.Join(", ", unknown)}.", "UnknownField");
+ var engraving = new[] { "MakerMark", "MakerMarkHeight", "MakerMarkDepth" };
+ if (engraving.Any(fields.ContainsKey))
+ {
+ if (!engraving.All(fields.ContainsKey) || string.IsNullOrWhiteSpace(Text(fields["MakerMark"])))
+ return Failure("MakerMark requires content, MakerMarkHeight, and MakerMarkDepth.", "InvalidMakerMark");
+ foreach (var field in engraving.Skip(1))
+ {
+ var raw = fields[field].Trim();
+ if (!raw.EndsWith("mm", StringComparison.Ordinal) ||
+ !double.TryParse(raw[..^2], NumberStyles.Float, CultureInfo.InvariantCulture, out var value) ||
+ !double.IsFinite(value) || value <= 0d)
+ return Failure($"{field} must be a finite positive length in mm.", "InvalidMakerMark");
+ }
+ }
var numericNames = RequiredFields.Where(field => field is not ("ThreadDesignation" or "PropertyClass")).ToArray();
var values = new Dictionary<string, double>(StringComparer.Ordinal);
diff --git a/Aetheris.Kernel.StandardLibrary/StandardLibraryReusableParts.cs b/Aetheris.Kernel.StandardLibrary/StandardLibraryReusableParts.cs
index 1a38c21d..89f940e0 100644
--- a/Aetheris.Kernel.StandardLibrary/StandardLibraryReusableParts.cs
+++ b/Aetheris.Kernel.StandardLibrary/StandardLibraryReusableParts.cs
@@ -25,7 +25,8 @@ public static class StandardLibraryReusableParts
public static KernelResult<StandardLibraryPartDefinition> TryCreate(
string partName,
- IReadOnlyDictionary<string, string> parameters)
+ IReadOnlyDictionary<string, string> parameters,
+ bool deferMakerMarkToCompiler = false)
{
if (string.Equals(partName, CubeWithCylindricalHolePartName, StringComparison.Ordinal))
{
@@ -42,6 +43,10 @@ public static class StandardLibraryReusableParts
var parsed = HexBoltParameterBinding.Bind(parameters);
if (!parsed.IsSuccess) return KernelResult<StandardLibraryPartDefinition>.Failure(parsed.Diagnostics);
+ if (parameters.ContainsKey("MakerMark") && !deferMakerMarkToCompiler)
+ return KernelResult<StandardLibraryPartDefinition>.Failure([new KernelDiagnostic(
+ KernelDiagnosticCode.InvalidArgument, KernelDiagnosticSeverity.Error,
+ "HexBolt MakerMark requires the standalone Firmament part compiler; reusable assembly engraving is not yet supported.")]);
var bodyStableId = parameters.TryGetValue("StableId", out var authoredId) && !string.IsNullOrWhiteSpace(authoredId)
? HexBoltParameterBinding.Text(authoredId)
: "HexBolt";
diff --git a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
index 52dad6ea..8d60c516 100644
--- a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
+++ b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
@@ -11,6 +11,22 @@ namespace Aetheris.Server.Tests;
public sealed class KernelApiIntegrationTests : IClassFixture<WebApplicationFactory<Program>>
{
+ [Fact]
+ public async Task DisplayPrepare_ThreadedShowcase_ShadesEveryRequiredFace()
+ {
+ var source = await File.ReadAllTextAsync(GetRepositoryPath("fixtures/Thread/hexbolt-showcase.firmament"));
+ var built = Aetheris.Kernel.Firmament.FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(built.IsSuccess, string.Join(" | ", built.Diagnostics.Select(d => d.Message)));
+ var document = await CreateDocumentAsync("/api/v1/documents");
+ var response = await _client.PostAsJsonAsync($"/api/v1/documents/{document.Data!.DocumentId}/import/step",
+ new StepImportRequestDto(built.Value.StepText, "hexbolt-showcase.step"));
+ response.EnsureSuccessStatusCode();
+ var imported = await response.Content.ReadFromJsonAsync<ApiResponseDto<StepImportResponseDto>>();
+ var prepared = await PrepareDisplayAsync(document.Data.DocumentId, imported!.Data!.OccurrenceId);
+ Assert.Equal("Complete", prepared.Data!.Status);
+ Assert.DoesNotContain(prepared.Data.Faces!, f => f.Status == "WireOnly");
+ Assert.Equal(built.Value.RuntimeBody!.Topology.Faces.Count(), prepared.Data.Faces!.Count);
+ }
[Fact]
public async Task StepImport_ExportedAssembly_ReturnsCadmataInstanceScene()
{
diff --git a/docs/public/firmament/threads.md b/docs/public/firmament/threads.md
new file mode 100644
index 00000000..3cb84dd5
--- /dev/null
+++ b/docs/public/firmament/threads.md
@@ -0,0 +1,25 @@
+# Bounded external threads
+
+The external `Thread` feature cuts a finite groove into continuous major-diameter cylindrical stock. It supports the existing metric 60-degree truncated profile on a Cylinder or standalone HexBolt shank. The helical law, certified spline realization, and seam topology remain BRep authority.
+
+`StartOffset` positions the groove centerline relative to the exposed cylindrical support start. `Length` sets its finite axial span; the bounded implementation admits 1–40 complete turns. The groove's outer footprint extends `7 * Pitch / 16` beyond each centerline endpoint. Leave stock outside that footprint at both ends. A HexBolt's support starts after `UnderHeadRadius` and ends before `TipChamferLength`. Invalid margins produce `thread-support-bounds` rather than clipping a thread into the head or chamfer.
+
+The canonical Preview 4 witness is [hexbolt-showcase.firmament](../../../fixtures/Thread/hexbolt-showcase.firmament). Its 52 mm stock preserves 38 turns at 1.25 mm pitch, with 0.953125 mm of head-side land and 1.315625 mm of tip-side land. No tapered manufacturing runout is modeled.
+
+```firmament
+Thread MainThread {
+ Surface: face(Bolt.Shank)
+ MajorDiameter: 8mm
+ Pitch: 1.25mm
+ Length: 47.5mm
+ StartOffset: 1.5mm
+}
+```
+
+A standalone HexBolt may author `MakerMark`, `MakerMarkHeight`, and `MakerMarkDepth` together. Height and depth require explicit positive millimetres; the existing bounded planar cap engraving admits depth up to 0.3 mm. For example, `MakerMark: "CODEX"`, `MakerMarkHeight: 2.5mm`, `MakerMarkDepth: 0.2mm` reuse the established text profiles and counter handling. Reusable assembly engraving is explicitly unsupported. The old `ThreadedHexBoltMakerMark` C# entry point is deprecated.
+
+Build through the repository CLI:
+
+```powershell
+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll build fixtures/Thread/hexbolt-showcase.firmament --output artifacts/local/p4-01b/showcase/bolt-cli.step --json
+```
diff --git a/docs/release/P4-01B-CLOSEOUT.md b/docs/release/P4-01B-CLOSEOUT.md
new file mode 100644
index 00000000..3e523f04
--- /dev/null
+++ b/docs/release/P4-01B-CLOSEOUT.md
@@ -0,0 +1,36 @@
+# P4-01B closeout
+
+**Verdict: Accepted — B1 and B2.**
+
+1. **The bolt is a credible Preview 4 mechanical showcase.** Normal Firmament authors continuous major-diameter stock minus a finite helical groove, with 0.953125 mm head-side and 1.315625 mm tip-side cylindrical lands. The under-head fillet and tip chamfer meet ordinary shaft stock. The 38 turns, 1.25 mm pitch and CODEX engraving with two counters remain. Stock length is deliberately 52 mm to preserve the thread span while providing these lands.
+2. **STEP is free of the obvious avoidable bloat found in this audit.** Export-local exact immutable geometry sharing saves 35.064% against the repaired artifact. Topology, pcurve associations, numeric literals and AP242 structures remain equivalent. Remaining size is predominantly unique certified spline/control geometry.
+
+| Stage | STEP bytes |
+| --- | ---: |
+| Original engraved witness | 9,028,303 |
+| Repaired geometry, before optimization | 6,991,354 |
+| Final optimized artifact | 4,539,892 |
+
+B1 was accepted before B2 profiling/optimization. [B1 report](P4-01B1-THREAD-SHOWCASE-REPAIR.md) documents the physical repair, wire-only timeout audit, legal spline knots, numerical evaluator fix and obsolete-generator deprecation. [B2 report](P4-01B2-STEP-COMPACTNESS-X0.md) documents entity/byte attribution, exact duplication, interning scope, precision and timing evidence.
+
+## Validation
+
+The final normal CLI and opt-in topology/display audit produce identical STEP bytes: SHA256 `2376F5E53F715716F4F0823C3787059B0E69337B22EFA39F93357F4951BE89E8`. Aetheris reimports one enclosed, orientation-consistent shell/body with 293 faces, 689 edges, 406 vertices and two uses per edge. All 293 faces shade; zero wire-only faces remain. Native FreeCAD independently imports one valid closed solid with unchanged repaired bounds and volume. An ordinary unthreaded fixture also passes native roundtrip and unchanged graph comparison.
+
+Normal Cadmata Auto preparation reports `Complete` under its original five-second budget; actual face selection and close zoom work. Helios rebuilds the same authored source through the final SDK and shows the complete bolt with zero diagnostics. Its non-AOT worker took 251.251 s under concurrent test load (compile 232.585 s, mesh 9.192 s). The earlier isolated B1 build took 209.625 s; engraving dominates this remaining latency. No text feature redesign was added.
+
+Release solution build: **zero errors** (five existing Web runtime warnings). Core fast lane: **1,017 passed**. Full serial solution lane: **4,340 passed across 20 projects, zero failures/skips**, including 1,150 Core, 2,012 Firmament and 62 Server tests. The final authored topology/display audit and 13 documentation qualification checks pass. Logs: `artifacts/local/p4-01b-final-build.log`, `p4-01b-final-fast.log`, `p4-01b-final-full.log`, `p4-01b-final-audit.log`, and `p4-01b-final-doc-tests.log`. The test-regenerated tracked ellipse STEP is restored; its current-export copy is retained only in ignored evidence. The intended NIST snapshot change contains 16 serialization hashes and no status, diagnostic or topology changes.
+
+## Deliverables
+
+- [Canonical Firmament source](../../fixtures/Thread/hexbolt-showcase.firmament)
+- [Final STEP](../../artifacts/local/p4-01b/showcase/bolt-cli.step)
+- [Cadmata full bolt](../../artifacts/local/p4-01b/showcase/cadmata-full.jpg)
+- [Head/thread and under-head fillet](../../artifacts/local/p4-01b/showcase/cadmata-head-thread.jpg)
+- [Tip/thread transition](../../artifacts/local/p4-01b/showcase/cadmata-tip-thread.jpg)
+- [Maker mark](../../artifacts/local/p4-01b/showcase/cadmata-maker-mark.jpg)
+- [Final face selection](../../artifacts/local/p4-01b/showcase/cadmata-selection.jpg)
+- [Final Helios witness](../../artifacts/local/p4-01b/showcase/helios-final.jpg)
+- [Before entity/size profile](../../artifacts/local/p4-01b/compactness/before-profile.json), [after profile](../../artifacts/local/p4-01b/compactness/after-profile.json), [compactness comparison](../../artifacts/local/p4-01b/compactness/comparison.json)
+
+Generated evidence remains ignored under `artifacts/local/`. The dedicated cleanup removes phase probes, the old root-rod/annular-shoulder stitch, and canonical dependency on the deprecated C# showcase generator. No manufacturing runout, broad Boolean/kernel redesign, cosmetic thread substitution, lossy precision, or Preview 4 distribution work was introduced.
diff --git a/docs/release/P4-01B1-THREAD-SHOWCASE-REPAIR.md b/docs/release/P4-01B1-THREAD-SHOWCASE-REPAIR.md
new file mode 100644
index 00000000..a2bdfdb7
--- /dev/null
+++ b/docs/release/P4-01B1-THREAD-SHOWCASE-REPAIR.md
@@ -0,0 +1,41 @@
+# P4-01B1 — Thread showcase repair
+
+## Construction
+
+Canonical source: `fixtures/Thread/hexbolt-showcase.firmament`. The standalone Firmament compiler creates continuous 8 mm major-diameter stock with a bounded inward helical groove. The established helical law, flank/root realization certificates, and complete-turn seams are reused. Known head, fillet, shank, and tip boundaries compose directly through shared major-radius rim edges. There is no independently attached root-stock rod, annular replacement shoulder, general Boolean, mesh mutation, or fixture-only geometry rewrite.
+
+The shaft is deliberately 52 mm instead of the former 50 mm. Keeping the original 1.25 mm pitch, 47.5 mm span, and 38 turns on 50 mm stock left only 0.26875 mm total land after accounting for the groove footprint and transitions. The new source uses `StartOffset: 1.5mm`, leaving 0.953125 mm after the existing 0.2 mm under-head fillet and 1.315625 mm before the existing 0.9375 mm tip chamfer. These dimensions are authored data. The existing `StartOffset` and `Length` semantics control other bolts too. No tapered runout was needed.
+
+The optional HexBolt fields `MakerMark`, `MakerMarkHeight`, and `MakerMarkDepth` invoke the existing planar text/section-stack machinery. CODEX remains 2.5 mm high and 0.2 mm deep with two counters. The old `ThreadedHexBoltMakerMark` C# generator is a deprecated compatibility adapter; the canonical build has no dependency on it. Unsupported reusable assembly engraving is rejected explicitly rather than silently omitted.
+
+## Wire-only audit and native STEP
+
+The historical 37 wire-only display faces were a time-budget defect, separate from the poor physical termination. Re-running the original STEP with the previous five-second whole-body preparation budget omitted 39 B-spline faces in this run (IDs 138–176). The exact count depends on how far tessellation gets before cancellation. Every missing face has a timeout diagnostic. A complete 60-second audit shades every original required face. The audit compares all BRep face IDs against shaded patches, including faces absent from partial results.
+
+An initial 30-second product budget proved the missing faces were computable. That temporary increase was removed after correcting the evaluator cost below. Normal Cadmata now returns `Complete` within its original five-second preparation budget, shades all 293 faces, and produces zero wire-only faces. Diagnostic fallback and CIR policy are unchanged.
+
+The normal Helios regression exposed a separate numerical cost: tensor-product B-spline evaluation computed every V row although U de Boor consumes only `DegreeU + 1` rows. The evaluator now computes the active rows and reuses the same blend arithmetic. Polynomial and rational nonuniform nets compare exactly against independent 1D tensor evaluation, including interior knots and clamped endpoints. This changes computation cost, not geometry or STEP serialization.
+
+Independent native import also exposed invalid cubic knot multiplicities in the previous helical spline realization: interior knots repeated four times for degree three. Adjacent Hermite spans now share endpoint controls, with multiplicity three internally and four at the ends. The represented polynomials and error certificates are unchanged. This obeys the [OCCT B-spline curve contract](https://occt3d.com/dev/doc/refman/html/class_geom___b_spline_curve.html) and [surface contract](https://occt3d.com/dev/doc/refman/html/class_geom___b_spline_surface.html). It is a geometry representation correctness fix made in B1, before compactness work.
+
+The normal CLI builds the repaired STEP and Aetheris reimports it as one shell/body: 293 faces, 689 edges, 406 vertices. Every edge has two uses; enclosure and orientation checks pass. FreeCAD 1.0.2 / OCCT independently imports one valid, closed solid with the same 293 faces, 693 edges and 408 vertices (its translator adds seam splits). Native volume is 2938.769841889224 mm³; bounds are X [-5.3, 52], Y/Z approximately [-7.505553499465, 7.505553499465] mm. The tessellation-based Aetheris mass approximation is not claimed as an exact native-volume oracle.
+
+## Evidence
+
+Generated outputs are ignored under `artifacts/local/p4-01b/`:
+
+- `before/bolt.step`: original unmarked X1 thread witness, 8,798,446 bytes.
+- `before/engraved-bolt.step`: preserved original engraved X2 witness, 9,028,303 bytes.
+- `before/bolt.product-display.json`: old-budget missing-face identities and timeout reasons.
+- `before/cadmata-full.jpg`, `before/cadmata-transitions.jpg`: old construction in the current viewer with a complete preparation budget.
+- `showcase/bolt-cli.step`, `showcase/cli-build.json`, `showcase/audit.json`: normal authored build, roundtrip and topology/display evidence.
+- `showcase/freecad.json`: independent native import.
+- `showcase/cadmata-full.jpg`, `cadmata-head-thread.jpg`, `cadmata-tip-thread.jpg`, `cadmata-maker-mark.jpg`: actual normal Cadmata screenshots. Head close-up also records a highlighted selected thread face.
+
+The source, compiler ownership, deprecated generator, repeated dimensions, shared-edge composition, pcurve domain mapping, and temporary debug geometry were reviewed. No authored one-off C# bolt surgery remains in the canonical path. Historical X1 and X2 release notes now point here.
+
+## Verification
+
+Release solution build: zero errors. Core fast lane: 1,006 passed. Full serial solution lane: 4,327 passed, zero failures. After cleanup, 18 focused Firmament/thread/mark tests and the normal Cadmata display integration test pass. Final combined milestone validation is recorded in the closeout.
+
+**B1 verdict: Accepted.** The normal Helios local editor rebuilt the canonical source through the current Aetheris SDK, displayed one definition/occurrence, and reported zero diagnostics with source/display revision 1. Its non-AOT worker took 209.625 s (compile 192.769 s; mesh 8.512 s; transfer 24 ms). Temporary phase diagnostics isolated approximately 169 s in the established engraving path, then were removed. No text geometry redesign was attempted. This browser latency remains a practical limitation, not a failed geometry check. Source was pasted into the local editor because extension file upload was unavailable; no Helios repository source or dependency installation was changed. `showcase/helios-b1.jpg` and `helios-b1-phases.json` record this independent product path. B2 began only after this B1 acceptance.
diff --git a/docs/release/P4-01B2-STEP-COMPACTNESS-X0.md b/docs/release/P4-01B2-STEP-COMPACTNESS-X0.md
new file mode 100644
index 00000000..107c6642
--- /dev/null
+++ b/docs/release/P4-01B2-STEP-COMPACTNESS-X0.md
@@ -0,0 +1,80 @@
+# P4-01B2 — STEP compactness X0
+
+B2 began after [B1 acceptance](P4-01B1-THREAD-SHOWCASE-REPAIR.md). The audited artifact is the normal Firmament showcase, including its full modeled groove and engraved CODEX mark. Geometry representation repairs belong to B1; the B2 comparison uses identical repaired geometry.
+
+## Baseline and result
+
+| Artifact | Bytes | Lines | Entities |
+| --- | ---: | ---: | ---: |
+| Original engraved X2 witness | 9,028,303 | — | — |
+| Repaired B1, before exporter optimization | 6,991,354 | 83,644 | 83,635 |
+| Repaired B1, exact geometry sharing | 4,539,892 | 50,115 | 50,106 |
+
+The bounded exporter change saves **2,451,462 bytes (35.064%)** against repaired geometry, or 49.715% against the original engraved witness. The original unmarked X1 witness was 8,798,446 bytes. The latter comparison includes physical construction and legal spline representation changes, so it is not attributed entirely to exporter optimization.
+
+Both repaired exports have one body, 293 faces, 689 edges, and 406 vertices. Pitch is 1.25 mm, span 47.5 mm, with 38 turns and two maker-mark counters.
+
+## Entity and byte attribution
+
+`scripts/profile-step-entities.py` profiles actual UTF-8 entity lines. Complex entities are listed by their component type names joined with `+`. The JSON reports include the complete histogram, required types including zero counts, numeric literal lengths, exact duplicate definitions, and normalized graph digest.
+
+| Type | Before count / bytes | After count / bytes |
+| --- | ---: | ---: |
+| CARTESIAN_POINT | 74,693 / 5,736,970 | 43,824 / 3,385,829 |
+| B_SPLINE_SURFACE_WITH_KNOTS | 114 / 484,742 | 114 / 484,617 |
+| B_SPLINE_CURVE_WITH_KNOTS | 380 / 428,841 | 304 / 411,575 |
+| ORIENTED_EDGE | 1,378 / 56,498 | 1,378 / 56,498 |
+| DIRECTION | 1,217 / 40,562 | 58 / 2,811 |
+| DEFINITIONAL_REPRESENTATION | 618 / 36,462 | 618 / 36,462 |
+| EDGE_CURVE | 689 / 33,072 | 689 / 33,072 |
+| VECTOR | 1,057 / 32,964 | 42 / 1,207 |
+| LINE | 981 / 30,411 | 605 / 18,675 |
+| PCURVE | 618 / 19,796 | 618 / 19,796 |
+| EDGE_LOOP | 301 / 16,870 | 301 / 16,870 |
+| SURFACE_CURVE | 275 / 16,691 | 275 / 16,691 |
+| ADVANCED_FACE | 293 / 13,627 | 293 / 13,627 |
+
+Exact immutable duplication totaled **33,529 definitions / 2,443,384 serialized line bytes** before optimization. This includes 30,869 Cartesian points / 2,351,024 bytes, 1,159 directions, 1,015 vectors, 376 lines, 76 spline curves, 19 placements, 9 circles, and 6 planes. Duplicate line bytes exclude the additional effect of shorter renumbered references. After sharing, the audited immutable types have zero exact duplicates.
+
+The dominant repetition was control points shared mathematically by adjacent spline supports and boundary curves but serialized independently. Topology itself is modest. Distinct thread turns have different placed supports: none of the 114 spline surfaces is an exact duplicate. The remaining 6 hyperbolas, 76 linear-extrusion surfaces and 22 trimmed curves also have zero exact duplicates. Sharing leaf/control geometry addresses the evidence without merging face trims or changing the helical realization.
+
+## Bounded implementation and cleanup
+
+`Step242TextWriter` owns one ordinal dictionary per export. A whitelist admits immutable points, directions, vectors, placements, analytic supports/curves, and ordinary polynomial spline definitions. Keys include the complete serialized type, name, arguments, and already-resolved child references. First encounter determines numbering. No approximate equality, tolerance welding, global state, thread/bolt condition, alternate serializer, or persistent cache is introduced. Memory is bounded by the unique geometry in that export.
+
+Topology, pcurve/surface-curve associations, representation/product entities, and raw complex entities retain independent identities. Rational/raw entities are deliberately outside this bounded interner. No AP242 association or valid pcurve is removed. Repeated qualified pcurve geometry benefits from ordinary point/line sharing while all 618 pcurve and definitional-representation associations remain.
+
+Numeric formatting remains the existing invariant `0.#############` engineering formatter, including its cross-platform last-bit suppression contract. Actual literals were already compact; arbitrary decimal truncation would introduce a different precision policy. B2 changes no numeric strings. Product/context boilerplate is small and not accidentally multiplied per face; no metadata reduction was justified.
+
+The dedicated review covered cache ownership, exact equality, deterministic insertion order, names/dimensionality, excluded associations, memory lifetime, formatter ownership, and absence of showcase conditions. Temporary B1 phase probes are removed. The final SDK snapshot is built from unmodified production transport/runtime sources.
+
+## Correctness, determinism and external import
+
+The profiler's identity-independent graph digest recursively resolves references, retains every topology/association/metadata multiplicity, and counts equal immutable geometry once. Before and after share digest `F88C6A7B3B58E97CF242A1DCC7B74AB04FA7BD8B600A07ECB2F3EFA7183B05A4`. Thus names, geometry arguments, numeric text, topology, pcurves and semantic structures match after legal immutable sharing. This evidence complements actual reimport rather than replacing it.
+
+Four exports of the same runtime body compare byte-for-byte with the normal compiler result, each followed by import and topology-count checks. Final STEP SHA256 is `2376F5E53F715716F4F0823C3787059B0E69337B22EFA39F93357F4951BE89E8`; the repository CLI independently produces the same bytes.
+
+FreeCAD 1.0.2's normal native importer accepts the optimized STEP as one valid, closed solid/shell: 293 faces, 693 edges, 408 vertices. Native bounds and volume are exactly equal to the pre-optimization repaired artifact: 2938.769841889224 mm³, X [-5.3, 52], Y/Z approximately ±7.505553499465 mm. Translator seam splits explain its four extra edges and two extra vertices. No custom healing or geometry rewrite is applied.
+
+The ordinary unthreaded, unmarked HexBolt improves from 22,476 to 17,825 bytes (20.69%). Its normalized graph digest is unchanged; both native imports are valid/closed with one solid, 21 faces, 48 edges, 28 vertices, identical bounds and 3381.1925048367398 mm³ volume. This is a general exporter regression, independent of thread machinery.
+
+Existing semantic PMI and corpus tests exercise associated exports. The established snapshot updater refreshes 16 canonical serialization hashes; a separate comparison verifies every corpus success/failure, diagnostic and topology snapshot field remains identical. Cone checks now compare support values and every face's angle rather than requiring duplicate support definitions. The three surgery parity hashes are refreshed while binding, roundtrip, enclosure and orientation assertions remain.
+
+## Performance and remaining size
+
+Warm native .NET runs use one discarded warm-up plus three timed repeats on the same body; assertions and file writes are outside export/import timers. Milliseconds below are medians, not statistical performance guarantees.
+
+| Path | Export before → after | Import before → after |
+| --- | ---: | ---: |
+| Modeled/engraved bolt | 118.913 → 125.960 ms | 793.705 → 650.693 ms |
+| Ordinary bolt | 0.311 → 0.306 ms | 14.151 → 10.229 ms |
+
+The measured export increase is 5.9% (~7 ms), with 18.0% faster import and 35.1% smaller output. Native FreeCAD import measured 0.920 s before and 0.728 s after in separate single runs; startup/cache variance limits that comparison. No large CPU penalty is observed.
+
+Remaining size is primarily unique Cartesian control data (3,385,829 bytes, 74.6%), spline surfaces (484,617), and spline curves (411,575). These three consume 94.3% of output. They express the current certified piecewise helical and engraved geometry; a smaller representation would require a separate geometric realization/tolerance project. This audit does not claim a mathematically minimal STEP encoding. It establishes that obvious exact duplication is eliminated without weakening the artifact.
+
+## Evidence and verdict
+
+Ignored artifacts under `artifacts/local/p4-01b/compactness/` include `repaired-before.step`, `before-profile.json`, `after-profile.json`, `ordinary-before-profile.json`, `ordinary-after-profile.json`, `before/` and `after/` timed exports/imports, and independent native reports. `showcase/bolt-cli.step` is the final deliverable. Final build/test and product qualification are recorded in [the closeout](P4-01B-CLOSEOUT.md).
+
+**B2 verdict: Accepted.** Exact exporter sharing materially removes avoidable bloat while preserving full modeled thread, maker mark, topology, numeric precision and associations.
diff --git a/docs/release/TEXT-CODEX-FINISH-X2.md b/docs/release/TEXT-CODEX-FINISH-X2.md
index 869ef286..2651627a 100644
--- a/docs/release/TEXT-CODEX-FINISH-X2.md
+++ b/docs/release/TEXT-CODEX-FINISH-X2.md
@@ -1,5 +1,7 @@
# TEXT-CODEX-FINISH-X2
+The historical C# showcase entry point below is deprecated. [P4-01B1](P4-01B1-THREAD-SHOWCASE-REPAIR.md) authors the same CODEX engraving through standalone HexBolt fields and preserves the existing text geometry.
+
## Verdict: Accepted for the bounded CODEX maker mark
The normalized X outline is valid. The former rejection came from an intersection split only 0.00000004535 mm from the cubic endpoint. The split parameter differed by 5.60898e-7, but its geometric separation was below the arrangement's existing 1e-7 mm tolerance. The section arrangement now deduplicates adjacent split parameters by both parameter and geometric distance. It retains the source cubic and removes only the tolerance-equivalent split; no glyph contour or font normalizer changed.
diff --git a/docs/release/THREAD-EXTERNAL-X1.md b/docs/release/THREAD-EXTERNAL-X1.md
index 707b0f52..0573fed4 100644
--- a/docs/release/THREAD-EXTERNAL-X1.md
+++ b/docs/release/THREAD-EXTERNAL-X1.md
@@ -1,5 +1,7 @@
# THREAD-EXTERNAL-X1 — one Firmament Thread on an existing HexBolt
+Historical construction and measurements below are superseded by [P4-01B1](P4-01B1-THREAD-SHOWCASE-REPAIR.md): external threads now remove a bounded groove from major-diameter stock, and the canonical engraved showcase is `fixtures/Thread/hexbolt-showcase.firmament`.
+
**Verdict: Accepted for the bounded HexBolt case.** The existing smooth `StandardPart Bolt { Family: HexBolt }` gains one `Thread` declaration and produces one modeled, closed, consistently oriented BRep and production STEP. No generic Boolean, arbitrary sweep, mesh union, or cosmetic thread route was added.
## Authored delta
diff --git a/fixtures/Thread/hexbolt-showcase.firmament b/fixtures/Thread/hexbolt-showcase.firmament
new file mode 100644
index 00000000..e2badc28
--- /dev/null
+++ b/fixtures/Thread/hexbolt-showcase.firmament
@@ -0,0 +1,29 @@
+Model ThreadExternalHexBolt {
+ Units: mm
+ StandardPart Bolt {
+ Family: HexBolt
+ StableId: "McMaster91280A546"
+ NominalDiameter: 8mm
+ Length: 52mm
+ HeadAcrossFlats: 13mm
+ HeadHeight: 5.3mm
+ TopFlatDiameter: 12.35mm
+ TopChamferAngle: 25deg
+ TipChamferLength: 0.9375mm
+ TipDiameter: 6.125mm
+ ThreadLength: 47.5mm
+ ThreadDesignation: "M8 x 1.25"
+ PropertyClass: "8.8"
+ UnderHeadRadius: 0.2mm
+ MakerMark: "CODEX"
+ MakerMarkHeight: 2.5mm
+ MakerMarkDepth: 0.2mm
+ }
+ Thread MainThread {
+ Surface: face(Bolt.Shank)
+ MajorDiameter: 8mm
+ Pitch: 1.25mm
+ Length: 47.5mm
+ StartOffset: 1.5mm
+ }
+}
diff --git a/scripts/profile-step-entities.py b/scripts/profile-step-entities.py
new file mode 100644
index 00000000..08b1a638
--- /dev/null
+++ b/scripts/profile-step-entities.py
@@ -0,0 +1,93 @@
+"""Count STEP entities and serialized bytes; audit exact immutable definitions.
+
+This diagnostic reads canonical one-entity-per-line exporter output. It never
+rewrites STEP or proposes merging topology. Output defaults to artifacts/local.
+"""
+import argparse
+import collections
+import hashlib
+import json
+import pathlib
+import re
+
+parser = argparse.ArgumentParser()
+parser.add_argument("input", type=pathlib.Path)
+parser.add_argument("--output", type=pathlib.Path, default=pathlib.Path("artifacts/local/step-entity-profile.json"))
+args = parser.parse_args()
+raw = args.input.read_bytes()
+entities = {}
+histogram = collections.defaultdict(lambda: {"count": 0, "bytes": 0})
+for line in raw.splitlines(keepends=True):
+ text = line.decode("utf-8").strip()
+ match = re.fullmatch(r"#(\d+)=(.*);", text)
+ if not match:
+ continue
+ body = match[2]
+ names = re.findall(r"\b([A-Z][A-Z0-9_]*)\(", re.sub(r"'(?:(?:'')|[^'])*'", "", body))
+ kind = names[0] if not body.startswith("(") else "+".join(names)
+ entities[int(match[1])] = (kind, body, len(line))
+ histogram[kind]["count"] += 1
+ histogram[kind]["bytes"] += len(line)
+
+# STEP value geometry can share a definition; topological identity is separate.
+# Names and every argument participate. No tolerance-based equivalence is used.
+immutable = {"CARTESIAN_POINT", "DIRECTION", "VECTOR", "AXIS2_PLACEMENT_3D", "AXIS2_PLACEMENT_2D",
+ "LINE", "CIRCLE", "ELLIPSE", "PLANE", "CYLINDRICAL_SURFACE", "CONICAL_SURFACE",
+ "SPHERICAL_SURFACE", "TOROIDAL_SURFACE", "B_SPLINE_CURVE_WITH_KNOTS", "B_SPLINE_SURFACE_WITH_KNOTS"}
+token = re.compile(r"'(?:(?:'')|[^'])*'|#(\d+)")
+signatures = {}
+active = set()
+def signature(identity):
+ if identity in signatures:
+ return signatures[identity]
+ if identity in active:
+ return "cycle:" + str(identity)
+ active.add(identity)
+ body = entities[identity][1]
+ normalized = token.sub(lambda m: "@" + signature(int(m[1])) if m[1] and int(m[1]) in entities else m[0], body)
+ value = hashlib.sha256(normalized.encode("utf-8")).hexdigest()
+ active.remove(identity)
+ signatures[identity] = value
+ return value
+
+groups = collections.defaultdict(list)
+for identity, (kind, body, size) in entities.items():
+ if kind in immutable:
+ groups[kind, signature(identity)].append(identity)
+duplicates = collections.defaultdict(lambda: {"duplicateDefinitions": 0, "duplicateLineBytes": 0})
+for (kind, key), ids in groups.items():
+ duplicates[kind]["duplicateDefinitions"] += len(ids) - 1
+ duplicates[kind]["duplicateLineBytes"] += sum(entities[i][2] for i in ids[1:])
+
+required = ["ADVANCED_FACE", "EDGE_CURVE", "ORIENTED_EDGE", "EDGE_LOOP", "FACE_BOUND", "FACE_OUTER_BOUND",
+ "PCURVE", "SURFACE_CURVE", "CARTESIAN_POINT", "DIRECTION", "VECTOR", "AXIS2_PLACEMENT_3D",
+ "LINE", "CIRCLE", "B_SPLINE_CURVE_WITH_KNOTS", "B_SPLINE_SURFACE_WITH_KNOTS", "PRODUCT",
+ "SHAPE_REPRESENTATION", "REPRESENTATION_CONTEXT"]
+for kind in required:
+ histogram[kind]
+number = re.compile(r"(?<![#\w.])[-+]?(?:\d+\.\d*|\d*\.\d+|\d+)(?:[Ee][-+]?\d+)?")
+lengths = collections.Counter()
+numeric_bytes = 0
+for kind, body, size in entities.values():
+ without_strings = re.sub(r"'(?:(?:'')|[^'])*'", "", body)
+ for match in number.finditer(without_strings):
+ lengths[len(match[0])] += 1
+ numeric_bytes += len(match[0])
+report = {
+ "input": str(args.input.resolve()), "sha256": hashlib.sha256(raw).hexdigest().upper(),
+ "bytes": len(raw), "lines": len(raw.splitlines()), "entities": len(entities),
+ "entityBytes": sum(size for kind, body, size in entities.values()),
+ "histogram": dict(sorted(histogram.items(), key=lambda item: (-item[1]["bytes"], item[0]))),
+ "exactImmutableDuplication": dict(sorted(duplicates.items(), key=lambda item: (-item[1]["duplicateLineBytes"], item[0]))),
+ "numericLiteralBytes": numeric_bytes, "numericLiteralLengthHistogram": dict(sorted(lengths.items())),
+ "duplicateBytesAreEstimate": "Duplicate line bytes exclude reference renumbering effects; topology and pcurve associations are not counted as internable.",
+}
+# Identity-independent graph digest: immutable value geometry counts once, while every
+# topological/association/metadata occurrence retains its multiplicity. Includes names,
+# numeric strings and recursively resolved references, not just topology totals.
+semantic = collections.Counter((kind, signature(identity)) for identity, (kind, _, _) in entities.items())
+normalized = [(kind, key, 1 if kind in immutable else count) for (kind, key), count in sorted(semantic.items())]
+report["normalizedArtifactSha256"] = hashlib.sha256(json.dumps(normalized, separators=(",", ":")).encode()).hexdigest().upper()
+args.output.parent.mkdir(parents=True, exist_ok=True)
+args.output.write_text(json.dumps(report, indent=2), encoding="utf-8")
+print(json.dumps({key: report[key] for key in ("bytes", "lines", "entities", "histogram", "exactImmutableDuplication")}, indent=2))
diff --git a/scripts/qualify-step-freecad.py b/scripts/qualify-step-freecad.py
new file mode 100644
index 00000000..db8e1b58
--- /dev/null
+++ b/scripts/qualify-step-freecad.py
@@ -0,0 +1,54 @@
+"""Independent OCCT STEP qualification inside FreeCADCmd.
+
+Set AETHERIS_STEP_INPUT and AETHERIS_STEP_REPORT to explicit paths. Uses the
+normal native importer, without custom healing or geometry replacement.
+Generated reports belong in artifacts/local.
+"""
+import json
+import hashlib
+import os
+import time
+
+import Part
+import FreeCAD
+import Import
+
+started = time.perf_counter()
+document = FreeCAD.newDocument("StepQualification")
+errors = []
+shape = Part.Shape()
+try:
+ Import.insert(os.environ["AETHERIS_STEP_INPUT"], document.Name)
+ shapes = [obj.Shape for obj in document.Objects if hasattr(obj, "Shape") and not obj.Shape.isNull()]
+ shape = Part.makeCompound(shapes) if shapes else Part.Shape()
+except Exception as error:
+ errors.append(str(error))
+elapsed = time.perf_counter() - started
+if shape.isNull() and not errors:
+ errors.append("Native importer produced no non-null shape.")
+try:
+ shape.check()
+except Exception as error:
+ errors.append(str(error))
+box = None if shape.isNull() else shape.BoundBox
+report = {
+ "input": os.environ["AETHERIS_STEP_INPUT"],
+ "importSeconds": elapsed,
+ "valid": not errors and not shape.isNull() and shape.isValid(),
+ "closed": not shape.isNull() and shape.isClosed(),
+ "null": shape.isNull(),
+ "solids": 0 if shape.isNull() else len(shape.Solids),
+ "shells": 0 if shape.isNull() else len(shape.Shells),
+ "faces": 0 if shape.isNull() else len(shape.Faces),
+ "edges": 0 if shape.isNull() else len(shape.Edges),
+ "vertices": 0 if shape.isNull() else len(shape.Vertexes),
+ "volume": 0 if shape.isNull() else shape.Volume,
+ "bounds": None if box is None else [box.XMin, box.YMin, box.ZMin, box.XMax, box.YMax, box.ZMax],
+ "errors": errors,
+ "freecadVersion": FreeCAD.Version(),
+}
+with open(os.environ["AETHERIS_STEP_INPUT"], "rb") as stream:
+ report["stepSha256"] = hashlib.sha256(stream.read()).hexdigest().upper()
+with open(os.environ["AETHERIS_STEP_REPORT"], "w", encoding="utf-8") as stream:
+ json.dump(report, stream, indent=2)
+print(json.dumps(report))
diff --git a/testdata/step242/manifests/nist.v0.report.json b/testdata/step242/manifests/nist.v0.report.json
index 13640e74..f3f26492 100644
--- a/testdata/step242/manifests/nist.v0.report.json
+++ b/testdata/step242/manifests/nist.v0.report.json
@@ -17,7 +17,7 @@
"edges": 318,
"faces": 117
},
- "canonicalSha256": "a4ee6eb4f37a73e8f3251e35e28c16fd7dd18dd8d892df868d693160690d34ba"
+ "canonicalSha256": "f7c5e83b9bde6c9abc85209dae7228919ab3655e54c582c7d4abb664d75b7755"
},
{
"fileId": "testdata_step242_nist_CTC_nist_ctc_02_asme1_ap242-e2",
@@ -37,7 +37,7 @@
"edges": 1416,
"faces": 637
},
- "canonicalSha256": "d0cc97ff25ccfba781b0f6d56bede800658b252c45aba0a881eec1b4979db625"
+ "canonicalSha256": "e8998780c677c585769af01479455d77563f849d8a2159e63095a3a22e516f69"
},
{
"fileId": "testdata_step242_nist_CTC_nist_ctc_03_asme1_ap242-e2",
@@ -57,7 +57,7 @@
"edges": 354,
"faces": 120
},
- "canonicalSha256": "263c825cc2fc049070fa8fca5a9fd7f89de6ffc40e7cddd1203c779851807d85"
+ "canonicalSha256": "346db4eedf0b1ee9e69e5116278d723fd643328f92c2a980327ce8155d6eb163"
},
{
"fileId": "testdata_step242_nist_CTC_nist_ctc_04_asme1_ap242-e1",
@@ -77,7 +77,7 @@
"edges": 1110,
"faces": 484
},
- "canonicalSha256": "1aa507053dd8f45bc2509c9a82a7873e4b116b8d23497c0c0ca1ea4f89c6f7f2"
+ "canonicalSha256": "b5c7b340162e8354e9fb8b33ae273d2c0cf39fcba7563fd5d02bd70f30a2c28d"
},
{
"fileId": "testdata_step242_nist_CTC_nist_ctc_05_asme1_ap242-e1",
@@ -97,7 +97,7 @@
"edges": 331,
"faces": 156
},
- "canonicalSha256": "158362ba6bcc92e55009ea7a6f15c2fcd45d3dd2ab5b59f8c95bffc6928fce58"
+ "canonicalSha256": "5a6a946fbf13434377e7ca7965052597eab7213351515cefb26797aa93c8b019"
},
{
"fileId": "testdata_step242_nist_FTC_nist_ftc_06_asme1_ap242-e2",
@@ -117,7 +117,7 @@
"edges": 476,
"faces": 187
},
- "canonicalSha256": "6fdd1ae26f65af0f0d827949c07c4786585caeef2cac46fc25e957cd0aa530c8"
+ "canonicalSha256": "1333c9974092f0b87fa373fbfed0b769a1e9e03c237e4010eb26579b22b3d96b"
},
{
"fileId": "testdata_step242_nist_FTC_nist_ftc_07_asme1_ap242-e2",
@@ -137,7 +137,7 @@
"edges": 871,
"faces": 306
},
- "canonicalSha256": "647501aefa5266d177d4fb0f5dfb8dcc27ae4088fcb3535861373ffe1d5d86f8"
+ "canonicalSha256": "2cc896fdc31ed01567e5f785cafd8c412fa83fc3e9eee3c9be5e8ecc0283cab4"
},
{
"fileId": "testdata_step242_nist_FTC_nist_ftc_08_asme1_ap242-e1-tg",
@@ -177,7 +177,7 @@
"edges": 616,
"faces": 247
},
- "canonicalSha256": "b7713bfdf83da13dc647e8953a111e6810182aa17e9ba7453106229b1491f71a"
+ "canonicalSha256": "46164341247a76f9e65ba946f83fa16a930c9e880e07edd42d75e852e4c54889"
},
{
"fileId": "testdata_step242_nist_FTC_nist_ftc_09_asme1_ap242-e1",
@@ -197,7 +197,7 @@
"edges": 458,
"faces": 159
},
- "canonicalSha256": "cda7b5c424f4e6273620770d197c21cb0984d8172ff979a43d2d5cf1fa8facb3"
+ "canonicalSha256": "eab5333dab3ae40f636c110d8f1fa23983c51c890f104c936f8e09a7a1bf2fbe"
},
{
"fileId": "testdata_step242_nist_FTC_nist_ftc_10_asme1_ap242-e2",
@@ -217,7 +217,7 @@
"edges": 813,
"faces": 268
},
- "canonicalSha256": "94c4d8ecfffdd8c04a31e25cc0ccd0e9b5e4e4f4a218603c95af7d5ac849f6e5"
+ "canonicalSha256": "8eeb191ff5607820ed5f9a2116f3ade55732f984f265191da17e191a3e748236"
},
{
"fileId": "testdata_step242_nist_FTC_nist_ftc_11_asme1_ap242-e2",
@@ -237,7 +237,7 @@
"edges": 104,
"faces": 42
},
- "canonicalSha256": "687e423472a6e686883b199e2a2d1f630f360d0b6199cc09c438cd3c07f98607"
+ "canonicalSha256": "6f23fa5f4186de4e592e3779ef27da2c29f13839e6dae452c5d5b41e6f272c6d"
},
{
"fileId": "testdata_step242_nist_STC_nist_stc_06_asme1_ap242-e3",
@@ -257,7 +257,7 @@
"edges": 310,
"faces": 144
},
- "canonicalSha256": "dac42cc7310c9fa2635e77c48b70d83b82cd30cfd3a209648a86539c1b49a665"
+ "canonicalSha256": "6af39a3e59d78e5b0a80d53b70263243f3ccac8c86c52b5619848e9c544f4b73"
},
{
"fileId": "testdata_step242_nist_STC_nist_stc_07_asme1_ap242-e3",
@@ -277,7 +277,7 @@
"edges": 871,
"faces": 306
},
- "canonicalSha256": "1d504dba84b2ba2f7ecf5e67c058024447e194a4ddfecb9f0ad96814945a6458"
+ "canonicalSha256": "811d2ac7736a815715ee5aa4f7b955b56be156e3cb34999f203ce6eac325b94a"
},
{
"fileId": "testdata_step242_nist_STC_nist_stc_08_asme1_ap242-e3",
@@ -297,7 +297,7 @@
"edges": 709,
"faces": 271
},
- "canonicalSha256": "c243c92651a728436cf1f999622c8621f218abc08860c2dd23395ebeef6f43a8"
+ "canonicalSha256": "526d3c15f84f113cf132d8a0e0a7c8b23299e6da145a2389303ebb8dd2d431cb"
},
{
"fileId": "testdata_step242_nist_STC_nist_stc_09_asme1_ap242-e3",
@@ -317,7 +317,7 @@
"edges": 392,
"faces": 125
},
- "canonicalSha256": "b6a0ecae8067ca806465a5774f8baf3281deec32506d663d28d70c10a9d0db84"
+ "canonicalSha256": "91788d0964d571b573fae9551ab91486b7231a0ceb0d8cdbb4b0a73e9ac423d4"
},
{
"fileId": "testdata_step242_nist_STC_nist_stc_10_asme1_ap242-e2",
@@ -337,6 +337,6 @@
"edges": 551,
"faces": 256
},
- "canonicalSha256": "79e1aa1d8d93c2c6b03c8014950d36c3db508515823488208c7551bf8133a1dd"
+ "canonicalSha256": "bda02784fb839f47fada74a6df536fe66f118f5242e0069cdf2cda50b53680ca"
}
]