Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add revision-aware document measurement API

Yuechen Li13d5767f2436
diff --git a/Aetheris.Geometry.Tests/BrepMeasurementQueryTests.cs b/Aetheris.Geometry.Tests/BrepMeasurementQueryTests.cs
new file mode 100644
index 00000000..e85bc04b
--- /dev/null
+++ b/Aetheris.Geometry.Tests/BrepMeasurementQueryTests.cs
@@ -0,0 +1,118 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Geometry.Surfaces;
+using Aetheris.Kernel.Core.Brep.Boolean;
+using Xunit;
+
+namespace Aetheris.Geometry.Tests;
+
+public sealed class BrepMeasurementQueryTests
+{
+ private static MeasurementPick Pick(string id, double x, double y, double z, double dx, double dy, double dz)
+ => new(id, null, [x,y,z], [dx,dy,dz]);
+
+ [Fact]
+ public void Point_picks_preserve_world_deltas_and_do_not_claim_face_clearance()
+ {
+ MeasurementTarget[] targets = [new("box", BrepPrimitives.CreateBox(10,20,6).Value, Transform3D.Identity)];
+ var result = BrepMeasurementQuery.Measure(targets, new("points", Pick("box",1,2,30,0,0,-1), Pick("box",4,6,-30,0,0,1)));
+ Assert.Equal(double.Sqrt(61), result.DistanceMm!.Value, 10);
+ Assert.Equal(new double[] {3,4,-6}, result.DeltaMm!);
+ Assert.Equal("Analytic BRep", result.Quality);
+ Assert.Contains("not minimum clearance", result.Explanation);
+ }
+
+ [Fact]
+ public void Parallel_support_planes_remove_tangential_pick_offset()
+ {
+ MeasurementTarget[] targets = [new("box", BrepPrimitives.CreateBox(10,20,6).Value, Transform3D.Identity)];
+ var result = BrepMeasurementQuery.Measure(targets, new("planes", Pick("box",1,2,30,0,0,-1), Pick("box",4,6,-30,0,0,1)));
+ Assert.Equal(6, result.DistanceMm!.Value, 10);
+ Assert.Equal(new double[] {0,0,-6}, result.DeltaMm!);
+ Assert.Equal(0, result.AngleDegrees);
+ var angled = BrepMeasurementQuery.Measure(targets, new("planes", Pick("box",1,2,30,0,0,-1), Pick("box",30,2,0,-1,0,0)));
+ Assert.Null(angled.DistanceMm); Assert.Equal(90, angled.AngleDegrees);
+ }
+
+ [Fact]
+ public void Repeated_rotated_occurrences_keep_their_own_world_geometry()
+ {
+ var box = BrepPrimitives.CreateBox(10,20,6).Value;
+ var moved = Transform3D.CreateRotationZ(double.Pi/2) * Transform3D.CreateTranslation(new(40,5,0));
+ MeasurementTarget[] targets = [new("a", box, Transform3D.Identity), new("b", box, moved)];
+ var result = BrepMeasurementQuery.Measure(targets, new("points", Pick("a",0,0,30,0,0,-1), Pick("b",40,5,30,0,0,-1)));
+ Assert.Equal(double.Sqrt(1625), result.DistanceMm!.Value, 10);
+ Assert.Equal("a", result.First.OccurrenceId); Assert.Equal("b", result.Second!.OccurrenceId);
+ Assert.Equal(new double[] {40,5,0}, result.DeltaMm!);
+ }
+
+ [Fact]
+ public void Cylinder_axis_spacing_and_diameters_are_not_surface_gap()
+ {
+ var cylinder = BrepPrimitives.CreateCylinder(3,10).Value;
+ MeasurementTarget[] targets = [new("a", cylinder, Transform3D.Identity), new("b", cylinder, Transform3D.CreateTranslation(new(20,0,0)))];
+ var result = BrepMeasurementQuery.Measure(targets, new("axes", Pick("a",0,-20,0,0,1,0), Pick("b",20,-20,0,0,1,0)));
+ Assert.Equal(20, result.DistanceMm!.Value, 10); Assert.Equal(6, result.First.DiameterMm);
+ Assert.Equal(0, result.AngleDegrees); Assert.Contains("infinite", result.Explanation);
+ }
+
+ [Fact]
+ public void Skew_axes_report_the_common_perpendicular_and_acute_angle()
+ {
+ var cylinder = BrepPrimitives.CreateCylinder(3,10).Value;
+ MeasurementTarget[] targets = [new("a", cylinder, Transform3D.Identity), new("b", cylinder,
+ Transform3D.CreateRotationX(double.Pi/2) * Transform3D.CreateTranslation(new(20,0,0)))];
+ var result = BrepMeasurementQuery.Measure(targets, new("axes", Pick("a",0,-20,0,0,1,0), Pick("b",20,0,20,0,0,-1)));
+ Assert.Equal(20, result.DistanceMm!.Value, 10); Assert.Equal(90, result.AngleDegrees!.Value, 10);
+ Assert.InRange(double.Abs(result.DeltaMm![1]), 0, 1e-10); Assert.InRange(double.Abs(result.DeltaMm[2]), 0, 1e-10);
+ }
+
+ [Fact]
+ public void Unsupported_foreground_surface_cannot_be_skipped_for_an_exact_back_face()
+ {
+ var box = BrepPrimitives.CreateBox(10,20,6).Value;
+ var top = box.Topology.Faces.Single(f => box.GetFaceSurface(f.Id).Plane is { } p && p.Origin.Z == 3);
+ var replacement = new BSplineSurfaceWithKnots(1,1,
+ [[new(-5,-10,3),new(-5,10,3)],[new(5,-10,3),new(5,10,3)]], "PLANE_SURF", false,false,false,[2,2],[2,2],[0,1],[0,1],"UNSPECIFIED");
+ var geometry = new BrepGeometryStore();
+ var replacedId = box.Bindings.GetFaceBinding(top.Id).SurfaceGeometryId;
+ foreach (var curve in box.Geometry.Curves) geometry.AddCurve(curve.Key, curve.Value);
+ foreach (var surface in box.Geometry.Surfaces) geometry.AddSurface(surface.Key, surface.Key == replacedId ? SurfaceGeometry.FromBSplineSurfaceWithKnots(replacement) : surface.Value);
+ var unsupported = new BrepBody(box.Topology, geometry, box.Bindings);
+ MeasurementTarget[] targets = [new("box", unsupported, Transform3D.Identity)];
+ var request = new MeasurementRequest("points", Pick("box",0,0,30,0,0,-1));
+ Assert.Equal("measurement-surface-unsupported", Assert.Throws<MeasurementException>(() => BrepMeasurementQuery.Measure(targets, request)).Code);
+ var approximate = BrepMeasurementQuery.Measure(targets, request with { AllowApproximate = true });
+ Assert.Equal("Approximate display", approximate.Quality); Assert.Equal(3, approximate.First.Point[2], 10);
+ Assert.Equal(top.Id.Value, approximate.First.FaceId);
+ }
+
+ [Fact]
+ public void Through_hole_void_does_not_become_a_surface_pick()
+ {
+ var box = BrepPrimitives.CreateBox(40,30,12).Value;
+ var hole = BrepPrimitives.CreateCylinder(4,20).Value;
+ var subtracted = BrepBoolean.Subtract(box, hole);
+ Assert.True(subtracted.IsSuccess);
+ MeasurementTarget[] targets = [new("plate", subtracted.Value, Transform3D.Identity)];
+ Assert.Equal("measurement-pick-missed", Assert.Throws<MeasurementException>(() => BrepMeasurementQuery.Measure(targets,
+ new("points", Pick("plate",0,0,30,0,0,-1)))).Code);
+ var walls = BrepMeasurementQuery.Measure(targets, new("axes", Pick("plate",0,0,0,1,0,0)));
+ Assert.Equal(8, walls.First.DiameterMm);
+ }
+
+ [Fact]
+ public void Missed_stale_and_wrong_kind_references_are_diagnostics_not_zero()
+ {
+ MeasurementTarget[] targets = [new("box", BrepPrimitives.CreateBox(10,20,6).Value, Transform3D.Identity)];
+ Assert.Equal("measurement-pick-missed", Assert.Throws<MeasurementException>(() => BrepMeasurementQuery.Measure(targets,
+ new("points", Pick("old",0,0,30,0,0,-1)))).Code);
+ Assert.Equal("measurement-axis-required", Assert.Throws<MeasurementException>(() => BrepMeasurementQuery.Measure(targets,
+ new("axes", Pick("box",0,0,30,0,0,-1)))).Code);
+ Assert.Equal("measurement-ray-invalid", Assert.Throws<MeasurementException>(() => BrepMeasurementQuery.Measure(targets,
+ new("points", Pick("box",0,0,30,0,0,0)))).Code);
+ Assert.Equal("measurement-pick-missed", Assert.Throws<MeasurementException>(() => BrepMeasurementQuery.Measure(targets,
+ new("points", Pick("box",0,0,30,0,0,-1) with { FaceId = int.MaxValue }))).Code);
+ }
+}
diff --git a/Aetheris.Geometry/BrepMeasurementQuery.cs b/Aetheris.Geometry/BrepMeasurementQuery.cs
new file mode 100644
index 00000000..90ecd69c
--- /dev/null
+++ b/Aetheris.Geometry/BrepMeasurementQuery.cs
@@ -0,0 +1,167 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Picking;
+using Aetheris.Kernel.Core.Brep.Queries;
+using Aetheris.Kernel.Core.Brep.Tessellation;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Topology;
+
+namespace Aetheris.Geometry;
+
+public sealed record MeasurementPick(string? OccurrenceId, int? FaceId, double[] RayOrigin, double[] RayDirection);
+public sealed record MeasurementRequest(string Mode, MeasurementPick First, MeasurementPick? Second = null, bool AllowApproximate = false);
+public sealed class MeasurementTarget(string occurrenceId, BrepBody body, Transform3D transform)
+{
+ public string OccurrenceId { get; } = occurrenceId;
+ public BrepBody Body { get; } = body;
+ public Transform3D Transform { get; } = transform;
+ private readonly Lazy<DisplayTessellationResult> _display = new(() => PrepareDisplay(body));
+ internal DisplayTessellationResult Display => _display.Value;
+
+ private static DisplayTessellationResult PrepareDisplay(BrepBody body)
+ {
+ var options = DisplayTessellationOptions.ForViewport(body);
+ if (!OperatingSystem.IsBrowser()) return BrepDisplayTessellator.TessellateBoundedPartial(body, options);
+ // Same policy as WebMeshBuilder: browser WASM cannot block on a monitor. Its Worker owns
+ // responsiveness. Do not enter the native Task.Run/WaitAsync budget wrapper here.
+ var result = BrepDisplayTessellator.Tessellate(body, options);
+ if (!result.IsSuccess) throw new MeasurementException("measurement-display-unavailable",
+ "This BRep could not produce a synchronous measurement pick proxy: " + string.Join("; ", result.Diagnostics.Select(d => d.Message)));
+ return result.Value;
+ }
+}
+public sealed record MeasurementReference(string OccurrenceId, int FaceId, string SurfaceKind, double[] Point,
+ string Quality, double? DiameterMm = null);
+public sealed record MeasurementResult(string Mode, MeasurementReference First, MeasurementReference? Second,
+ double? DistanceMm, double[]? DeltaMm, double[]? WitnessA, double[]? WitnessB, double? AngleDegrees,
+ string Quality, string Explanation);
+public sealed class MeasurementException(string code, string message) : Exception(message)
+{
+ public string Code { get; } = code;
+}
+
+/// <summary>
+/// Read-only BRep measurement authority. Support-plane and infinite-axis distances are deliberately
+/// distinct from finite material clearance. Surface points use the existing analytic trim policy;
+/// a display approximation is available only by explicit request and remains labeled approximate.
+/// Callers own revision checks and supply geometry from the displayed compilation, never a recompile.
+/// </summary>
+public static class BrepMeasurementQuery
+{
+ private sealed record Reference(MeasurementReference Display, SurfaceGeometry Surface, Transform3D Transform, Point3D Point);
+
+ public static MeasurementResult Measure(IReadOnlyList<MeasurementTarget> targets, MeasurementRequest request)
+ {
+ if (request?.First is null) throw Error("measurement-request-invalid", "A first measurement pick is required.");
+ if (request.Mode is not ("points" or "planes" or "axes"))
+ throw Error("measurement-mode-unsupported", "Choose Surface points, Support planes, or Axes.");
+ var a = Resolve(targets, request.First, request.Mode == "points" && request.AllowApproximate);
+ var b = request.Second is null ? null : Resolve(targets, request.Second, request.Mode == "points" && request.AllowApproximate);
+ var quality = a.Display.Quality == "Approximate display" || b?.Display.Quality == "Approximate display"
+ ? "Approximate display" : "Analytic BRep";
+ Point3D p = a.Point, q = b?.Point ?? p;
+ double? angle = null;
+ string explanation;
+ switch (request.Mode)
+ {
+ case "planes":
+ var n = PlaneNormal(a);
+ explanation = "Spacing of infinite support planes; not minimum clearance between trimmed faces.";
+ if (b is not null)
+ {
+ var m = PlaneNormal(b);
+ angle = Angle(n, m);
+ if (n.Cross(m).Length > 1e-10)
+ return new(request.Mode, a.Display, b.Display, null, null, null, null, angle, quality,
+ "The support planes are not parallel. Their acute angle is shown; no parallel spacing exists.");
+ q = p + n * ((b.Point - p).Dot(n));
+ }
+ break;
+ case "axes":
+ var (o, u) = Axis(a);
+ explanation = "Shortest spacing of infinite analytic axes; not wall thickness or material clearance.";
+ p = o;
+ if (b is not null)
+ {
+ var (v0, v) = Axis(b);
+ angle = Angle(u, v);
+ var w = o - v0;
+ var dot = u.Dot(v);
+ // Cross-product magnitude avoids cancellation in 1-dot² near parallel axes.
+ var denominator = u.Cross(v).LengthSquared;
+ if (denominator <= 1e-20) { p = o; q = v0 + v * w.Dot(v); }
+ else
+ {
+ var s = (dot * v.Dot(w) - u.Dot(w)) / denominator;
+ var t = (v.Dot(w) - dot * u.Dot(w)) / denominator;
+ p = o + u * s; q = v0 + v * t;
+ }
+ }
+ break;
+ default:
+ explanation = quality == "Approximate display"
+ ? "Distance between picked points. Includes a display-mesh point; unsuitable for tolerance verification."
+ : "Distance between analytically resolved surface picks; not minimum clearance between faces.";
+ break;
+ }
+ if (b is null) return new(request.Mode, a.Display, null, null, null, Coordinates(p), null, null, quality, explanation);
+ var delta = q - p;
+ if (!double.IsFinite(delta.Length)) throw Error("measurement-numerical-failure", "The measured coordinates exceeded the finite query range.");
+ return new(request.Mode, a.Display, b.Display, delta.Length, [delta.X, delta.Y, delta.Z], Coordinates(p), Coordinates(q), angle, quality, explanation);
+ }
+
+ private static Reference Resolve(IReadOnlyList<MeasurementTarget> targets, MeasurementPick pick, bool approximate)
+ {
+ if (pick.RayOrigin is not { Length: 3 } || pick.RayDirection is not { Length: 3 }
+ || pick.RayOrigin.Concat(pick.RayDirection).Any(v => !double.IsFinite(v)))
+ throw Error("measurement-ray-invalid", "A pick requires a finite origin and a nonzero finite direction.");
+ var scale = pick.RayDirection.Max(double.Abs);
+ if (scale == 0 || !Direction3D.TryCreate(new(pick.RayDirection[0] / scale, pick.RayDirection[1] / scale, pick.RayDirection[2] / scale), out var direction))
+ throw Error("measurement-ray-invalid", "A pick requires a finite origin and a nonzero finite direction.");
+ var ray = new Ray3D(new(pick.RayOrigin[0], pick.RayOrigin[1], pick.RayOrigin[2]), direction);
+ var candidates = new List<(Reference Reference, double Distance)>();
+ foreach (var target in targets.Where(t => pick.OccurrenceId is null || t.OccurrenceId == pick.OccurrenceId))
+ {
+ if (!target.Transform.IsRigid()) throw Error("measurement-transform-unsupported", "Measurement requires a rigid occurrence placement.");
+ var inverse = target.Transform.Inverse();
+ var local = new Ray3D(inverse.Apply(ray.Origin), inverse.Apply(ray.Direction));
+ if (pick.FaceId is null && target.Body.Topology.Faces.Any(face => !target.Display.FacePatches.Any(patch => patch.FaceId == face.Id)))
+ throw Error("measurement-face-reference-required", "This body has undisplayed faces. Select an explicit visible face so the query cannot see through missing geometry.");
+ // The display picker locates the frontmost trim, including surfaces not admitted by the
+ // analytic picker. Never see through an unsupported foreground face to a supported back face.
+ // Match the viewport's double-sided picking, including inward-facing hole walls.
+ var hits = BrepPicker.Pick(target.Body, target.Display, local, PickQueryOptions.Default with { IncludeBackfaces = true });
+ if (!hits.IsSuccess) continue;
+ var faceHit = hits.Value.Where(h => h.FaceId is not null && (pick.FaceId is null || h.FaceId.Value.Value == pick.FaceId))
+ .OrderBy(h => h.T).FirstOrDefault();
+ if (faceHit?.FaceId is not { } id) continue;
+ if (!target.Body.TryGetFaceSurfaceGeometry(id, out var surface) || surface is null) continue;
+ var exact = AnalyticDisplayQuery.TryIntersectFace(target.Body, id, local, out var hit);
+ var point = target.Transform.Apply(exact ? hit.Position : faceHit.Point);
+ var diameter = surface.Cylinder is { } cylinder ? 2 * cylinder.Radius : (double?)null;
+ var reference = new MeasurementReference(target.OccurrenceId, id.Value, surface.Kind.ToString(), Coordinates(point),
+ exact ? "Analytic BRep" : "Approximate display", diameter);
+ candidates.Add((new(reference, surface, target.Transform, point), (point - ray.Origin).Dot(ray.Direction.ToVector())));
+ }
+ var chosen = candidates.OrderBy(c => c.Distance).ThenBy(c => c.Reference.Display.OccurrenceId, StringComparer.Ordinal).FirstOrDefault().Reference;
+ if (chosen is null) throw Error("measurement-pick-missed", "No current BRep face was hit. Pick a visible face; mesh-only geometry cannot be measured analytically.");
+ if (chosen.Display.Quality != "Analytic BRep" && !approximate)
+ throw Error("measurement-surface-unsupported", "This trimmed surface has no admitted analytic pick. Choose another face or explicitly enable approximate display points.");
+ return chosen;
+ }
+
+ private static Vector3D PlaneNormal(Reference reference) => reference.Surface.Plane is { } plane
+ ? reference.Transform.Apply(plane.Normal).ToVector()
+ : throw Error("measurement-plane-required", $"Select planar faces for support-plane spacing; this face is {reference.Display.SurfaceKind}.");
+ private static (Point3D, Vector3D) Axis(Reference reference)
+ {
+ var surface = reference.Surface;
+ if (surface.Cylinder is { } cylinder) return (reference.Transform.Apply(cylinder.Origin), reference.Transform.Apply(cylinder.Axis).ToVector());
+ if (surface.Cone is { } cone) return (reference.Transform.Apply(cone.Apex), reference.Transform.Apply(cone.Axis).ToVector());
+ if (surface.Torus is { } torus) return (reference.Transform.Apply(torus.Center), reference.Transform.Apply(torus.Axis).ToVector());
+ throw Error("measurement-axis-required", $"Select cylindrical, conical or toroidal faces for axis spacing; this face is {reference.Display.SurfaceKind}.");
+ }
+ private static double Angle(Vector3D a, Vector3D b) => double.Acos(double.Clamp(double.Abs(a.Dot(b)), 0, 1)) * 180 / double.Pi;
+ private static double[] Coordinates(Point3D p) => [p.X, p.Y, p.Z];
+ private static MeasurementException Error(string code, string message) => new(code, message);
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentAssertionsTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentAssertionsTests.cs
index 58404dac..9fd02e04 100644
--- a/Aetheris.Kernel.Firmament.Tests/FirmamentAssertionsTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentAssertionsTests.cs
@@ -7,6 +7,20 @@ public sealed class FirmamentAssertionsTests
{
private static string Source(string name) => File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Regression/Assertions/" + name + ".firmament"));
+ [Fact]
+ public void HistoricalFilletGeometryBuildsButAnUnprovableVolumeAssertionStillRejects()
+ {
+ var path = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Regression/CanonicalGeometry/profile-fillet-convex-two-segment-top.firmament");
+ var source = File.ReadAllText(path);
+ var accepted = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(accepted.IsSuccess, string.Join("; ", accepted.Diagnostics.Select(d => d.Message)));
+ source = source.Insert(source.LastIndexOf('}'), "Assert Volume Body { expected: 1mm^3 tolerance: 0mm^3 }\n");
+ var rejected = FirmamentBuildAndExport.CompileSource(source);
+ Assert.False(rejected.IsSuccess);
+ Assert.Contains(rejected.Diagnostics, d => d.Message.StartsWith("firmament-v2-assert-volume-measurement-unavailable:", StringComparison.Ordinal));
+ Assert.Equal(accepted.Value.StepText, FirmamentBuildAndExport.CompileForMeasurement(source).Value.StepText);
+ }
+
[Fact]
public void ExactVolumeBoundsAndTopologyGateTheRealCompilationWithoutChangingGeometry()
{
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentCorpusHarness.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentCorpusHarness.cs
index 0ed5a562..65bdd6b4 100644
--- a/Aetheris.Kernel.Firmament.Tests/FirmamentCorpusHarness.cs
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentCorpusHarness.cs
@@ -69,22 +69,18 @@ internal static class FirmamentCorpusHarness
return compiler.Compile(request);
}
- // These preserved historical specimens asserted a curved-fillet volume
- // while only a display mesh was measured. Qualify their geometry separately
- // and require ordinary compilation to disclose the missing volume authority.
- public static FirmamentStepExportResult InspectUnverifiedVolumeSpecimen(string fullPath)
+ // Retain geometry coverage while asserting provable topology, not a mesh-derived volume.
+ public static FirmamentStepExportResult InspectFilletSpecimen(string fullPath)
{
var source = NormalizeLf(File.ReadAllText(fullPath));
- var rejected = FirmamentBuildAndExport.CompileSource(source, Path.GetDirectoryName(fullPath));
- Assert.False(rejected.IsSuccess);
- Assert.Contains(rejected.Diagnostics, d => d.Message.StartsWith("firmament-v2-assert-volume-measurement-unavailable:", StringComparison.Ordinal));
+ var accepted = FirmamentBuildAndExport.CompileSource(source, Path.GetDirectoryName(fullPath));
+ Assert.True(accepted.IsSuccess, string.Join("; ", accepted.Diagnostics.Select(d => d.Message)));
var inspected = FirmamentBuildAndExport.CompileForMeasurement(source, Path.GetDirectoryName(fullPath));
Assert.True(inspected.IsSuccess, string.Join("; ", inspected.Diagnostics.Select(d => d.Message)));
- var control = FirmamentBuildAndExport.CompileSource(FirmamentV2.FirmamentAssertionSyntax.Mask(source), Path.GetDirectoryName(fullPath));
- Assert.True(control.IsSuccess, string.Join("; ", control.Diagnostics.Select(d => d.Message)));
- Assert.Equal(control.Value.StepText, inspected.Value.StepText);
- return inspected.Value;
+ Assert.Equal(accepted.Value.StepText, inspected.Value.StepText);
+ return accepted.Value;
}
+
}
internal sealed class FirmamentCorpusManifest
diff --git a/Aetheris.Kernel.Firmament.Tests/Integration/ProfileBoundaryChamferFixtureTests.cs b/Aetheris.Kernel.Firmament.Tests/Integration/ProfileBoundaryChamferFixtureTests.cs
index d055bbb0..a809a37f 100644
--- a/Aetheris.Kernel.Firmament.Tests/Integration/ProfileBoundaryChamferFixtureTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/Integration/ProfileBoundaryChamferFixtureTests.cs
@@ -107,8 +107,8 @@ public sealed class ProfileBoundaryChamferFixtureTests
public void ConvexTwoSegmentFilletFixture_ExportsDeterministicTwoCylindersAndSphere(string fixtureName)
{
var source = FirmamentCorpusHarness.ResolveFixtureFullPath($"fixtures/Regression/CanonicalGeometry/{fixtureName}");
- var first = FirmamentCorpusHarness.InspectUnverifiedVolumeSpecimen(source);
- var second = FirmamentCorpusHarness.InspectUnverifiedVolumeSpecimen(source);
+ var first = FirmamentCorpusHarness.InspectFilletSpecimen(source);
+ var second = FirmamentCorpusHarness.InspectFilletSpecimen(source);
Assert.Equal(first.StepText, second.StepText);
var imported = Step242Importer.ImportBody(first.StepText);
Assert.True(imported.IsSuccess, string.Join(Environment.NewLine, imported.Diagnostics.Select(item => item.Message)));
@@ -138,8 +138,8 @@ public sealed class ProfileBoundaryChamferFixtureTests
public void ReflexTwoSegmentFilletFixture_ExportsDeterministicTwoCylindersAndHornTorus(string fixtureName)
{
var source = FirmamentCorpusHarness.ResolveFixtureFullPath($"fixtures/Regression/CanonicalGeometry/{fixtureName}");
- var first = FirmamentCorpusHarness.InspectUnverifiedVolumeSpecimen(source);
- var second = FirmamentCorpusHarness.InspectUnverifiedVolumeSpecimen(source);
+ var first = FirmamentCorpusHarness.InspectFilletSpecimen(source);
+ var second = FirmamentCorpusHarness.InspectFilletSpecimen(source);
Assert.Equal(first.StepText, second.StepText);
var imported = Step242Importer.ImportBody(first.StepText);
Assert.True(imported.IsSuccess, string.Join(Environment.NewLine, imported.Diagnostics.Select(item => item.Message)));
diff --git a/Aetheris.Kernel.Firmament.Tests/Integration/ProfileEdgeFinishMixedShellPlanTests.cs b/Aetheris.Kernel.Firmament.Tests/Integration/ProfileEdgeFinishMixedShellPlanTests.cs
index 9cba3f33..6df57286 100644
--- a/Aetheris.Kernel.Firmament.Tests/Integration/ProfileEdgeFinishMixedShellPlanTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/Integration/ProfileEdgeFinishMixedShellPlanTests.cs
@@ -154,8 +154,8 @@ public sealed class ProfileEdgeFinishMixedShellPlanTests
public void SevenStationFillet_ExportsDeterministicallyWithExpectedSphereTorusDelta(string fixture, int spheres, int tori)
{
var source = FirmamentCorpusHarness.ResolveFixtureFullPath($"fixtures/Regression/CanonicalGeometry/{fixture}");
- var first = FirmamentCorpusHarness.InspectUnverifiedVolumeSpecimen(source);
- var second = FirmamentCorpusHarness.InspectUnverifiedVolumeSpecimen(source);
+ var first = FirmamentCorpusHarness.InspectFilletSpecimen(source);
+ var second = FirmamentCorpusHarness.InspectFilletSpecimen(source);
Assert.Equal(first.StepText, second.StepText);
var imported = Step242Importer.ImportBody(first.StepText);
Assert.True(imported.IsSuccess, string.Join(Environment.NewLine, imported.Diagnostics.Select(diagnostic => diagnostic.Message)));
@@ -173,7 +173,7 @@ public sealed class ProfileEdgeFinishMixedShellPlanTests
public void SevenStationFillet_ReimportedMassIsNonAuthoritativeSanityEvidence(string fixture)
{
var source = FirmamentCorpusHarness.ResolveFixtureFullPath($"fixtures/Regression/CanonicalGeometry/{fixture}");
- var built = FirmamentCorpusHarness.InspectUnverifiedVolumeSpecimen(source);
+ var built = FirmamentCorpusHarness.InspectFilletSpecimen(source);
var imported = Step242Importer.ImportBody(built.StepText);
Assert.True(imported.IsSuccess, string.Join(Environment.NewLine, imported.Diagnostics.Select(diagnostic => diagnostic.Message)));
diff --git a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
index 280ada3f..659a1b98 100644
--- a/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
+++ b/Aetheris.Server.Tests/KernelApiIntegrationTests.cs
@@ -57,6 +57,12 @@ public sealed class KernelApiIntegrationTests : IClassFixture<WebApplicationFact
Assert.Equal("Qualified", imported.Data.ImportStatus);
Assert.NotNull(scene.Definitions[0].ImportQualification);
Assert.Equal(6, scene.Definitions[0].ImportQualification!.DisplayedFaces);
+ var measurement = new DocumentMeasurementRequest(imported.Data.Revision, new("points",
+ new("one", null, [0,0,30], [0,0,-1]), new("two", null, [25,0,30], [0,0,-1])));
+ var measured = await _client.PostAsJsonAsync($"/api/v1/documents/{document.Data.DocumentId}/measure", measurement);
+ measured.EnsureSuccessStatusCode();
+ var result = await measured.Content.ReadFromJsonAsync<JsonElement>();
+ Assert.Equal(25, result.GetProperty("data").GetProperty("measurement").GetProperty("distanceMm").GetDouble());
}
private readonly HttpClient _client;
diff --git a/Aetheris.Server.Tests/MeasurementTests.cs b/Aetheris.Server.Tests/MeasurementTests.cs
new file mode 100644
index 00000000..84a17a7d
--- /dev/null
+++ b/Aetheris.Server.Tests/MeasurementTests.cs
@@ -0,0 +1,48 @@
+using System.Net;
+using System.Net.Http.Json;
+using System.Text.Json;
+using Aetheris.Geometry;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Server.Contracts;
+using Aetheris.Server.Documents;
+using Microsoft.AspNetCore.Mvc.Testing;
+
+namespace Aetheris.Server.Tests;
+
+public sealed class MeasurementTests : IClassFixture<WebApplicationFactory<Program>>
+{
+ private readonly HttpClient _client;
+ public MeasurementTests(WebApplicationFactory<Program> factory) => _client = factory.CreateClient();
+
+ [Fact]
+ public void Document_revision_invalidates_measurements_after_placement_edit()
+ {
+ var document = new DocumentSession(Guid.NewGuid());
+ var occurrence = document.AddBody(BrepPrimitives.CreateBox(10,20,6).Value);
+ var revision = document.Revision;
+ var request = new MeasurementRequest("planes", new(occurrence.OccurrenceId.ToString(),null,[0,0,30],[0,0,-1]),
+ new(occurrence.OccurrenceId.ToString(),null,[0,0,-30],[0,0,1]));
+ Assert.Equal(6, document.Measure(revision, request).DistanceMm);
+ Assert.True(document.ApplyBodyTranslation(occurrence.OccurrenceId, new(1,0,0), out _));
+ Assert.Equal("measurement-stale-revision", Assert.Throws<MeasurementException>(() => document.Measure(revision, request)).Code);
+ }
+
+ [Fact]
+ public async Task Http_measurement_uses_current_BRep_and_rejects_stale_revision()
+ {
+ var created = await (await _client.PostAsJsonAsync("/api/v1/documents", new { name="measurement" })).Content.ReadFromJsonAsync<ApiResponseDto<DocumentCreateResponseDto>>();
+ var url = $"/api/v1/documents/{created!.Data!.DocumentId}";
+ var body = await (await _client.PostAsJsonAsync(url+"/bodies/primitives/box", new {width=10,height=20,depth=6})).Content.ReadFromJsonAsync<ApiResponseDto<BodyCreatedResponseDto>>();
+ var summary = await _client.GetFromJsonAsync<ApiResponseDto<DocumentSummaryResponseDto>>(url);
+ var request = new DocumentMeasurementRequest(summary!.Data!.Revision, new("planes", new(body!.Data!.BodyId.ToString(),null,[0,0,30],[0,0,-1]), new(body.Data.BodyId.ToString(),null,[0,0,-30],[0,0,1])));
+ var response = await _client.PostAsJsonAsync(url+"/measure", request);
+ response.EnsureSuccessStatusCode();
+ var json = await response.Content.ReadFromJsonAsync<JsonElement>();
+ Assert.Equal(6, json.GetProperty("data").GetProperty("measurement").GetProperty("distanceMm").GetDouble());
+ await _client.PostAsJsonAsync(url+$"/bodies/{body.Data.BodyId}/transform", new {translation=new {x=1,y=0,z=0}});
+ var stale = await _client.PostAsJsonAsync(url+"/measure", request);
+ Assert.Equal(HttpStatusCode.BadRequest, stale.StatusCode);
+ Assert.Contains("measurement-stale-revision", await stale.Content.ReadAsStringAsync());
+ }
+}
diff --git a/Aetheris.Server/Aetheris.Server.csproj b/Aetheris.Server/Aetheris.Server.csproj
index f0e17857..98380789 100644
--- a/Aetheris.Server/Aetheris.Server.csproj
+++ b/Aetheris.Server/Aetheris.Server.csproj
@@ -13,6 +13,7 @@
</PropertyGroup>
<ItemGroup>
+ <ProjectReference Include="..\Aetheris.Geometry\Aetheris.Geometry.csproj" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.24" />
<PackageReference Include="Microsoft.AspNetCore.SpaProxy" Version="8.0.24" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
diff --git a/Aetheris.Server/Api/KernelEndpoints.cs b/Aetheris.Server/Api/KernelEndpoints.cs
index fe69e8cb..ed1862f9 100644
--- a/Aetheris.Server/Api/KernelEndpoints.cs
+++ b/Aetheris.Server/Api/KernelEndpoints.cs
@@ -29,6 +29,13 @@ public static class KernelEndpoints
private static void MapDocumentRoutes(RouteGroupBuilder documents)
{
+ documents.MapPost("/{documentId:guid}/measure", (Guid documentId, DocumentMeasurementRequest request, KernelDocumentStore store) =>
+ WithDocument(store, documentId, document =>
+ {
+ try { return ApiMappings.Ok(new { revision = request.Revision, measurement = document.Measure(request.Revision, request.Measurement) }); }
+ catch (Aetheris.Geometry.MeasurementException error) { return Results.BadRequest(new ApiResponseDto<object>(false, null,
+ [new DiagnosticDto(error.Code, "Error", error.Message, "Measurement")])); }
+ }));
documents.MapPost("", (DocumentCreateRequestDto? request, KernelDocumentStore store) =>
{
var created = store.Create(request?.Name);
@@ -63,7 +70,7 @@ public static class KernelEndpoints
bodyIds.Length,
bodyIds,
definitions.Count,
- occurrenceSummaries));
+ occurrenceSummaries, document.Revision));
});
documents.MapPost("/{documentId:guid}/bodies/primitives/box", (Guid documentId, BoxCreateRequestDto request, KernelDocumentStore store) =>
@@ -269,10 +276,13 @@ public static class KernelEndpoints
if (!AssemblyDisplayService.TryBuildStep(assemblyResult.Value, out var assemblyPacket, out var displayError))
return ApiMappings.BadRequestFromMessage(displayError, "documents.import.step.assembly.display");
var qualifications = assemblyPacket!.Definitions.Select(d => d.ImportQualification!).ToArray();
+ var definitionBodies = assemblyResult.Value.Definitions.Where(d => d.Geometry is not null).ToDictionary(d => d.StableId, d => d.Geometry!);
+ document.SetImportedMeasurementTargets(assemblyPacket.Occurrences.Where(o => o.DefinitionStableId is not null && definitionBodies.ContainsKey(o.DefinitionStableId))
+ .Select(o => new Aetheris.Geometry.MeasurementTarget(o.StableId, definitionBodies[o.DefinitionStableId!], Transform3D.FromRowMajor(o.WorldTransform))).ToArray());
var status = qualifications.Length == 0 ? "Failed" : qualifications.Max(q => q.Status).ToString();
return ApiMappings.Ok(new StepImportResponseDto(documentId, Guid.Empty, Guid.Empty,
assemblyPacket.Name, assemblyResult.Diagnostics.Select(ApiMappings.ToDiagnostic).ToArray(), AssemblyPresentation: assemblyPacket,
- ImportStatus: status, ImportQualifications: qualifications));
+ ImportStatus: status, ImportQualifications: qualifications, Revision: document.Revision));
}
if (assemblyResult.Diagnostics.All(diagnostic => diagnostic.Source != "Importer.Assembly.ProductStructure"))
return ApiMappings.KernelFailure(assemblyResult.Diagnostics);
diff --git a/Aetheris.Server/Contracts/ApiContracts.cs b/Aetheris.Server/Contracts/ApiContracts.cs
index 9e0a6d55..dc4b29e9 100644
--- a/Aetheris.Server/Contracts/ApiContracts.cs
+++ b/Aetheris.Server/Contracts/ApiContracts.cs
@@ -16,7 +16,9 @@ public sealed record DocumentSummaryResponseDto(
int BodyCount,
IReadOnlyList<Guid> BodyIds,
int DefinitionCount,
- IReadOnlyList<BodyOccurrenceSummaryDto> Occurrences);
+ IReadOnlyList<BodyOccurrenceSummaryDto> Occurrences, long Revision = 0);
+
+public sealed record DocumentMeasurementRequest(long Revision, Aetheris.Geometry.MeasurementRequest Measurement);
public sealed record BodyCreatedResponseDto(Guid DocumentId, Guid BodyId, Guid DefinitionId, int FaceCount, int EdgeCount, int VertexCount);
@@ -53,7 +55,7 @@ public sealed record StepImportResponseDto(
CadmataVisualizationArtifactDto? SemanticPresentation = null,
AssemblyDisplayPacketDto? AssemblyPresentation = null,
string ImportStatus = "Inspectable",
- IReadOnlyList<Aetheris.Kernel.Core.Import.BrepImportQualificationReport>? ImportQualifications = null);
+ IReadOnlyList<Aetheris.Kernel.Core.Import.BrepImportQualificationReport>? ImportQualifications = null, long Revision = 0);
public sealed record ExtrudeRequestDto(
IReadOnlyList<ProfilePoint2Dto> Profile,
diff --git a/Aetheris.Server/Documents/DocumentSession.cs b/Aetheris.Server/Documents/DocumentSession.cs
index b6ef690a..6eb71719 100644
--- a/Aetheris.Server/Documents/DocumentSession.cs
+++ b/Aetheris.Server/Documents/DocumentSession.cs
@@ -1,5 +1,6 @@
using Aetheris.Kernel.Core.Brep;
using Aetheris.Kernel.Core.Math;
+using Aetheris.Geometry;
namespace Aetheris.Server.Documents;
@@ -8,6 +9,31 @@ public sealed class DocumentSession
private readonly Dictionary<Guid, BrepBody> _definitions = new();
private readonly Dictionary<Guid, BodyOccurrence> _occurrences = new();
private readonly object _sync = new();
+ private long _revision;
+ private long _measurementRevision = -1;
+ private IReadOnlyList<MeasurementTarget> _measurementTargets = [];
+ private IReadOnlyList<MeasurementTarget> _importedMeasurementTargets = [];
+ public long Revision { get { lock (_sync) return _revision; } }
+
+ public void SetImportedMeasurementTargets(IReadOnlyList<MeasurementTarget> targets)
+ {
+ lock (_sync) { _importedMeasurementTargets = targets; _revision++; }
+ }
+
+ public MeasurementResult Measure(long revision, MeasurementRequest request)
+ {
+ lock (_sync)
+ {
+ if (revision != _revision) throw new MeasurementException("measurement-stale-revision", "The document changed. Reload the displayed geometry before measuring.");
+ if (_measurementRevision != _revision)
+ {
+ _measurementTargets = _occurrences.Values.Select(o => new MeasurementTarget(o.OccurrenceId.ToString(), _definitions[o.DefinitionId], o.Placement))
+ .Concat(_importedMeasurementTargets).ToArray();
+ _measurementRevision = _revision;
+ }
+ return BrepMeasurementQuery.Measure(_measurementTargets, request);
+ }
+ }
public DocumentSession(Guid id, string? name = null)
{
@@ -43,6 +69,7 @@ public sealed class DocumentSession
var occurrenceId = Guid.NewGuid();
_definitions[definitionId] = body;
_occurrences[occurrenceId] = new BodyOccurrence(occurrenceId, definitionId, Transform3D.Identity, occurrenceName);
+ _revision++;
return (occurrenceId, definitionId);
}
}
@@ -90,6 +117,7 @@ public sealed class DocumentSession
var occurrenceId = Guid.NewGuid();
occurrence = new BodyOccurrence(occurrenceId, definitionId, Transform3D.Identity, name);
_occurrences[occurrenceId] = occurrence;
+ _revision++;
return true;
}
}
@@ -107,6 +135,7 @@ public sealed class DocumentSession
var occurrenceId = Guid.NewGuid();
occurrence = new BodyOccurrence(occurrenceId, source.DefinitionId, Transform3D.Identity, name);
_occurrences[occurrenceId] = occurrence;
+ _revision++;
return true;
}
}
@@ -142,6 +171,7 @@ public sealed class DocumentSession
var delta = Transform3D.CreateTranslation(translation);
updatedTransform = delta * occurrence.Placement;
_occurrences[occurrenceId] = occurrence with { Placement = updatedTransform };
+ _revision++;
return true;
}
}
diff --git a/Aetheris.Web.Runtime/Aetheris.Web.Runtime.csproj b/Aetheris.Web.Runtime/Aetheris.Web.Runtime.csproj
index 5d87fbad..a2081156 100644
--- a/Aetheris.Web.Runtime/Aetheris.Web.Runtime.csproj
+++ b/Aetheris.Web.Runtime/Aetheris.Web.Runtime.csproj
@@ -12,9 +12,11 @@
<Description>Browser WebAssembly host for the public Aetheris CAD TypeScript SDK.</Description>
</PropertyGroup>
<ItemGroup>
+ <ProjectReference Include="..\Aetheris.Geometry\Aetheris.Geometry.csproj" />
<ProjectReference Include="..\Aetheris.Kernel.Firmament\Aetheris.Kernel.Firmament.csproj" />
<!-- The JSON bridge serializes anonymous response shapes through reflection. -->
<TrimmerRootAssembly Include="Aetheris.Web.Runtime" />
+ <TrimmerRootAssembly Include="Aetheris.Geometry" />
<TrimmerRootAssembly Include="Aetheris.Kernel.Firmament" />
<!-- Assembly/Scene snapshots serialize semantic provenance records. Preserve
their constructor parameter metadata for the reflection JSON bridge. -->
diff --git a/Aetheris.Web.Runtime/Program.Measurement.cs b/Aetheris.Web.Runtime/Program.Measurement.cs
new file mode 100644
index 00000000..023cd1c8
--- /dev/null
+++ b/Aetheris.Web.Runtime/Program.Measurement.cs
@@ -0,0 +1,23 @@
+using Aetheris.Geometry;
+
+namespace Aetheris.Web.Runtime;
+
+public static partial class Program
+{
+ private sealed partial class WebModelSession
+ {
+ private IReadOnlyList<MeasurementTarget> _measurementTargets = [];
+ private IReadOnlyList<MeasurementTarget> _pendingMeasurementTargets = [];
+
+ public object Measure(WebRequest request)
+ {
+ if (_dirty || request.BuildRevision != Revision)
+ throw new WebRuntimeException("measurement-stale-revision", "Build the current source successfully before measuring.");
+ if (_measurementTargets.Count == 0)
+ throw new WebRuntimeException("measurement-geometry-unavailable", "This build has no retained BRep measurement geometry. Scene and mesh-only measurement is not yet supported.");
+ if (request.Measurement is null) throw new WebRuntimeException("measurement-request-invalid", "A measurement request is required.");
+ try { return new { revision = Revision, measurement = BrepMeasurementQuery.Measure(_measurementTargets, request.Measurement) }; }
+ catch (MeasurementException error) { throw new WebRuntimeException(error.Code, error.Message); }
+ }
+ }
+}
diff --git a/Aetheris.Web.Runtime/Program.cs b/Aetheris.Web.Runtime/Program.cs
index 7e5fa66c..44e657f7 100644
--- a/Aetheris.Web.Runtime/Program.cs
+++ b/Aetheris.Web.Runtime/Program.cs
@@ -68,6 +68,7 @@ public static partial class Program
"rewriteField" => RewriteField(request),
"snapshot" => Session(request).Snapshot,
"sampleMotion" => Session(request).SampleMotion(request),
+ "measure" => Session(request).Measure(request),
"setProperty" => SetProperty(request),
"setSource" => SetSource(request),
"rebuild" => Rebuild(request),
@@ -277,7 +278,7 @@ public static partial class Program
bool Performance = false, IReadOnlyDictionary<string, string>? ProjectDocuments = null, string? ProjectRoot = null,
int? Bridge = null, IReadOnlyList<FirmamentLanguageEditOperation>? Operations = null,
string? Motion = null, double? TimeSeconds = null, bool PreserveEndpoint = false,
- IReadOnlyList<string>? Formats = null);
+ IReadOnlyList<string>? Formats = null, Aetheris.Geometry.MeasurementRequest? Measurement = null);
/// <summary>
/// BUILD-PERF-M3 response bridge (request <c>bridge: 1</c>, sent by the SDK). Large numeric arrays
@@ -302,7 +303,7 @@ public static partial class Program
public string Code { get; } = code;
}
- private sealed class WebModelSession(string id, string source, string sourceName, IReadOnlyDictionary<string, string>? projectDocuments) : IDisposable
+ private sealed partial class WebModelSession(string id, string source, string sourceName, IReadOnlyDictionary<string, string>? projectDocuments) : IDisposable
{
private string _source = source;
private string _sourceName = sourceName;
@@ -340,7 +341,7 @@ public static partial class Program
throw new WebRuntimeException(separator > 0 ? error.Message[..separator] : "export-failed", error.Message);
}
}
- public void Dispose() { _assembly = null; _pendingAssembly = null; _scene = null; _pendingScene = null; _exportDisplay = null; _compilationSession.Dispose(); _sceneSession.Dispose(); }
+ public void Dispose() { _measurementTargets = []; _pendingMeasurementTargets = []; _assembly = null; _pendingAssembly = null; _scene = null; _pendingScene = null; _exportDisplay = null; _compilationSession.Dispose(); _sceneSession.Dispose(); }
internal object SampleMotion(WebRequest request)
{
if (_assembly is null || request.Motion is null || request.TimeSeconds is null)
@@ -455,6 +456,7 @@ public static partial class Program
_lastReuse = null;
_pendingAssembly = null;
_pendingScene = null;
+ _pendingMeasurementTargets = [];
_dirty = true;
var nextProperties = sourceProperties;
foreach (var (propertyId, value) in _overrides)
@@ -472,6 +474,7 @@ public static partial class Program
return compiled with { Revision = Revision, RetainedPreviousGeometry = _lastSnapshot is not null };
Revision++;
+ _measurementTargets = _pendingMeasurementTargets;
_assembly = _pendingAssembly;
_scene = _pendingScene;
_exportDisplay = compiled.ExportDisplay ?? (AssemblyDisplayMeshDocument)compiled.Mesh!;
@@ -499,6 +502,7 @@ public static partial class Program
{
id = Id, name = Name, revision = Revision, source = _source, sourceName = _sourceName,
tree = compiled.Tree, properties = _properties, mesh = compiled.Mesh,
+ measurementAvailable = _measurementTargets.Count > 0,
diagnostics = compiled.Diagnostics, changes, timings,
exportFormats = ProductArtifactExporter.Options(_stepText is not null || _stepWriter is not null, _assembly is null && _scene is null),
motions = (_assembly?.Motions ?? []).Select(m => new { m.Name, m.DurationSeconds, repeat = m.Repeat.ToString(),
@@ -536,6 +540,7 @@ public static partial class Program
var definitionId = "definition:" + Sha(step)[..16].ToLowerInvariant();
var entityId = build.Value.RuntimeCorrespondence?.BodyStableId
?? (string.IsNullOrWhiteSpace(build.Value.ExportedFeatureId) ? Id + ":body" : build.Value.ExportedFeatureId);
+ _pendingMeasurementTargets = [new(entityId + ":occurrence", displayBody, Aetheris.Kernel.Core.Math.Transform3D.Identity)];
var sourceMap = build.Value.RuntimeCorrespondence is { } correspondence
? new Aetheris.Kernel.Firmament.Materializer.GeometrySourceMap(correspondence) : null;
WebSourceRef? CompilerSource(string symbol) =>
@@ -634,6 +639,11 @@ public static partial class Program
var root = new WebTreeNode(compilation.Ir.RootInstanceStableId, "Assembly", compilation.Ir.Name, null, children, true, SourceRef(_sourceName, 0, effective.Length));
var tree = new { rootId = root.Id, nodes = nodes.Prepend(root).DistinctBy(node => node.Id).ToArray() };
_pendingAssembly = compilation.Ir;
+ var measurementDefinitions = compilation.Geometry.Artifact.Definitions.ToDictionary(d => d.StableId,
+ d => compilation.Geometry.DefinitionBodies[d.DefinitionIdentity], StringComparer.Ordinal);
+ _pendingMeasurementTargets = compilation.Geometry.Artifact.Instances.Select(instance =>
+ new Aetheris.Geometry.MeasurementTarget(instance.InstanceStableId, measurementDefinitions[instance.DefinitionArtifactStableId],
+ Aetheris.Kernel.Core.Math.Transform3D.FromRowMajor(instance.WorldTransform.Matrix))).ToArray();
return WebBuildResult.Passed(null, tree, mesh, nodes.Select(node => node.Id).Prepend(root.Id).Distinct().ToArray(), compileMs, meshMs) with { StepWriter = StepWriter };
}
diff --git a/Aetheris.Web.Runtime/sdk/scripts/build.mjs b/Aetheris.Web.Runtime/sdk/scripts/build.mjs
index 329efadc..073e1c0a 100644
--- a/Aetheris.Web.Runtime/sdk/scripts/build.mjs
+++ b/Aetheris.Web.Runtime/sdk/scripts/build.mjs
@@ -13,7 +13,7 @@ const run = args => {
const result = spawnSync('dotnet', args, { cwd: repo, stdio: 'inherit' });
if (result.status !== 0) process.exit(result.status ?? 1);
};
-run(['build', project, '-c', 'Release', '--nologo']);
+run(['build', project, '-c', 'Release', '--nologo', '-m:1', '-nr:false', '-p:UseSharedCompilation=false']);
const app = join(runtime, 'bin', 'Release', 'net10.0', 'wwwroot');
const dist = join(sdk, 'dist');
await rm(dist, { recursive: true, force: true });
diff --git a/Aetheris.Web.Runtime/sdk/src/index.d.ts b/Aetheris.Web.Runtime/sdk/src/index.d.ts
index 3e098d67..0d36c0d2 100644
--- a/Aetheris.Web.Runtime/sdk/src/index.d.ts
+++ b/Aetheris.Web.Runtime/sdk/src/index.d.ts
@@ -87,11 +87,13 @@ export class Aetheris {
export interface MotionClip { readonly name: string; readonly durationSeconds: number; readonly repeat: 'Once' | 'Loop'; readonly tracks: readonly { readonly name: string; readonly mateStableId: string; readonly jointName: string; readonly valueDimension: 'Angle' | 'Length' }[] }
export interface MotionPose { readonly revision: number; readonly motion: string; readonly timeSeconds: number; readonly state: Readonly<Record<string, number>>; readonly transforms: readonly { readonly id: string; readonly matrix: readonly number[] | Float64Array }[] }
export class ModelSession {
+ readonly measurementAvailable?: boolean;
readonly exportFormats: readonly ExportFormatOption[];
/** One format returns its file; multiple formats return one ZIP. Rejected exports produce no files. */
exportArtifacts(formats: readonly ExportFormat[], options?: OperationOptions): Promise<readonly ExportFile[]>;
readonly motions: readonly MotionClip[];
sampleMotion(motion: string, timeSeconds: number, options?: OperationOptions & { readonly preserveEndpoint?: boolean }): Promise<MotionPose>;
+ measure(request: MeasurementRequest, options?: OperationOptions): Promise<MeasurementResult>;
readonly id: string; readonly name: string; readonly revision: number; readonly source: string; readonly sourceName: string;
readonly tree: ModelTree; readonly properties: readonly EditableProperty[]; readonly mesh: DisplayMesh; readonly diagnostics: readonly Diagnostic[]; readonly changes: ChangeSet;
readonly timings?: { readonly compileMilliseconds: number; readonly meshMilliseconds?: number; readonly totalBeforeSnapshotMilliseconds?: number; readonly profile?: { readonly phases: readonly { readonly name: string; readonly inclusiveMilliseconds: number; readonly exclusiveMilliseconds: number; readonly allocatedBytes: number }[]; readonly counts: Readonly<Record<string, number>>; readonly gc0: number; readonly gc1: number; readonly gc2: number } };
@@ -118,3 +120,13 @@ export class ModelSession {
export type ExportFormat = 'step' | 'glb' | 'usda' | 'stl' | 'obj' | 'pdf' | 'svg' | 'pptx';
export interface ExportFormatOption { readonly format: ExportFormat; readonly label: string; readonly description: string; readonly available: boolean; readonly reason?: string | null }
export interface ExportFile { readonly fileName: string; readonly mediaType: string; readonly bytes: Uint8Array }
+
+export type MeasurementMode = 'points' | 'planes' | 'axes';
+export interface MeasurementPick { occurrenceId: string | null; faceId: number | null; rayOrigin: number[]; rayDirection: number[] }
+export interface MeasurementRequest { mode: MeasurementMode; first: MeasurementPick; second?: MeasurementPick; allowApproximate: boolean }
+export interface MeasurementReference { occurrenceId: string; faceId: number; surfaceKind: string; point: number[]; quality: string; diameterMm?: number | null }
+export interface MeasurementResult {
+ mode: MeasurementMode; first: MeasurementReference; second?: MeasurementReference | null;
+ distanceMm: number | null; deltaMm: number[] | null; witnessA: number[] | null; witnessB: number[] | null;
+ angleDegrees: number | null; quality: string; explanation: string;
+}
diff --git a/Aetheris.Web.Runtime/sdk/src/index.js b/Aetheris.Web.Runtime/sdk/src/index.js
index 57acd743..133f11ca 100644
--- a/Aetheris.Web.Runtime/sdk/src/index.js
+++ b/Aetheris.Web.Runtime/sdk/src/index.js
@@ -173,6 +173,15 @@ export class ModelSession {
return pose;
});
}
+ async measure(measurement, options = {}) {
+ return this.serial(async () => {
+ throwIfAborted(options.signal);
+ const reply = await this.transport.request({ operation: 'measure', sessionId: this.id, buildRevision: this.revision, measurement });
+ throwIfAborted(options.signal);
+ if (reply.revision !== this.revision) throw new AetherisError('measurement-stale-revision', 'The measurement belongs to a different build revision.');
+ return reply.measurement;
+ });
+ }
async describeConstruct(semanticId, options = {}) {
throwIfAborted(options.signal);
return this.transport.request({ operation: 'describeConstruct', sessionId: this.id, constructSemanticId: semanticId });
diff --git a/Aetheris.Web.Runtime/sdk/tests/measurement.test.mjs b/Aetheris.Web.Runtime/sdk/tests/measurement.test.mjs
new file mode 100644
index 00000000..1d69e611
--- /dev/null
+++ b/Aetheris.Web.Runtime/sdk/tests/measurement.test.mjs
@@ -0,0 +1,20 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { ModelSession } from '../src/index.js';
+
+const snapshot = { id: 'session', revision: 7, mesh: { definitions: [], occurrences: [] } };
+const request = { mode: 'planes', first: { occurrenceId: 'part', faceId: 2, rayOrigin: [0,0,30], rayDirection: [0,0,-1] } };
+
+test('measure uses the serialized session queue and current build revision', async () => {
+ const calls = [];
+ const transport = { request: async value => { calls.push(value); return { revision: 7, measurement: { distanceMm: 6 } }; } };
+ const model = new ModelSession(transport, snapshot);
+ assert.equal((await model.measure(request)).distanceMm, 6);
+ assert.deepEqual(calls, [{ operation: 'measure', sessionId: 'session', buildRevision: 7, measurement: request }]);
+});
+test('measure refuses a result from another build and preserves backend errors', async () => {
+ const model = new ModelSession({ request: async () => ({ revision: 6, measurement: { distanceMm: 6 } }) }, snapshot);
+ await assert.rejects(model.measure(request), error => error.code === 'measurement-stale-revision');
+ model.transport.request = async () => { throw new Error('unsupported trim'); };
+ await assert.rejects(model.measure(request), /unsupported trim/);
+});
diff --git a/Aetheris.Web.Runtime/telos/src/index.ts b/Aetheris.Web.Runtime/telos/src/index.ts
index a8922ed7..15b2938e 100644
--- a/Aetheris.Web.Runtime/telos/src/index.ts
+++ b/Aetheris.Web.Runtime/telos/src/index.ts
@@ -10,3 +10,4 @@ export * from "./presentation.js";
export * from "./temporal.js";
export * from "./concepts.js";
+export * from "./measurement.js";
diff --git a/Aetheris.Web.Runtime/telos/src/measurement.ts b/Aetheris.Web.Runtime/telos/src/measurement.ts
new file mode 100644
index 00000000..96c79534
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/src/measurement.ts
@@ -0,0 +1,163 @@
+import type { TelosLine } from './contracts.js';
+import { BufferGeometry, Float32BufferAttribute, Group, LineBasicMaterial, LineSegments } from 'three';
+
+export type MeasurementMode = 'points' | 'planes' | 'axes';
+export interface MeasurementPick { occurrenceId: string | null; faceId: number | null; rayOrigin: number[]; rayDirection: number[] }
+export interface MeasurementRequest { mode: MeasurementMode; first: MeasurementPick; second?: MeasurementPick; allowApproximate: boolean }
+export interface MeasurementReference { occurrenceId: string; faceId: number; surfaceKind: string; point: number[]; quality: string; diameterMm?: number | null }
+export interface MeasurementResult {
+ mode: MeasurementMode; first: MeasurementReference; second?: MeasurementReference | null;
+ distanceMm: number | null; deltaMm: number[] | null; witnessA: number[] | null; witnessB: number[] | null;
+ angleDegrees: number | null; quality: string; explanation: string;
+}
+
+/** Presentation only. All geometry and interpretation come from the compiler/server query owner. */
+export class MeasurementTool {
+ active = false;
+ mode: MeasurementMode = 'points';
+ result: MeasurementResult | null = null;
+ private first?: MeasurementPick;
+ private second?: MeasurementPick;
+ private slot: 'A' | 'B' = 'A';
+ private approximate = false;
+ private generation = 0;
+ private context: unknown;
+ private disabled = '';
+ private message = '';
+ private pending = false;
+ private inches = false;
+ private readonly keyboard = (event: KeyboardEvent) => {
+ const element = event.target as HTMLElement | null;
+ if (element?.closest('input,textarea,select,[contenteditable="true"]') || event.ctrlKey || event.metaKey || event.altKey) return;
+ if (event.key === 'Escape' && this.active) { this.active = false; this.reset(); this.render(); }
+ if (event.key.toLowerCase() === 'm' && !this.disabled && this.host.parentElement?.contains(document.activeElement)) {
+ event.preventDefault(); this.toggle();
+ }
+ };
+ constructor(private host: HTMLElement, private query: (request: MeasurementRequest) => Promise<MeasurementResult>, private changed: () => void) {
+ host.style.cssText = 'position:absolute;top:54px;right:12px;z-index:20;max-width:min(330px,90%);font:12px/1.5 system-ui;color:#202020';
+ host.addEventListener('pointerdown', event => event.stopPropagation());
+ host.addEventListener('click', event => event.stopPropagation());
+ document.addEventListener('keydown', this.keyboard);
+ this.render();
+ }
+ setContext(context: unknown, disabled = '') {
+ if (context === this.context && disabled === this.disabled) return;
+ this.context = context; this.disabled = disabled; this.reset(); this.render();
+ }
+ dispose() { this.generation++; document.removeEventListener('keydown', this.keyboard); this.host.replaceChildren(); }
+ private reset() { this.generation++; this.first = undefined; this.second = undefined; this.result = null; this.slot = 'A'; this.pending = false; this.message = ''; this.changed(); }
+ private toggle() { this.active = !this.active; this.reset(); this.render(); }
+ async pick(pick: MeasurementPick) {
+ if (!this.active || this.disabled) return;
+ const generation = ++this.generation;
+ const first = this.slot === 'A' || !this.first ? pick : this.first;
+ const second = this.slot === 'A' || !this.first ? this.second : pick;
+ // Stage input identities immediately so rapid A/B clicks remain a pair. No number or witness
+ // is published until the current complete request has been admitted by the query owner.
+ this.first = first; this.second = second; this.slot = 'B';
+ this.pending = true; this.message = ''; this.result = null; this.changed(); this.render();
+ try {
+ const result = await this.query({ mode: this.mode, first, second, allowApproximate: this.approximate });
+ if (generation !== this.generation) return;
+ this.first = first; this.second = second; this.result = result; this.slot = 'B'; this.changed();
+ } catch (error) {
+ if (generation !== this.generation) return;
+ // A failed replacement cannot leave an old number looking like the new measurement.
+ this.result = null; this.first = undefined; this.second = undefined; this.slot = 'A';
+ this.changed(); this.message = error instanceof Error ? error.message : String(error);
+ const details = (error as { details?: unknown })?.details;
+ if (typeof details === 'string' && details) this.message += ` ${details}`;
+ } finally { if (generation === this.generation) { this.pending = false; this.render(); } }
+ }
+ private render() {
+ this.host.replaceChildren();
+ this.host.style.background = ''; this.host.style.padding = ''; this.host.style.border = '';
+ const button = (label: string, action: () => void) => {
+ const b = document.createElement('button'); b.type = 'button'; b.textContent = label;
+ b.style.cssText = 'padding:5px 9px;margin:2px;border:1px solid #bbb;background:white;color:#222;border-radius:4px;cursor:pointer';
+ b.onclick = action; this.host.append(b); return b;
+ };
+ const toggle = button(this.active ? 'Close measurement (Esc)' : 'Measure · M', () => this.toggle());
+ toggle.disabled = !!this.disabled && !this.active; toggle.title = this.disabled || 'Measure two references in the current built model';
+ if (!this.active) return;
+ this.host.style.background = '#fffef9'; this.host.style.padding = '8px'; this.host.style.border = '1px solid #c6aa62'; this.host.style.borderRadius = '6px';
+ const line = (text: string) => { const p = document.createElement('div'); p.textContent = text; this.host.append(p); return p; };
+ const select = document.createElement('select'); select.setAttribute('aria-label', 'Measurement mode');
+ for (const [value, label] of [['points','Surface points'], ['planes','Support planes'], ['axes','Axes']]) {
+ const option = document.createElement('option'); option.value = value!; option.textContent = label!; select.append(option);
+ }
+ select.value = this.mode; select.onchange = () => { this.mode = select.value as MeasurementMode; this.reset(); this.render(); }; this.host.append(select);
+ button(this.inches ? 'Units: in' : 'Units: mm', () => { this.inches = !this.inches; this.render(); });
+ line(this.disabled || (this.pending ? 'Resolving BRep reference…' : `Pick ${this.slot}: click a visible face. Drag to orbit.`));
+ const slotButton = (slot: 'A' | 'B', reference?: MeasurementReference | null) => {
+ const b = button(`${slot === this.slot ? '●' : '○'} ${slot}: ${reference ? `${reference.surfaceKind} · face ${reference.faceId}` : 'not selected'}`, () => { this.slot = slot; this.render(); });
+ b.title = reference ? `${reference.occurrenceId} / face ${reference.faceId}` : `Replace reference ${slot}`;
+ };
+ slotButton('A', this.result?.first); slotButton('B', this.result?.second);
+ button('New measurement', () => { this.reset(); this.render(); });
+ const fmt = (value: number) => `${(value / (this.inches ? 25.4 : 1)).toLocaleString('en-US', { maximumFractionDigits: 6 })} ${this.inches ? 'in' : 'mm'}`;
+ if (this.result) {
+ const r = this.result;
+ line(r.quality).style.fontWeight = '600';
+ if (r.distanceMm !== null) line(`Distance: ${fmt(r.distanceMm)}`).style.fontSize = '17px';
+ if (r.deltaMm) line(`ΔX ${fmt(r.deltaMm[0]!)} · ΔY ${fmt(r.deltaMm[1]!)} · ΔZ ${fmt(r.deltaMm[2]!)}`);
+ if (r.angleDegrees !== null) line(`Acute angle: ${r.angleDegrees.toFixed(6)}°`);
+ for (const [name, ref] of [['A', r.first], ['B', r.second]] as const) if (ref?.diameterMm != null) line(`${name} diameter: ${fmt(ref.diameterMm)}`);
+ line(r.explanation);
+ button('Copy result', () => { void navigator.clipboard?.writeText(JSON.stringify(r, null, 2)).catch(() => { this.message = 'Clipboard unavailable; select the displayed result to copy.'; this.render(); }); });
+ }
+ if (this.mode === 'points') {
+ const label = document.createElement('label'), check = document.createElement('input'); check.type = 'checkbox'; check.checked = this.approximate;
+ check.onchange = () => { this.approximate = check.checked; this.reset(); this.render(); };
+ label.append(check, ' Allow approximate display points'); this.host.append(label);
+ }
+ if (this.message) { const message = line(this.message); message.setAttribute('role', 'alert'); message.style.color = '#a12217'; }
+ line('Read-only · world coordinates · no drawing dimensions authored').style.color = '#666';
+ }
+}
+
+/** Capture only deliberate clicks; an orbit drag must never replace a measurement reference. */
+export function bindMeasurementPicking(element: HTMLElement, tool: () => MeasurementTool | undefined,
+ rayAt: (x: number, y: number) => MeasurementPick | null): () => void {
+ let start: [number, number] | null = null;
+ let dragged = false;
+ const down = (event: PointerEvent) => { if (event.button === 0) { start = [event.clientX, event.clientY]; dragged = false; } };
+ const move = (event: PointerEvent) => { if (start && Math.hypot(event.clientX - start[0], event.clientY - start[1]) > 4) dragged = true; };
+ const click = (event: MouseEvent) => {
+ const current = tool();
+ if (!current?.active) return;
+ event.stopImmediatePropagation();
+ if (!start || dragged || event.button !== 0) return;
+ const rect = element.getBoundingClientRect();
+ const pick = rayAt(event.clientX - rect.left, event.clientY - rect.top);
+ if (pick) void current.pick(pick);
+ start = null;
+ };
+ element.addEventListener('pointerdown', down); element.addEventListener('pointermove', move); element.addEventListener('click', click, true);
+ return () => { element.removeEventListener('pointerdown', down); element.removeEventListener('pointermove', move); element.removeEventListener('click', click, true); };
+}
+
+/** Non-pickable witness guides. Endpoint crosses remain visible at zero distance. */
+export function measurementLines(result: MeasurementResult | null): TelosLine[] {
+ if (!result?.witnessA) return [];
+ const a = result.witnessA, b = result.witnessB;
+ const points: number[] = b ? [...a, ...b] : [];
+ const size = Math.max(0.1, Math.min(2, (result.distanceMm ?? 10) * 0.02));
+ for (const p of [a, b]) if (p) for (let axis = 0; axis < 3; axis++) {
+ const left = [...p], right = [...p]; left[axis]! -= size; right[axis]! += size; points.push(...left, ...right);
+ }
+ const lines: TelosLine[] = [];
+ for (let i = 0; i < points.length; i += 6) lines.push({ id: `measurement:witness:${i / 6}`, points: points.slice(i,i+6), identity: { occurrenceId: 'measurement:witness' }, color: [0.95, 0.55, 0.05, 1], widthPixels: 2, depthMode: 'always-on-top', overlay: true, pickable: false });
+ return lines;
+}
+
+export function measurementGroup(result: MeasurementResult | null): Group {
+ const group = new Group(); group.name = 'Measurement witnesses';
+ for (const guide of measurementLines(result)) {
+ const geometry = new BufferGeometry().setAttribute('position', new Float32BufferAttribute(Array.from(guide.points), 3));
+ const line = new LineSegments(geometry, new LineBasicMaterial({ color: '#f5a21c', depthTest: false, depthWrite: false, toneMapped: false }));
+ line.raycast = () => undefined; line.renderOrder = 30; group.add(line);
+ }
+ return group;
+}
diff --git a/aetheris.client/src/App.tsx b/aetheris.client/src/App.tsx
index 87798f13..f12fa20b 100644
--- a/aetheris.client/src/App.tsx
+++ b/aetheris.client/src/App.tsx
@@ -1,3 +1,4 @@
+import type { MeasurementRequest } from '@aetheris/three-telos';
import {
useCallback,
useEffect,
@@ -18,6 +19,7 @@ import {
executeBoolean,
exportDefinitionStep,
getDocumentSummary,
+ measureDocument,
importStep,
maximizePaperclips,
pickBody,
@@ -183,6 +185,7 @@ function App() {
const [viewportThemeId, setViewportThemeId] = useState<ViewportThemeId>(
loadViewportThemePreference,
);
+ const [measurementRevision, setMeasurementRevision] = useState<number | undefined>(undefined);
const [documentId, setDocumentId] = useState<string | null>(null);
const [bodyIds, setBodyIds] = useState<string[]>([]);
const [occurrences, setOccurrences] = useState<BodyOccurrenceSummaryDto[]>([]);
@@ -328,6 +331,11 @@ function App() {
}
}, []);
+ const measurementQuery = useCallback(async (request: MeasurementRequest) => {
+ if (!documentId || measurementRevision === undefined) throw new Error('Reload this model to establish its measurement revision.');
+ const restrict = (pick: MeasurementRequest['first']) => ({ ...pick, occurrenceId: assemblyPacket ? pick.occurrenceId : activeBodyId });
+ return measureDocument(documentId, measurementRevision, { ...request, first: restrict(request.first), second: request.second ? restrict(request.second) : undefined });
+ }, [documentId, measurementRevision, activeBodyId, assemblyPacket]);
const refreshSummaryAndActiveTessellation = useCallback(
async (targetBodyId?: string, suppressDisplayErrors = false): Promise<RefreshDisplayResult> => {
if (!documentId) {
@@ -335,6 +343,7 @@ function App() {
}
const summary = await getDocumentSummary(documentId);
+ setMeasurementRevision(summary.revision);
const selected =
targetBodyId ??
(summary.bodyIds.includes(activeBodyId ?? "")
@@ -569,6 +578,7 @@ function App() {
const qualificationStatus = imported.importStatus ?? "Inspectable";
setDiagnostics(imported.diagnostics);
if (imported.assemblyPresentation) {
+ setMeasurementRevision(imported.revision);
setAssemblyPacket(imported.assemblyPresentation);
setSelectedAssemblyOccurrenceId(null);
setDisplayPreparation(null);
@@ -1176,6 +1186,8 @@ function App() {
</label>
</div>
<AetherisViewport
+ measurementQuery={measurementQuery}
+ measurementDisabledReason={status === "loading" ? "Wait for geometry loading to finish." : assemblySourcePath ? "Measurement for this stateless preview is not available; import STEP to measure it." : measurementRevision === undefined ? "Load or create a BRep model before measuring." : undefined}
showConcepts={showConcepts}
busyMessage={status === "loading" ? statusMessage : null}
errorMessage={status === "error" ? statusMessage : null}
diff --git a/aetheris.client/src/__tests__/measurement.test.ts b/aetheris.client/src/__tests__/measurement.test.ts
new file mode 100644
index 00000000..5691752c
--- /dev/null
+++ b/aetheris.client/src/__tests__/measurement.test.ts
@@ -0,0 +1,49 @@
+import { describe, it, expect, vi } from 'vitest';
+import { MeasurementTool, bindMeasurementPicking, measurementLines, type MeasurementRequest, type MeasurementResult } from '@aetheris/three-telos';
+const pick = {occurrenceId:'part', faceId:1, rayOrigin:[0,0,10],rayDirection:[0,0,-1]};
+const answer = (request: MeasurementRequest): MeasurementResult => ({mode:request.mode,first:{occurrenceId:'part',faceId:1,surfaceKind:'Plane',point:[0,0,0],quality:'Analytic BRep'},second:request.second ? {occurrenceId:'part',faceId:2,surfaceKind:'Plane',point:[0,0,6],quality:'Analytic BRep'}:null,distanceMm:request.second?6:null,deltaMm:request.second?[0,0,6]:null,witnessA:[0,0,0],witnessB:request.second?[0,0,6]:null,angleDegrees:null,quality:'Analytic BRep',explanation:'picked points'});
+function setup(query:(request:MeasurementRequest)=>Promise<MeasurementResult>) {
+ const root=document.createElement('div'),host=document.createElement('div');root.append(host);document.body.append(root);
+ const tool = new MeasurementTool(host,query,()=>{});tool.setContext('revision-1');host.querySelector('button')!.click();
+ return {root,host,tool,close:()=>{tool.dispose();root.remove();}};
+}
+describe('shared measurement interaction',()=>{
+ it('advances A to B, replaces either reference, converts display units, and clears',async()=>{
+ const query=vi.fn(async(request:MeasurementRequest)=>answer(request)), {tool,host,close}=setup(query);
+ await tool.pick(pick);expect(host.textContent).toContain('Pick B');expect(tool.result?.distanceMm).toBeNull();
+ await tool.pick({...pick,faceId:2});expect(tool.result?.distanceMm).toBe(6);expect(host.textContent).toContain('ΔZ 6 mm');
+ Array.from(host.querySelectorAll('button')).find(b=>b.textContent?.includes('A:'))!.click();
+ await tool.pick({...pick,faceId:3});expect(query.mock.lastCall![0].first.faceId).toBe(3);expect(query.mock.lastCall![0].second?.faceId).toBe(2);
+ Array.from(host.querySelectorAll('button')).find(b=>b.textContent==='Units: mm')!.click();expect(host.textContent).toContain('0.23622 in');
+ tool.setContext('revision-2');expect(tool.result).toBeNull();expect(host.textContent).not.toContain('Distance:');
+ tool.setContext('revision-3','Build the source before measuring.');expect(host.querySelector('button')!.disabled).toBe(false);
+ host.querySelector('button')!.click();expect(tool.active).toBe(false);expect(host.querySelector('button')!.disabled).toBe(true);close();
+ });
+ it('keeps rapid clicks as A and B while the first reply is pending',async()=>{
+ const replies: Array<()=>void> = [];
+ const query=vi.fn((request:MeasurementRequest)=>new Promise<MeasurementResult>(resolve=>replies.push(()=>resolve(answer(request)))));
+ const {tool,close}=setup(query);
+ const a=tool.pick(pick), b=tool.pick({...pick,faceId:2});
+ expect(query.mock.lastCall![0].first.faceId).toBe(1);expect(query.mock.lastCall![0].second?.faceId).toBe(2);
+ replies[1]!();await b;replies[0]!();await a;
+ expect(tool.result?.distanceMm).toBe(6);expect(tool.result?.second?.faceId).toBe(2);close();
+ });
+ it('discards a late reply after rebuild and removes an old number on query failure',async()=>{
+ let resolve!:(result:MeasurementResult)=>void;
+ const {tool,host,close}=setup(()=>new Promise(r=>{resolve=r;}));
+ const pending=tool.pick(pick);tool.setContext('revision-2');resolve(answer({mode:'points',first:pick,allowApproximate:false}));await pending;
+ expect(tool.result).toBeNull();expect(host.textContent).not.toContain('Distance:');close();
+ let fail=false;const next=setup(async r=>{if(fail)throw new Error('unsupported trim');return answer(r);});
+ await next.tool.pick(pick);await next.tool.pick(pick);expect(next.tool.result?.distanceMm).toBe(6);fail=true;await next.tool.pick(pick);
+ expect(next.tool.result).toBeNull();expect(next.host.textContent).toContain('unsupported trim');expect(next.host.textContent).not.toContain('Distance:');next.close();
+ });
+ it('does not turn an orbit drag into a pick; witness guides never intercept picks',async()=>{
+ const query=vi.fn(async r=>answer(r)),{tool,root,close}=setup(query);const canvas=document.createElement('canvas');root.append(canvas);
+ const unbind=bindMeasurementPicking(canvas,()=>tool,()=>pick);
+ const pointer=(type:string,x:number)=>canvas.dispatchEvent(new MouseEvent(type,{clientX:x,clientY:20,button:0,bubbles:true}));
+ pointer('pointerdown',10);pointer('pointermove',50);pointer('click',50);expect(query).not.toHaveBeenCalled();
+ pointer('pointerdown',10);pointer('click',10);await Promise.resolve();expect(query).toHaveBeenCalledOnce();
+ const guides=measurementLines(answer({mode:'points',first:pick,second:pick,allowApproximate:false}));
+ expect(guides.length).toBe(7);expect(guides.every(g=>g.pickable===false && g.points.length===6)).toBe(true);unbind();close();
+ });
+});
diff --git a/aetheris.client/src/api/aetherisApi.ts b/aetheris.client/src/api/aetherisApi.ts
index c3d54673..f2d4bc67 100644
--- a/aetheris.client/src/api/aetherisApi.ts
+++ b/aetheris.client/src/api/aetherisApi.ts
@@ -1,3 +1,4 @@
+import type { MeasurementRequest, MeasurementResult } from '@aetheris/three-telos';
import { reportDesktopDiagnostic } from "../desktopDiagnostics";
export interface DiagnosticDto {
@@ -27,6 +28,7 @@ export interface BodyOccurrenceSummaryDto {
}
export interface DocumentSummaryResponseDto {
+ revision?: number;
documentId: string;
name: string | null;
bodyCount: number;
@@ -60,6 +62,7 @@ export interface StepExportResponseDto {
}
export interface StepImportResponseDto {
+ revision?: number;
documentId: string;
definitionId: string;
occurrenceId: string;
@@ -642,3 +645,11 @@ export async function prepareAssemblyDisplay(path: string): Promise<AssemblyDisp
}
export { parseEnvelope };
+
+export async function measureDocument(documentId: string, revision: number, measurement: MeasurementRequest): Promise<MeasurementResult> {
+ const reply = await request<{ revision: number; measurement: MeasurementResult }>(`/api/v1/documents/${documentId}/measure`, {
+ method: 'POST', body: JSON.stringify({ revision, measurement }),
+ });
+ if (reply.revision !== revision) throw new Error('The measurement belongs to a different document revision.');
+ return reply.measurement;
+}
diff --git a/aetheris.client/src/viewer/AetherisViewport.tsx b/aetheris.client/src/viewer/AetherisViewport.tsx
index 603c910f..c0e9d817 100644
--- a/aetheris.client/src/viewer/AetherisViewport.tsx
+++ b/aetheris.client/src/viewer/AetherisViewport.tsx
@@ -1,3 +1,4 @@
+import { MeasurementTool, bindMeasurementPicking, measurementLines } from '@aetheris/three-telos';
import { lazy, Suspense, useEffect, useMemo, useRef, useState } from "react";
import { TelosHost, clearColor } from "@aetheris/three-telos";
import type { AetherisViewportProps } from "./viewportProps";
@@ -17,6 +18,24 @@ export type { AetherisViewportProps } from "./viewportProps";
/** One graphics authority; legacy rendering is loaded only for unsupported browsers. */
export function AetherisViewport(props: AetherisViewportProps) {
+ const panel = useRef<HTMLDivElement>(null), tool = useRef<MeasurementTool | undefined>(undefined), latest = useRef(props); latest.current = props;
+ const [tick, setTick] = useState(0);
+ useEffect(() => {
+ if (!panel.current) return;
+ tool.current = new MeasurementTool(panel.current, request => {
+ const query = latest.current.measurementQuery; if (!query) throw new Error('No measurement geometry is available.');
+ return query(request);
+ }, () => setTick(n => n + 1));
+ setTick(n => n + 1);
+ return () => { tool.current?.dispose(); tool.current = undefined; };
+ }, []);
+ useEffect(() => { tool.current?.setContext(props.measurementQuery, props.measurementDisabledReason || (!props.measurementQuery ? 'Load a BRep model to measure.' : '')); },
+ [props.measurementQuery, props.measurementDisabledReason, props.displayScene, props.assemblyPacket]);
+ return <div tabIndex={0} style={{width:'100%',height:'100%',position:'relative'}} aria-label="Model measurement workspace">
+ <ViewportRenderer {...props} measurementTool={tool.current} measurementTick={tick} /><div ref={panel} />
+ </div>;
+}
+function ViewportRenderer(props: AetherisViewportProps) {
const [generation, setGeneration] = useState(0);
const supported = typeof navigator !== "undefined" && !!navigator.gpu;
const legacyReason = !supported ? "WebGPU unavailable" : null;
@@ -94,7 +113,8 @@ function TelosViewport(props: AetherisViewportProps & { onRetry(): void }) {
theme = value.theme ?? ATELIER_VIEWPORT_THEME;
current.setAA(value.aaMode ?? "SpatialOnly", value.aaDebug ?? "color");
current.setPresentation(telosPresentation(theme));
- current.setScene(inspectSurfaces(cadmataTelosScene(value), inspection.current.mode, inspection.current.face));
+ const scene = inspectSurfaces(cadmataTelosScene(value), inspection.current.mode, inspection.current.face);
+ current.setScene({...scene, lines:[...scene.lines, ...measurementLines(value.measurementTool?.result ?? null)]});
canvas.current?.setAttribute("data-concept-wires", String(current.scene.lines.filter(line => line.id.startsWith("concept:") && !line.id.endsWith(":halo")).length));
current.background = clearColor(theme.sceneBackground);
current.grid = value.showGrid !== false && theme.gridStyle.enabled;
@@ -140,6 +160,13 @@ function TelosViewport(props: AetherisViewportProps & { onRetry(): void }) {
if (value.assemblyPacket && hit)
value.onAssemblyOccurrenceSelect?.(hit.occurrenceId);
};
+ const unbindMeasurement = bindMeasurementPicking(element, () => latest.current.measurementTool, (x,y) => {
+ const current = host.current; if (!current) return null;
+ const ray = current.camera.worldRay([x,y]), hit = current.picker.pick([x,y], 'face');
+ if (!hit || hit.overlayId) return null;
+ const face = hit.faceId == null ? null : Number(String(hit.faceId).split(':').pop());
+ return { occurrenceId: latest.current.assemblyPacket ? hit.occurrenceId : null, faceId: Number.isInteger(face) ? face : null, rayOrigin: ray.origin.toArray(), rayDirection: ray.direction.toArray() };
+ });
element.addEventListener("click", click);
const hover = (event: PointerEvent) => {
const current = host.current;
@@ -187,6 +214,7 @@ function TelosViewport(props: AetherisViewportProps & { onRetry(): void }) {
if (!disposed) setDiagnostic(String(error));
});
return () => {
+ unbindMeasurement();
disposed = true;
initialization.abort();
element.removeEventListener("click", click);
diff --git a/aetheris.client/src/viewer/LegacyAetherisViewport.tsx b/aetheris.client/src/viewer/LegacyAetherisViewport.tsx
index 73ce343d..39b830a8 100644
--- a/aetheris.client/src/viewer/LegacyAetherisViewport.tsx
+++ b/aetheris.client/src/viewer/LegacyAetherisViewport.tsx
@@ -1,3 +1,4 @@
+import { bindMeasurementPicking, measurementGroup, type MeasurementTool } from '@aetheris/three-telos';
/* eslint-disable react-hooks/immutability -- Three.js cameras/renderers are intentionally configured through their imperative mutable API. */
import { Line, OrbitControls, Text } from "@react-three/drei";
import { Canvas, useFrame, useThree } from "@react-three/fiber";
@@ -270,12 +271,14 @@ export type { AetherisViewportProps } from "./viewportProps";
import type { AetherisViewportProps } from "./viewportProps";
function FaceMesh({
+ faceId,
positions,
normals,
indices,
isHighlighted,
theme,
}: {
+ faceId?: number;
positions: Float32Array;
normals: Float32Array;
indices: Uint32Array;
@@ -311,6 +314,7 @@ function FaceMesh({
);
return (
<mesh
+ userData={{ measurementFaceId: faceId }}
geometry={geometry}
material={material}
castShadow={theme.shadowStyle.enabled}
@@ -392,6 +396,24 @@ function EdgeLine({
);
}
+function MeasurementGuides({tool, tick}: {tool?: MeasurementTool; tick?: number}) {
+ const {scene, camera, gl, invalidate} = useThree();
+ useEffect(() => {
+ if (!tool?.result) return;
+ const group = measurementGroup(tool?.result ?? null); scene.add(group); invalidate();
+ return () => { disposeConceptWireframe(group); invalidate(); };
+ }, [scene, tool, tick, invalidate]);
+ useEffect(() => bindMeasurementPicking(gl.domElement, () => tool, (x,y) => {
+ const raycaster = new Raycaster(); raycaster.setFromCamera(new Vector2(x / gl.domElement.clientWidth * 2 - 1, 1 - y / gl.domElement.clientHeight * 2), camera);
+ const hit = raycaster.intersectObjects(scene.children, true).find(h => Number.isInteger(h.object.userData.measurementFaceId));
+ if (!hit) return null;
+ let parent = hit.object.parent;
+ while (parent && !parent.userData.measurementOccurrenceId) parent = parent.parent;
+ return { occurrenceId: parent?.userData.measurementOccurrenceId ?? null, faceId: hit.object.userData.measurementFaceId, rayOrigin: raycaster.ray.origin.toArray(), rayDirection: raycaster.ray.direction.toArray() };
+ }), [gl.domElement, scene, camera, tool]);
+ return null;
+}
+
function PickRayCapture({ onPickRay }: { onPickRay?: AetherisViewportProps["onPickRay"] }) {
const { camera, gl } = useThree();
useEffect(() => {
@@ -510,6 +532,7 @@ function AssemblyMeshes({
return (
<group
key={occurrence.stableId}
+ userData={{ measurementOccurrenceId: occurrence.stableId }}
matrix={matrix}
matrixAutoUpdate={false}
onClick={(event) => {
@@ -520,6 +543,7 @@ function AssemblyMeshes({
{(definitions.get(occurrence.definitionStableId!) ?? []).map((patch) => (
<FaceMesh
key={`${occurrence.stableId}-${patch.faceId}`}
+ faceId={patch.faceId}
positions={patch.positions}
normals={patch.normals}
indices={patch.indices}
@@ -553,6 +577,7 @@ function ConceptWires({ packet }: { packet: DisplayPacket }) {
}
export function LegacyAetherisViewport({
+ measurementTool, measurementTick,
showConcepts = false,
displayScene = null,
highlightedFaceId = null,
@@ -636,6 +661,7 @@ export function LegacyAetherisViewport({
AnalyticPatch: (patch) => [
<FaceMesh
key={`analytic-${patch.faceId}`}
+ faceId={patch.faceId}
positions={patch.previewMesh.positions}
normals={patch.previewMesh.normals}
indices={patch.previewMesh.indices}
@@ -648,6 +674,7 @@ export function LegacyAetherisViewport({
MeshPatch: (patch) => [
<FaceMesh
key={`mesh-${patch.faceId}`}
+ faceId={patch.faceId}
positions={patch.mesh.positions}
normals={patch.mesh.normals}
indices={patch.mesh.indices}
@@ -698,7 +725,8 @@ export function LegacyAetherisViewport({
onSelect={onCadmataSelect}
theme={theme}
/>
- <PickRayCapture onPickRay={onPickRay} />
+ <MeasurementGuides tool={measurementTool} tick={measurementTick} />
+ <PickRayCapture onPickRay={onPickRay} />
<OrbitControls makeDefault enablePan enableZoom />
</Canvas>
);
diff --git a/aetheris.client/src/viewer/viewportProps.ts b/aetheris.client/src/viewer/viewportProps.ts
index cbeaac78..14486015 100644
--- a/aetheris.client/src/viewer/viewportProps.ts
+++ b/aetheris.client/src/viewer/viewportProps.ts
@@ -5,6 +5,10 @@ import type { CadmataLayerVisibility } from "./cadmataLayers";
import type { PmiVisibility } from "./pmiPresentation";
import type { ViewportTheme } from "./viewportTheme";
export interface AetherisViewportProps {
+ measurementQuery?: (request: import('@aetheris/three-telos').MeasurementRequest) => Promise<import('@aetheris/three-telos').MeasurementResult>;
+ measurementDisabledReason?: string;
+ measurementTool?: import('@aetheris/three-telos').MeasurementTool;
+ measurementTick?: number;
showConcepts?: boolean;
busyMessage?: string | null;
errorMessage?: string | null;
diff --git a/docs/development/FIRMAMENT-ASSERTIONS-2026-10-19.md b/docs/development/FIRMAMENT-ASSERTIONS-2026-10-19.md
index ba7ce0c3..ac192490 100644
--- a/docs/development/FIRMAMENT-ASSERTIONS-2026-10-19.md
+++ b/docs/development/FIRMAMENT-ASSERTIONS-2026-10-19.md
@@ -185,3 +185,13 @@ and ToleranceStackup uses shared AST admission while preserving its existing
worst-case solver. Geometry qualification remains intact. Unsupported measurement
families reject honestly; this pass does not claim a general curved-BRep volume
integrator, Boolean-mirror parity, or dedicated-domain assertion support.
+
+## Follow-up: historical fillet assertion cleanup
+
+The subsequent UI measurement pass replaces the six unsupported historical volume
+assertions with a provable single-shell topology assertion. These fixtures now
+compile through normal admission; their existing detailed geometry regressions
+remain. `HistoricalFilletGeometryBuildsButAnUnprovableVolumeAssertionStillRejects`
+retains a separate rejection witness and STEP parity comparison. This supersedes
+the earlier decision to leave these six fixtures rejected, without claiming a
+new exact curved-fillet volume capability.
diff --git a/docs/development/UI-MEASUREMENT-2026-10-19.md b/docs/development/UI-MEASUREMENT-2026-10-19.md
new file mode 100644
index 00000000..5627a490
--- /dev/null
+++ b/docs/development/UI-MEASUREMENT-2026-10-19.md
@@ -0,0 +1,169 @@
+# Cadmata / Helios measurement queries and fillet assertion cleanup
+
+## Scope and ownership
+
+The viewport now exposes a read-only measurement tool in both Cadmata and Helios.
+`Aetheris.Geometry.BrepMeasurementQuery` owns BRep reference resolution and numerical
+interpretation. It reuses `BrepPicker`, `AnalyticDisplayQuery`, native analytic
+surfaces, and rigid occurrence transforms. The public browser SDK and Cadmata HTTP
+endpoint call that owner; neither frontend implements CAD distance calculations.
+The shared Telos tool owns input state, labels and non-pickable witness guides.
+
+The admitted modes are picked surface-point distance, parallel support-plane
+spacing, and infinite analytic-axis spacing. The latter modes disclose their
+scope instead of labeling supporting geometry as finite-body clearance. Angles
+are acute and explicitly labeled. Cylinder diameters are projected directly from
+the native surface. World ΔX/ΔY/ΔZ and millimetre/inch presentation share the same
+result, and Copy result preserves the underlying millimetre data.
+
+This is deliberately not a general trimmed-face minimum-distance solver. The
+existing bounded parametric closest-point engine does not, by itself, admit that
+claim for arbitrary BRep trims. Edge/vertex snapping and general material clearance
+remain separate follow-ups; no speculative solver was added here.
+
+## Integrity and interaction
+
+- A/B input references are independently replaceable. Rapid clicks stage the pair
+ while the backend resolves it; generation checks discard superseded replies.
+- Rebuilds, source drift, loading transitions, document placement edits and motion
+ playback clear or disable results. Server and WASM revision checks independently
+ reject stale requests. Failed builds retain the model through the existing app
+ path but do not retain an apparently current measurement.
+- Pick errors clear the previous number. A failed replacement cannot leave a
+ previous value looking like a newly accepted result.
+- Dragging or orbiting does not replace a reference. Witnesses are excluded from
+ engineering picking in Telos and WebGL.
+- Native analytic picks must pass the existing trim support policy. Approximate
+ display points require explicit opt-in, apply only to point mode, and label the
+ whole result approximate. They are not tolerance-verification evidence.
+- The frontmost unsupported surface cannot be skipped to find a supported back
+ face. Ray-only requests on an incomplete pick proxy require an explicit face.
+- Double-sided candidate picking matches the viewport, including visible inward
+ hole walls. The final analytic point still comes from the BRep query owner.
+- Document measurement caches are invalidated by the document revision. Browser
+ geometry is retained from the successful compilation, not rebuilt from text
+ during a query. Assembly definitions are paired with solved occurrence matrices.
+
+## Runtime correction
+
+Real-browser testing exposed the native bounded tessellation wrapper's blocking
+Task/monitor wait, which browser WASM cannot execute. Measurement pick preparation
+now follows the existing WebMeshBuilder policy: synchronous tessellation inside
+the browser Worker, bounded partial preparation on the native host. A browser
+proxy preparation failure is a named `measurement-display-unavailable` error.
+The browser path does not claim native hard-timeout preemption. Geometry and
+measurement interpretation remain in the same kernel owners.
+
+## Supported contexts and remaining boundaries
+
+Helios retains query targets for Parts and static Assemblies. Cadmata retains
+document bodies and imported STEP assembly definitions with their world occurrence
+placements. Both viewports integrate the shared tool into Telos and WebGL paths.
+Scene/mesh-only builds, animated poses, and Cadmata stateless Firmament gallery
+previews are explicitly unavailable. They need a retained geometry/pose context,
+not a renderer-only calculation. No new Firmament syntax or engineering geometry
+construction was introduced.
+
+## Historical fillet assertions
+
+The six `CanonicalGeometry` curved-fillet specimens previously asserted volumes
+that the admitted volume authority could not prove. Those assertions are replaced
+with `Assert Topology Body { shells: 1 }`. Normal compilation now admits them;
+their detailed existing topology, surface-family and deterministic STEP tests
+remain. A separate negative witness still requires an appended unprovable volume
+assertion to reject with `assert-volume-measurement-unavailable`.
+
+The CLI built controls from the original Git sources with only their unsupported
+Volume assertion removed, then built the revised fixtures. All six STEP outputs
+were byte-identical. Raw source controls, CLI JSON, STEP files and SHA-256 evidence
+are under ignored `artifacts/local/measurement-parity/`.
+
+## Qualification
+
+Focused geometry tests exercise world-space point deltas, parallel-plane spacing,
+nonparallel angles, rotated/repeated instances, parallel and skew axes, diameters,
+stale topology identities, invalid rays, hole voids and unsupported foreground
+surfaces with explicitly labeled display approximation. Server integration tests
+exercise the actual HTTP contract, document revision invalidation, and imported
+STEP assembly instance spacing. SDK transport tests check queueing, build revision
+and preserved backend errors. Shared interaction tests cover A/B replacement,
+rapid picks, late replies, failed replacements, units, clearing and orbit drags.
+
+Browser evidence is stored under ignored `artifacts/local/measurement-*.jpg`.
+The native Cadmata browser workflow measured a 10 × 20 × 6 mm box as 6 mm across
+opposite support planes after orbiting, showed 90° for perpendicular faces, and
+cleared the result after translation. This is browser-host qualification; it does
+not claim a separately packaged WebView2 desktop release or an AOT production SDK
+qualification.
+
+### Geometry parity digests
+
+Control sources were taken from baseline `d462d911cbf54f4343da2e732ab58753fcbe9bec`.
+Only the unsupported Volume assertion block was removed from each control.
+The following SHA-256 values match both the control and revised STEP bytes.
+
+| Fixture | Matching STEP SHA-256 |
+| --- | --- |
+| `profile-edgefinish-chimera-fillet.firmament` | `4d4fbc833ae4ffaa1102160fa0823900acb2ee7dc8daa64bec340d41f8e79339` |
+| `profile-edgefinish-chimera-reflex-sphere-compat.firmament` | `7e15adbd0025f6c1bb231f0c076e705d6d45f03039e971502719ea0bcc4b69d9` |
+| `profile-fillet-convex-two-segment-bottom.firmament` | `16b51d19d299994a727dce81ad887bc3dea128f185324a38145330167d02b53d` |
+| `profile-fillet-convex-two-segment-top.firmament` | `dbe3b1336a1ab791abef4b6c6558efd58a3d00c1af95da7049a0f5394b63901f` |
+| `profile-fillet-reflex-two-segment-bottom.firmament` | `cfae62660893a9e2ddb413f1edbaf6b997e8750e6c16d5884ec2b1fb601a3bf6` |
+| `profile-fillet-reflex-two-segment-top.firmament` | `6d2a3425db82f571b559f2db8374841340aab1bcd3726531a4417efb229a89e5` |
+
+### Browser results on the final SDK
+
+- Helios mounting plate: two rapid surface picks produce 27.612275 mm with
+ ΔX 24.619761 mm, ΔY 12.502203 mm and ΔZ 0 mm. Gold witnesses track both picks.
+- Selecting the cylindrical hole wall reports its authored 8 mm diameter.
+- Editing the source clears the measurement and disables new queries while the
+ last valid model remains visible.
+- Industrial ATLAS builds with 24 definitions, 113 total hierarchy occurrences,
+ and no diagnostics. A query distinguishes runtime face 2 on
+ `AtlasIndustrial.UpperArm.ShoulderDrive.Cap` from runtime face 2 on
+ `AtlasIndustrial.UpperArm.ElbowDrive.Cap`: 202.495056 mm between the picked
+ world points (not axis centres). Inch presentation is 7.972246 in.
+- Native Cadmata, Helios and ATLAS screenshots are retained at
+ `artifacts/local/measurement-cadmata.jpg`, `measurement-helios.jpg`, and
+ `measurement-atlas.jpg`. Browser workflows exercised WebGPU; WebGL integration
+ was compiled and covered through component/shared-controller tests, without
+ claiming a separate live fallback-browser qualification.
+
+### Final gate
+
+| Check | Result |
+| --- | --- |
+| Serial Release solution build | Passed; existing nullable/analyzer/WASM warnings remain |
+| Core fast lane, Category != SlowCorpus | 1,087 passed |
+| Final full solution lane, serial | 5,706 passed across 20 test suites; zero failures/skips |
+| Cadmata frontend | 96 tests passed; production build passed |
+| Helios frontend | 101 tests passed; TypeScript and development bundle build passed |
+| Shared Telos | 15 tests passed; build passed |
+| Public SDK transport | 16 tests passed; actual browser WASM package rebuilt and installed locally |
+| Historical fillet geometry | Six byte-identical STEP comparisons; 44 focused assertion/fillet tests passed |
+| Workspace whitespace checks | `git diff --check` passed in Aetheris and HeliosCAD |
+| Host cleanup | Temporary browser tabs, native Cadmata host and Helios Vite host closed; no dotnet/testhost/MSBuild/VBCSCompiler hosts remained |
+
+The full suite was repeated after the browser execution fix. Logs are retained in
+ignored `artifacts/local/measurement-final-build.log`, `measurement-fast.log`,
+`measurement-final-full.log`, and `measurement-fillet.log`. No AOT production SDK
+publish or packaged desktop release was performed. The ordinary Helios production
+build correctly requires that separate AOT package; the qualified bundle here uses
+its supported development/interpreted-WASM lane.
+
+The code-quality pass checked shared geometry authority, closed query modes,
+revision invalidation, disposal, stale asynchronous replies, analytic versus
+approximate labeling, field identity conversion, non-pickable overlays, preserved
+geometry and compatibility of the additive SDK/HTTP contracts. The small product
+bindings adapt their existing session owners; the shared tool contains no parser,
+geometry solver or independent semantic validator.
+
+## Verdict
+
+**Success for the bounded measurement UI pass and assertion cleanup.** The actual
+Cadmata and Helios paths now expose useful BRep-backed measurements with explicit
+interpretation, reference identities, witnesses and stale-state handling. The
+unprovable historical fillet volumes no longer block otherwise valid fixtures,
+and their compiled geometry remains unchanged. General trimmed-face clearance,
+retained Scene/motion measurement contexts and live WebGL/AOT/native desktop release
+qualification remain explicit follow-ups rather than implied capabilities.
diff --git a/docs/public/README.md b/docs/public/README.md
index 29b17b07..1516442e 100644
--- a/docs/public/README.md
+++ b/docs/public/README.md
@@ -11,7 +11,7 @@ Start with [Getting Started](getting-started.md), then use these guides:
- Mechanisms: [Editable V8, prescribed motion and assembly mesh export](firmament/editable-mechanisms.md)
- Showcase: [Difference Engine, real hierarchical CAD and prescribed browser animation](demos/difference-engine-showcase.md), [single-cut carved electric guitar, STEP/USD and Cycles](demos/guitar-surfacing-x0.md)
- Drawings: [Generate PDF/SVG/PPTX from parts and semantic PMI](drawings.md)
-- Inspection: [Cadmata](cadmata/overview.md), [Cadmata PMI](cadmata/pmi.md), and [Three Telos display migration](three-telos.md)
+- Inspection: [Cadmata](cadmata/overview.md), [measurements in Cadmata and Helios](cadmata/measurement.md), [Cadmata PMI](cadmata/pmi.md), and [Three Telos display migration](three-telos.md)
- Reference: [CLI](reference/cli.md), [wireframe SVG previews](reference/wireframe.md), [targets/selectors](reference/targets.md), [diagnostics](reference/diagnostics.md), [supported features](reference/supported-features.md), [known issues](reference/known-issues.md), and [release notes](reference/release-notes.md)
The Windows ZIP begins with the tested [release-bundle walkthrough](release-bundle.md).
diff --git a/docs/public/cadmata/measurement.md b/docs/public/cadmata/measurement.md
new file mode 100644
index 00000000..c0632eb0
--- /dev/null
+++ b/docs/public/cadmata/measurement.md
@@ -0,0 +1,59 @@
+# Measure in Cadmata and Helios
+
+Open **Measure** in the viewport, choose a measurement mode, then click two visible
+faces. The first pick becomes **A**, the second **B**. Further clicks replace B;
+click the A or B button to replace that reference. Orbit between picks to reach
+the other side of a part. Dragging does not select a measurement point.
+
+**New measurement** clears both references. **Esc** closes the tool. **M** toggles
+it while the viewport workspace has keyboard focus. Switch between millimetres
+and inches without recalculating geometry. **Copy result** copies the underlying
+millimetre values, reference identities, witnesses and interpretation as JSON.
+
+| Mode | What the number means | Typical use |
+| --- | --- | --- |
+| Surface points | Straight-line distance between the actual picked points | Check an offset; inspect signed world ΔX/ΔY/ΔZ |
+| Support planes | Perpendicular spacing between parallel infinite planes supporting the selected planar faces | Plate thickness or planar seat spacing |
+| Axes | Shortest separation between infinite axes of cylindrical, conical or toroidal faces | Hole/shaft centre spacing; cylinder diameter is also shown |
+
+Nonparallel support planes show their acute angle instead of inventing a parallel
+spacing. Axis mode also reports the acute angle. Plane/axis witnesses may lie
+outside the finite faces because these modes measure their supporting geometry.
+None of these modes claims general minimum clearance between arbitrary trimmed
+faces or bodies. Pick a cylindrical hole wall for axis spacing, rather than the
+surrounding planar face.
+
+Gold witness crosses and a connecting line show the measured world-space segment.
+The panel retains occurrence and face identities in the A/B button tooltips, so
+two instances of the same part remain distinguishable. Zero distance is allowed;
+it does not prove that the selected faces or bodies coincide.
+
+## Geometry and revisions
+
+The kernel resolves references against the displayed build's BRep, including rigid
+assembly occurrence placements. Analytic surface picks use the kernel's existing
+trim admission policy. An unsupported face produces an explanation. In Surface
+points mode, **Allow approximate display points** explicitly permits a mesh-based
+pick; the entire result is then labeled **Approximate display**. Such results
+are unsuitable for checking manufacturing tolerances. Display precision is not
+an accuracy or tolerance certification.
+
+Measurements are read-only queries. They do not author Firmament dimensions, PMI,
+constraints, or assertions. A source edit, rebuild, document transform, or loading
+transition clears or disables the result. Late replies from an older context
+are discarded. Helios retains its last valid model after a failed build, but
+measurement stays disabled until the current source builds successfully.
+
+This pass supports Helios Parts and static Assemblies, and Cadmata document bodies
+and imported STEP assemblies, through both Telos and WebGL rendering. Return a
+Helios motion clip to its built pose before measuring. Scene/mesh-only builds and
+Cadmata's stateless Firmament gallery previews do not yet retain a BRep query
+context; the tool explains that boundary. Import the preview's STEP into Cadmata
+when a retained document measurement context is needed.
+
+The browser SDK exposes `ModelSession.measure(request)`. Cadmata exposes
+`POST /api/v1/documents/{documentId}/measure` with `{ revision, measurement }`;
+use the document summary's revision. Both adapters call the same geometry query
+owner and preserve named errors such as `measurement-stale-revision`,
+`measurement-surface-unsupported`, `measurement-plane-required`, and
+`measurement-axis-required`.
diff --git a/docs/public/cadmata/overview.md b/docs/public/cadmata/overview.md
index b9e12dd6..ffbc0092 100644
--- a/docs/public/cadmata/overview.md
+++ b/docs/public/cadmata/overview.md
@@ -6,4 +6,9 @@ Use `aetheris view model.firmament` or `aetheris view part.step` from the qualif
Cadmata opens AP242 STEP assemblies as a product tree with shared part definitions and placed occurrences. The STEP viewer's import control is the normal entry point; internal fixture endpoints are reserved for automated qualification and are not part of the viewer controls.
+Use the viewport's **Measure** tool for picked-point distance, parallel support-plane
+spacing, and analytic axis spacing. See [measurements in Cadmata and Helios](measurement.md)
+for reference replacement, world-coordinate deltas, units, approximation labels and
+the supported geometry boundary.
+
Preview 3 qualification is Windows x64. See [PMI presentation](pmi.md) and the [support matrix](../reference/supported-features.md).
diff --git a/fixtures/Regression/Assertions/README.md b/fixtures/Regression/Assertions/README.md
index 83c590fd..61c3ed4f 100644
--- a/fixtures/Regression/Assertions/README.md
+++ b/fixtures/Regression/Assertions/README.md
@@ -11,8 +11,9 @@ The tests mutate expected values, fields and topology to prove rejection without
changing these witnesses. `measure` explicitly builds without evaluating declared
assertions and reports that level; it is not a successful validation substitute.
-Six historical curved-fillet volume specimens are preserved in
-`../CanonicalGeometry/`. Their unsupported volume assertions now reject normal
-compilation. Geometry qualification uses explicit measurement and an assertion-free
-control, preserving deterministic STEP and topology checks. See
-`docs/development/FIRMAMENT-ASSERTIONS-2026-10-19.md` for the full classification.
+Six historical curved-fillet specimens in `../CanonicalGeometry/` now use
+`Assert Topology Body { shells: 1 }` in place of unprovable historical volume
+assertions. They compile normally and retain their existing deterministic STEP,
+topology and geometry regression checks. A separate negative test appends an
+unprovable volume assertion and still requires `measurement-unavailable` rejection.
+See `docs/development/FIRMAMENT-ASSERTIONS-2026-10-19.md` for the earlier classification.
diff --git a/fixtures/Regression/CanonicalGeometry/profile-edgefinish-chimera-fillet.firmament b/fixtures/Regression/CanonicalGeometry/profile-edgefinish-chimera-fillet.firmament
index 26d5ec42..564af1de 100644
--- a/fixtures/Regression/CanonicalGeometry/profile-edgefinish-chimera-fillet.firmament
+++ b/fixtures/Regression/CanonicalGeometry/profile-edgefinish-chimera-fillet.firmament
@@ -32,9 +32,5 @@ Model ProfileEdgeFinishChimeraFillet {
Selection ReflexMediumStation { Target: TopBoundary Source: Chimera.ProfileSegments([MediumDrop, ReflexMediumArc, BetweenMediumLarge]) Require: ConnectedChain }
Selection ReflexLargeStation { Target: TopBoundary Source: Chimera.ProfileSegments([BetweenMediumLarge, ReflexLargeArc, LargeRise]) Require: ConnectedChain }
Modify Body { EdgeFinish ChimeraTopFillet { Target: Chimera.Outer On: Top Kind: Fillet Radius: 4mm } }
- Assert Volume Body {
- Expected: 913725.7396023329mm^3
- Tolerance: 41239mm^3
- Note: "Independent adaptive source-section integration; tolerance is the current curved-trim verifier's certified conservative error envelope."
- }
+ Assert Topology Body { shells: 1 }
}
diff --git a/fixtures/Regression/CanonicalGeometry/profile-edgefinish-chimera-reflex-sphere-compat.firmament b/fixtures/Regression/CanonicalGeometry/profile-edgefinish-chimera-reflex-sphere-compat.firmament
index 2039aa6e..affdc4a2 100644
--- a/fixtures/Regression/CanonicalGeometry/profile-edgefinish-chimera-reflex-sphere-compat.firmament
+++ b/fixtures/Regression/CanonicalGeometry/profile-edgefinish-chimera-reflex-sphere-compat.firmament
@@ -32,9 +32,5 @@ Model ProfileEdgeFinishChimeraReflexSphereCompatibility {
Selection ReflexMediumStation { Target: TopBoundary Source: Chimera.ProfileSegments([MediumDrop, ReflexMediumArc, BetweenMediumLarge]) Require: ConnectedChain }
Selection ReflexLargeStation { Target: TopBoundary Source: Chimera.ProfileSegments([BetweenMediumLarge, ReflexLargeArc, LargeRise]) Require: ConnectedChain }
Modify Body { EdgeFinish ChimeraTopFilletCompatibility { Target: Chimera.Outer On: Top Kind: Fillet Radius: 4mm ReflexJunction: SphereSeamCompatibility } }
- Assert Volume Body {
- Expected: 913733.5792146825mm^3
- Tolerance: 41263mm^3
- Note: "Independent adaptive source-section integration; tolerance is the current curved-trim verifier's certified conservative error envelope."
- }
+ Assert Topology Body { shells: 1 }
}
diff --git a/fixtures/Regression/CanonicalGeometry/profile-fillet-convex-two-segment-bottom.firmament b/fixtures/Regression/CanonicalGeometry/profile-fillet-convex-two-segment-bottom.firmament
index 27c34eb2..df4399cd 100644
--- a/fixtures/Regression/CanonicalGeometry/profile-fillet-convex-two-segment-bottom.firmament
+++ b/fixtures/Regression/CanonicalGeometry/profile-fillet-convex-two-segment-bottom.firmament
@@ -16,9 +16,5 @@ Profile Bracket Using RectangleLayout { Loop Outer {
Struct Body { Extrude Bracket { Profile: Bracket; From: 0mm; To: 8mm } }
Selection CornerPair { Source: Bracket.Outer.[South, East] Require: ConnectedChain }
Modify Body { EdgeFinish RoundedCorner { Target: CornerPair On: Bottom Kind: Fillet Radius: 2mm EndClearance: 3mm } }
-Assert Volume Body {
- Expected: 1570.7317878719023mm^3
- Tolerance: 0.5mm^3
- Note: "Bottom mirror of two straight Profile rolls joined by one convex spherical fillet junction"
-}
+Assert Topology Body { shells: 1 }
}
diff --git a/fixtures/Regression/CanonicalGeometry/profile-fillet-convex-two-segment-top.firmament b/fixtures/Regression/CanonicalGeometry/profile-fillet-convex-two-segment-top.firmament
index 5c0260e8..af39ee60 100644
--- a/fixtures/Regression/CanonicalGeometry/profile-fillet-convex-two-segment-top.firmament
+++ b/fixtures/Regression/CanonicalGeometry/profile-fillet-convex-two-segment-top.firmament
@@ -16,9 +16,5 @@ Profile Bracket Using RectangleLayout { Loop Outer {
Struct Body { Extrude Bracket { Profile: Bracket; From: 0mm; To: 8mm } }
Selection CornerPair { Source: Bracket.Outer.[South, East] Require: ConnectedChain }
Modify Body { EdgeFinish RoundedCorner { Target: CornerPair On: Top Kind: Fillet Radius: 2mm EndClearance: 3mm } }
-Assert Volume Body {
- Expected: 1570.7317878719023mm^3
- Tolerance: 0.5mm^3
- Note: "Two straight Profile rolls joined by one convex spherical fillet junction"
-}
+Assert Topology Body { shells: 1 }
}
diff --git a/fixtures/Regression/CanonicalGeometry/profile-fillet-reflex-two-segment-bottom.firmament b/fixtures/Regression/CanonicalGeometry/profile-fillet-reflex-two-segment-bottom.firmament
index 51a8fee6..8cfc711d 100644
--- a/fixtures/Regression/CanonicalGeometry/profile-fillet-reflex-two-segment-bottom.firmament
+++ b/fixtures/Regression/CanonicalGeometry/profile-fillet-reflex-two-segment-bottom.firmament
@@ -14,9 +14,5 @@ Model ProfileFilletReflexTwoSegmentBottom {
Struct Body { Extrude Bracket { Profile: Bracket; From: 0mm; To: 8mm } }
Selection ReflexNotch { Source: Bracket.Outer.[Inner, Upright] Require: ConnectedChain }
Modify Body { EdgeFinish ReflexRound { Target: ReflexNotch On: Bottom Kind: Fillet Radius: 2mm EndClearance: 3mm } }
- Assert Volume Body {
- Expected: 5595.374298764066mm^3
- Tolerance: 0.5mm^3
- Note: "Horn-torus quadrant regression literal"
- }
+ Assert Topology Body { shells: 1 }
}
diff --git a/fixtures/Regression/CanonicalGeometry/profile-fillet-reflex-two-segment-top.firmament b/fixtures/Regression/CanonicalGeometry/profile-fillet-reflex-two-segment-top.firmament
index b6c32ddf..eb68eb2a 100644
--- a/fixtures/Regression/CanonicalGeometry/profile-fillet-reflex-two-segment-top.firmament
+++ b/fixtures/Regression/CanonicalGeometry/profile-fillet-reflex-two-segment-top.firmament
@@ -14,9 +14,5 @@ Model ProfileFilletReflexTwoSegmentTop {
Struct Body { Extrude Bracket { Profile: Bracket; From: 0mm; To: 8mm } }
Selection ReflexNotch { Source: Bracket.Outer.[Inner, Upright] Require: ConnectedChain }
Modify Body { EdgeFinish ReflexRound { Target: ReflexNotch On: Top Kind: Fillet Radius: 2mm EndClearance: 3mm } }
- Assert Volume Body {
- Expected: 5595.374298764066mm^3
- Tolerance: 0.5mm^3
- Note: "Horn-torus quadrant regression literal"
- }
+ Assert Topology Body { shells: 1 }
}