Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Preserve and rebind imported STEP 242 PMI

Yuechen Li00889982868e
diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242PmiTransferTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242PmiTransferTests.cs
new file mode 100644
index 00000000..d7228e18
--- /dev/null
+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242PmiTransferTests.cs
@@ -0,0 +1,233 @@
+using Aetheris.Kernel.Core.Step242;
+using System.Globalization;
+using System.Text.RegularExpressions;
+using Aetheris.Kernel.Core.Brep;
+
+namespace Aetheris.Kernel.Core.Tests.Step242;
+
+public sealed class Step242PmiTransferTests
+{
+ public static IEnumerable<object[]> NistFiles() => Directory.EnumerateFiles(Step242Corpus.Path("testdata/step242/nist"), "*.stp", SearchOption.AllDirectories)
+ .Where(path => !path.EndsWith("-tg.stp", StringComparison.Ordinal)).Order()
+ .Select(path => new object[] { "testdata/step242/nist/" + System.IO.Path.GetRelativePath(Step242Corpus.Path("testdata/step242/nist"), path).Replace('\\', '/') });
+
+ [Theory, MemberData(nameof(NistFiles)), Trait("Category", "SlowCorpus")]
+ public void NistSemanticGraphPreservesRecordsUnitsAndTopologyAssociations(string path)
+ {
+ var imported = Step242Corpus.Import(path);
+ Assert.True(imported.IsSuccess, string.Join(";", imported.Diagnostics.Select(d => d.Message)));
+ var transfer = Step242PmiTransfer.Read(Step242Corpus.Text(path), imported.Value);
+ Assert.True(transfer.IsSuccess, string.Join(";", transfer.Diagnostics.Select(d => d.Message)));
+ var output = Step242Exporter.ExportBody(imported.Value, new Step242ExportOptions { ImportedPmi = transfer.Value });
+ Assert.True(output.IsSuccess, path + ": " + string.Join(";", output.Diagnostics.Select(d => d.Message)));
+ var baseline = Step242Exporter.ExportBody(imported.Value).Value;
+ Assert.StartsWith(baseline[..baseline.LastIndexOf("ENDSEC;", StringComparison.Ordinal)], output.Value);
+ var parsed = Step242SubsetParser.Parse(output.Value);
+ Assert.True(parsed.IsSuccess);
+ var ids = parsed.Value.Entities.Select(e => e.Id).ToHashSet();
+ Assert.All(parsed.Value.Entities.SelectMany(e => Step242PmiTransfer.References(e.Instance)), id => Assert.Contains(id, ids));
+ var before = Step242SubsetParser.Parse(Step242Corpus.Text(path)).Value;
+ Assert.Equal(before.Entities.Count(Step242PmiTransfer.IsSemanticRoot), parsed.Value.Entities.Count(Step242PmiTransfer.IsSemanticRoot));
+ Assert.DoesNotContain(parsed.Value.Entities, e => Step242SubsetDecoder.TryGetConstructor(e.Instance, "CONVERSION_BASED_UNIT") is { } c
+ && c.Arguments.FirstOrDefault() is Step242StringValue s && s.Value.Contains("inch", StringComparison.OrdinalIgnoreCase));
+ var again = Step242Importer.ImportBody(output.Value);
+ Assert.True(again.IsSuccess, string.Join(";", again.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(imported.Value.Topology.Faces.Count(), again.Value.Topology.Faces.Count());
+ Assert.Equal(imported.Value.Topology.Edges.Count(), again.Value.Topology.Edges.Count());
+ Assert.Equal(imported.Value.Geometry.Surfaces.Select(s => s.Value.Kind).Order(), again.Value.Geometry.Surfaces.Select(s => s.Value.Kind).Order());
+ var sourcePmi = Step242SemanticPmiInspector.Inspect(Step242Corpus.Text(path));
+ var roundtripPmi = Step242SemanticPmiInspector.Inspect(output.Value);
+ AssertEdgeUsages(sourcePmi.Items, imported.Value, roundtripPmi.Items, again.Value);
+ Assert.Equal(sourcePmi.DatumCount, roundtripPmi.DatumCount); Assert.Equal(sourcePmi.DimensionCount, roundtripPmi.DimensionCount);
+ Assert.Equal(sourcePmi.GeometricToleranceCount, roundtripPmi.GeometricToleranceCount);
+ var expectedTargets = AssociationKeys(sourcePmi.Items, imported.Value);
+ var actualTargets = AssociationKeys(roundtripPmi.Items, again.Value);
+ var expectedGeometry = GeometryKeys(sourcePmi.Items, imported.Value, before);
+ var actualGeometry = GeometryKeys(roundtripPmi.Items, again.Value, parsed.Value);
+ var expected = sourcePmi.Items.Select(item => Semantics(item, expectedTargets, expectedGeometry)).ToArray();
+ var actual = roundtripPmi.Items.Select(item => Semantics(item, actualTargets, actualGeometry)).ToArray();
+ Assert.Equal(expected.Length, actual.Length);
+ var differences = expected.Zip(actual).Select((pair, index) => (pair, index)).Where(item => item.pair.First != item.pair.Second).ToArray();
+ Assert.True(differences.Length == 0, path + "\n" + string.Join("\n", differences.Take(3).Select(item => $"{item.index}: expected {item.pair.First}\nactual {item.pair.Second}")));
+ }
+ private static Dictionary<int, string> AssociationKeys(IReadOnlyList<Step242SemanticPmiInspectionItem> items, BrepBody body)
+ {
+ var keys = body.Bindings.FaceBindings.Where(binding => binding.SourceStepEntityId.HasValue)
+ .ToDictionary(binding => binding.SourceStepEntityId!.Value, binding => "body:" + binding.FaceId.Value);
+ // Edge-adjacency presentation can include auxiliary surfaces outside the solid;
+ // direct source usage identity is qualified separately below.
+ foreach (var id in items.SelectMany(item => item.GeometricFaceEntityIds).Distinct().Where(id => !keys.ContainsKey(id)))
+ keys.Add(id, "auxiliary");
+ return keys;
+ }
+ private static Dictionary<int, string> GeometryKeys(IReadOnlyList<Step242SemanticPmiInspectionItem> items, BrepBody body, Step242ParsedDocument document)
+ {
+ var geometry = body.Bindings.FaceBindings.Where(b => b.SourceStepEntityId.HasValue).ToDictionary(b => b.SourceStepEntityId!.Value, b => "face:" + b.FaceId.Value);
+ foreach (var edge in body.Bindings.EdgeBindings.Where(b => b.SourceStepEntityId.HasValue)) geometry.Add(edge.SourceStepEntityId!.Value, EdgeKey(body, edge));
+ foreach (var solid in document.Entities.Where(e => e.Name is "MANIFOLD_SOLID_BREP" or "BREP_WITH_VOIDS")) geometry.Add(solid.Id, "solid");
+ var auxiliary = items.SelectMany(item => item.GeometricItemEntityIds).Distinct().Where(id => !geometry.ContainsKey(id)).Order().ToArray();
+ for (var i = 0; i < auxiliary.Length; i++) geometry.Add(auxiliary[i], "auxiliary:" + i);
+ return geometry;
+ }
+ private static string EdgeKey(BrepBody body, EdgeGeometryBinding binding)
+ {
+ // Import allocates edge ids in traversal order, which can change after export.
+ // Qualify the associated physical edge rather than its temporary allocation number.
+ var edge = body.Topology.GetEdge(binding.EdgeId);
+ Assert.True(body.TryGetEdgeCurveGeometry(edge.Id, out var curve));
+ var adjacent = body.Topology.Faces.Where(face => face.LoopIds.SelectMany(id => body.Topology.GetLoop(id).CoedgeIds)
+ .Any(id => body.Topology.GetCoedge(id).EdgeId == edge.Id)).Select(face => face.Id.Value).Order();
+ return "edge:" + curve!.Kind + ":" + string.Join(",", adjacent);
+ }
+ private static void AssertEdgeUsages(IReadOnlyList<Step242SemanticPmiInspectionItem> before, BrepBody original,
+ IReadOnlyList<Step242SemanticPmiInspectionItem> after, BrepBody emitted)
+ {
+ static Dictionary<int, (string Key, Aetheris.Kernel.Core.Math.Point3D Start, Aetheris.Kernel.Core.Math.Point3D End, Aetheris.Kernel.Core.Math.Point3D? Mid)> Witnesses(BrepBody body)
+ => body.Bindings.EdgeBindings.Where(binding => binding.SourceStepEntityId.HasValue).ToDictionary(binding => binding.SourceStepEntityId!.Value, binding =>
+ {
+ var edge = body.Topology.GetEdge(binding.EdgeId);
+ Assert.True(body.TryGetVertexPoint(edge.StartVertexId, out var start));
+ Assert.True(body.TryGetVertexPoint(edge.EndVertexId, out var end));
+ Assert.True(body.TryGetEdgeCurveGeometry(edge.Id, out var curve));
+ var mid = binding.TrimInterval is { } interval ? BrepPcurveValidator.Evaluate(curve!, (interval.Start + interval.End) / 2) : null;
+ return (EdgeKey(body, binding), start, end, mid);
+ });
+ var source = Witnesses(original); var output = Witnesses(emitted);
+ Assert.Equal(before.Count, after.Count);
+ foreach (var pair in before.Zip(after))
+ {
+ var unmatched = pair.Second.GeometricItemEntityIds.Where(output.ContainsKey).Select(id => output[id]).ToList();
+ foreach (var witness in pair.First.GeometricItemEntityIds.Where(source.ContainsKey).Select(id => source[id]))
+ {
+ var index = unmatched.FindIndex(candidate => candidate.Key == witness.Key
+ && (((candidate.Start - witness.Start).Length < 1e-7 && (candidate.End - witness.End).Length < 1e-7)
+ || ((candidate.Start - witness.End).Length < 1e-7 && (candidate.End - witness.Start).Length < 1e-7))
+ && (candidate.Mid.HasValue == witness.Mid.HasValue)
+ && (!candidate.Mid.HasValue || (candidate.Mid.Value - witness.Mid!.Value).Length < 1e-7));
+ Assert.True(index >= 0, $"{pair.First.Name}: direct edge usage lost its physical witness.");
+ unmatched.RemoveAt(index);
+ }
+ Assert.Empty(unmatched);
+ }
+ }
+ private static string Semantics(Step242SemanticPmiInspectionItem item, IReadOnlyDictionary<int, string> targets, IReadOnlyDictionary<int, string> geometry) => string.Join("|", item.Kind, item.Value?.ToString("R", CultureInfo.InvariantCulture), item.ValueUnit,
+ item.TolerancePlus?.ToString("R", CultureInfo.InvariantCulture), item.ToleranceMinus?.ToString("R", CultureInfo.InvariantCulture),
+ string.Join(",", item.DatumReferences), string.Join(",", item.Modifiers), string.Join(",", item.ZoneForms),
+ string.Join(";", item.DatumReferenceFrames.Select(frame => string.Join(",", frame.Labels) + ":" + string.Join(",", frame.Modifiers))),
+ // Exact source correspondence, rather than a face-count check that could miss a swapped target.
+ // Only material-face adjacency belongs to the geometry witness. Unreferenced auxiliary
+ // edge neighbours need not be copied; direct auxiliary usage identity is checked below.
+ string.Join(",", item.GeometricFaceEntityIds.Select(id => targets[id]).Where(key => key != "auxiliary").Order(StringComparer.Ordinal)),
+ string.Join(",", item.GeometricItemEntityIds.Select(id => geometry[id]).Order(StringComparer.Ordinal)));
+
+ private const string Ftc11 = "testdata/step242/nist/FTC/nist_ftc_11_asme1_ap242-e2.stp";
+ [Theory]
+ [InlineData(2, 645.16)]
+ [InlineData(3, 16387.064)]
+ public void CompoundLengthUnitsRespectTheirDimensionalExponent(int exponent, double expected)
+ {
+ var source = InchTolerance(.001);
+ var document = Step242SubsetParser.Parse(source).Value;
+ var inches = document.Entities.Single(e => Step242SubsetDecoder.TryGetConstructor(e.Instance, "CONVERSION_BASED_UNIT") is { } unit
+ && unit.Arguments.FirstOrDefault() is Step242StringValue { Value: "inch" }).Id;
+ var fresh = document.Entities.Max(e => e.Id) + 1;
+ source = source.Insert(source.LastIndexOf("ENDSEC;", StringComparison.Ordinal),
+ $"#{fresh}=DERIVED_UNIT_ELEMENT(#{inches},{exponent});\n#{fresh + 1}=DERIVED_UNIT((#{fresh}));\n");
+ var entities = Step242SubsetParser.Parse(source).Value.Entities.ToDictionary(e => e.Id);
+ Assert.True(Step242LengthUnitNormalizer.TryResolvePmiScale(entities, fresh + 1, [], out var scale));
+ Assert.Equal(expected, scale, 9);
+ }
+ [Theory]
+ [InlineData(.001, .0254)] [InlineData(.000001, .0000254)] [InlineData(1e-12, 2.54e-11)]
+ public void MixedUnitNistToleranceConvertsIndependentlyWithoutAnAuthoringGrid(double inches, double expected)
+ {
+ var source = InchTolerance(inches);
+ // The semantic-unit specimen differs from the corpus source, so it deliberately needs its own import receipt.
+ var original = Step242Importer.ImportBody(source).Value;
+ var before = Assert.Single(Step242SemanticPmiInspector.Inspect(source).Items, i => i.Kind == "Flatness");
+ Assert.InRange(System.Math.Abs(before.Value!.Value - expected), 0, System.Math.Abs(expected) * 1e-14);
+ var transfer = Step242PmiTransfer.Read(source, original); Assert.True(transfer.IsSuccess, string.Join(";", transfer.Diagnostics.Select(d => d.Message)));
+ var output = Step242Exporter.ExportBody(original, new Step242ExportOptions { ImportedPmi = transfer.Value });
+ Assert.True(output.IsSuccess, string.Join(";", output.Diagnostics.Select(d => d.Message)));
+ var after = Assert.Single(Step242SemanticPmiInspector.Inspect(output.Value).Items, i => i.Kind == "Flatness");
+ Assert.True(after.Value > 0); Assert.Equal(before.Value, after.Value); Assert.Equal("mm", after.ValueUnit);
+ Assert.Equal(before.Modifiers, after.Modifiers); Assert.Equal(before.GeometricFaceEntityIds.Count, after.GeometricFaceEntityIds.Count);
+ var body = Step242Importer.ImportBody(output.Value); Assert.True(body.IsSuccess);
+ var baseline = Step242Exporter.ExportBody(original).Value;
+ Assert.StartsWith(baseline[..baseline.LastIndexOf("ENDSEC;", StringComparison.Ordinal)], output.Value);
+ }
+ [Fact]
+ public void TransferRejectsChangedBodyAndUnresolvableUnit()
+ {
+ var source = InchTolerance(.001); var body = Step242Importer.ImportBody(source).Value;
+ var transfer = Step242PmiTransfer.Read(source, body).Value;
+ var changed = body.Clone(); changed.Topology.AddVertex(new(new(999999)));
+ var rejected = Step242Exporter.ExportBody(changed, new Step242ExportOptions { ImportedPmi = transfer });
+ Assert.False(rejected.IsSuccess); Assert.Contains(rejected.Diagnostics, d => d.Message.Contains("pmi-source-body-changed"));
+ source = source.Replace("LENGTH_MEASURE(25.4)", "LENGTH_MEASURE(-25.4)", StringComparison.Ordinal);
+ body = Step242Importer.ImportBody(source).Value;
+ transfer = Step242PmiTransfer.Read(source, body).Value;
+ rejected = Step242Exporter.ExportBody(body, new Step242ExportOptions { ImportedPmi = transfer });
+ Assert.False(rejected.IsSuccess); Assert.Contains(rejected.Diagnostics, d => d.Message.Contains("Cannot resolve length unit"));
+ }
+ [Fact]
+ public void SourceReceiptAndClosedSemanticOwnershipPreventAccidentalPartialTransfer()
+ {
+ var source = InchTolerance(.001);
+ var wrongBody = Step242Corpus.Body(Ftc11);
+ var mismatch = Step242PmiTransfer.Read(source, wrongBody);
+ Assert.False(mismatch.IsSuccess); Assert.Contains(mismatch.Diagnostics, d => d.Message.Contains("pmi-source-body-mismatch"));
+ var document = Step242SubsetParser.Parse(source).Value;
+ var control = document.Entities.First(e => Step242SubsetDecoder.TryGetConstructor(e.Instance, "GEOMETRIC_TOLERANCE") is not null);
+ var fresh = document.Entities.Max(e => e.Id) + 1;
+ source = source.Insert(source.LastIndexOf("ENDSEC;", StringComparison.Ordinal), $"#{fresh}=UNQUALIFIED_PMI_OWNER(#{control.Id});\n");
+ var body = Step242Importer.ImportBody(source).Value;
+ var rejected = Step242PmiTransfer.Read(source, body);
+ Assert.False(rejected.IsSuccess); Assert.Contains(rejected.Diagnostics, d => d.Message.Contains("UNQUALIFIED_PMI_OWNER"));
+ }
+ [Fact]
+ public void InchGeometryAndItsControlBothExportInMillimetres()
+ {
+ var box = BrepPrimitives.CreateBox(2, 3, 4).Value;
+ var authored = new Step242SemanticPmiGeometricTolerance("Body.Seat", "Seat", "Flatness", .001, []) { GeometricFaceIds = [box.Topology.Faces.First().Id.Value] };
+ var source = Step242Exporter.ExportBody(box, [authored]).Value;
+ var document = Step242SubsetParser.Parse(source).Value;
+ var unit = document.Entities.Single(e => Step242SubsetDecoder.TryGetConstructor(e.Instance, "LENGTH_UNIT") is not null).Id;
+ var fresh = document.Entities.Max(e => e.Id) + 1;
+ source = Regex.Replace(source, $@"#{unit}\s*=.*?;", $"#{unit}=(CONVERSION_BASED_UNIT('inch',#{fresh})LENGTH_UNIT()NAMED_UNIT(*));", RegexOptions.Singleline);
+ source = source.Insert(source.LastIndexOf("ENDSEC;", StringComparison.Ordinal), $"#{fresh}=LENGTH_MEASURE_WITH_UNIT(LENGTH_MEASURE(25.4),#{fresh + 1});\n#{fresh + 1}=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.));\n");
+ var imported = Step242Importer.ImportBody(source); Assert.True(imported.IsSuccess);
+ var transfer = Step242PmiTransfer.Read(source, imported.Value); Assert.True(transfer.IsSuccess);
+ var output = Step242Exporter.ExportBody(imported.Value, new Step242ExportOptions { ImportedPmi = transfer.Value }); Assert.True(output.IsSuccess);
+ var body = Step242Importer.ImportBody(output.Value).Value;
+ var points = body.Topology.Vertices.Select(v => { Assert.True(body.TryGetVertexPoint(v.Id, out var point)); return point; }).ToArray();
+ Assert.Equal(50.8, points.Max(p => p.X) - points.Min(p => p.X));
+ Assert.Equal(76.2, points.Max(p => p.Y) - points.Min(p => p.Y), 10);
+ Assert.Equal(101.6, points.Max(p => p.Z) - points.Min(p => p.Z));
+ var control = Assert.Single(Step242SemanticPmiInspector.Inspect(output.Value).Items, i => i.Kind == "Flatness");
+ Assert.Equal(.0254, control.Value); Assert.Equal("mm", control.ValueUnit); Assert.Single(control.GeometricFaceEntityIds);
+ }
+ [Fact]
+ public void NistFtc11HasReadableControlsAndDatumPrecedenceIndependentOfVendorLabels()
+ {
+ var inspection = Step242SemanticPmiInspector.Inspect(Step242Corpus.Text(Ftc11));
+ Assert.Equal(4, inspection.GeometricToleranceCount); Assert.Equal(6, inspection.DimensionCount); Assert.Equal(2, inspection.DatumCount);
+ var profile = Assert.Single(inspection.Items, i => i.Kind == "SurfaceProfile");
+ Assert.Equal(new[] { "A", "B" }, profile.DatumReferences); Assert.Contains("FREE_STATE", profile.Modifiers);
+ Assert.NotEmpty(profile.GeometricFaceEntityIds);
+ }
+ private static string InchTolerance(double inches)
+ {
+ var source = Step242Corpus.Text(Ftc11); var document = Step242SubsetParser.Parse(source).Value;
+ var control = document.Entities.Single(e => Step242SubsetDecoder.TryGetConstructor(e.Instance, "FLATNESS_TOLERANCE") is not null);
+ var magnitude = (Step242EntityReference)Step242SubsetDecoder.TryGetConstructor(control.Instance, "GEOMETRIC_TOLERANCE")!.Arguments[2];
+ var mm = document.Entities.Single(e => Step242SubsetDecoder.TryGetConstructor(e.Instance, "LENGTH_UNIT") is not null && Step242SubsetDecoder.TryGetConstructor(e.Instance, "SI_UNIT")?.Arguments.FirstOrDefault() is Step242EnumValue { Value: "MILLI" }).Id;
+ var fresh = document.Entities.Max(e => e.Id) + 1;
+ var original = Regex.Match(source, $@"#{control.Id}\s*=.*?;", RegexOptions.Singleline).Value;
+ source = source.Replace(original, Regex.Replace(original, $@"#{magnitude.TargetId}\b", "#" + fresh), StringComparison.Ordinal);
+ var declarations = $"#{fresh}=LENGTH_MEASURE_WITH_UNIT(LENGTH_MEASURE({inches.ToString("R", CultureInfo.InvariantCulture)}),#{fresh + 1});\n"
+ + $"#{fresh + 1}=(CONVERSION_BASED_UNIT('inch',#{fresh + 2})LENGTH_UNIT()NAMED_UNIT(*));\n"
+ + $"#{fresh + 2}=LENGTH_MEASURE_WITH_UNIT(LENGTH_MEASURE(25.4),#{mm});\n";
+ return source.Insert(source.LastIndexOf("ENDSEC;", StringComparison.Ordinal), declarations);
+ }
+}
diff --git a/Aetheris.Kernel.Core/Brep/BrepBindings.cs b/Aetheris.Kernel.Core/Brep/BrepBindings.cs
index 129c85de..c980b00b 100644
--- a/Aetheris.Kernel.Core/Brep/BrepBindings.cs
+++ b/Aetheris.Kernel.Core/Brep/BrepBindings.cs
@@ -8,7 +8,10 @@ public readonly record struct EdgeGeometryBinding(
EdgeId EdgeId,
CurveGeometryId CurveGeometryId,
ParameterInterval? TrimInterval = null,
- bool OrientedEdgeSense = true);
+ bool OrientedEdgeSense = true)
+{
+ public int? SourceStepEntityId { get; init; }
+}
/// <summary>
/// Canonical face orientation after topology/material-side resolution. This is
diff --git a/Aetheris.Kernel.Core/Brep/BrepBody.cs b/Aetheris.Kernel.Core/Brep/BrepBody.cs
index a99eddbc..3a8c66d1 100644
--- a/Aetheris.Kernel.Core/Brep/BrepBody.cs
+++ b/Aetheris.Kernel.Core/Brep/BrepBody.cs
@@ -56,6 +56,8 @@ public sealed class BrepBody
/// <summary>Source BRep evidence; display completeness is assessed separately.</summary>
public Aetheris.Kernel.Core.Import.BrepImportQualificationReport? ImportQualification { get; internal set; }
+ /// <summary>Exact source receipt for rebinding imported annotations. Not a geometry identity.</summary>
+ public string? SourceStepTextHash { get; internal set; }
/// <summary>
/// An independent body: its topology, geometry and binding stores are copies, so adding to them
@@ -67,6 +69,7 @@ public sealed class BrepBody
{
PcurveRecoveryReport = PcurveRecoveryReport,
ImportQualification = ImportQualification,
+ SourceStepTextHash = SourceStepTextHash,
};
public bool TryGetVertexPoint(VertexId vertexId, out Point3D point) => _vertexPoints.TryGetValue(vertexId, out point);
diff --git a/Aetheris.Kernel.Core/Step242/Step242ExportOptions.cs b/Aetheris.Kernel.Core/Step242/Step242ExportOptions.cs
index 6fc1b37b..453a1695 100644
--- a/Aetheris.Kernel.Core/Step242/Step242ExportOptions.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242ExportOptions.cs
@@ -19,6 +19,8 @@ public enum BrepExportPreflightPolicy
public sealed class Step242ExportOptions
{
+ /// <summary>Source semantic PMI rebound to an unchanged imported body. Graphical glyphs are regenerated separately.</summary>
+ public Step242PmiTransfer? ImportedPmi { get; init; }
/// <summary>Declared distance accuracy of retained imported geometry, in mm.
/// Null preserves the historical export. This is not a machining tolerance.</summary>
public double? DistanceAccuracyMillimetres { get; init; }
diff --git a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs b/Aetheris.Kernel.Core/Step242/Step242Exporter.cs
index 096041fa..9a337b62 100644
--- a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242Exporter.cs
@@ -20,6 +20,17 @@ public static class Step242Exporter
Step242ExportOptions? options = null)
{
options ??= new Step242ExportOptions();
+ var declaredDatums = (semanticPmi ?? []).OfType<Step242SemanticPmiDatum>().Select(d => d.Label).ToHashSet(StringComparer.OrdinalIgnoreCase);
+ if ((options.ImportedPmi?.DatumLabels ?? []).Any(declaredDatums.Contains))
+ return Failure("pmi-source-datum-conflict: Authored datum labels must not shadow retained source datums.", "Step242.Pmi");
+ declaredDatums.UnionWith(options.ImportedPmi?.DatumLabels ?? []);
+ foreach (var control in (semanticPmi ?? []).OfType<Step242SemanticPmiGeometricTolerance>())
+ {
+ if (Step242GeometricToleranceKinds.Validate(control, declaredDatums) is { } problem)
+ return Failure($"pmi-geometric-tolerance-invalid: '{control.Name}': {problem}", "Step242.Pmi");
+ if (control.GeometricFaceIds.Count == 0 || control.GeometricFaceIds.Any(id => !body.Topology.Faces.Any(face => face.Id.Value == id)))
+ return Failure($"pmi-geometric-target-unresolved: '{control.Name}' requires proved face associations.", "Step242.Pmi");
+ }
IReadOnlyList<KernelDiagnostic> normalizationDiagnostics = [];
if (options.BrepExportPreflightPolicy == BrepExportPreflightPolicy.TrustedProductionRoute
&& options.ImportedRecoveryToleranceMillimetres is { } normalizationBudget
@@ -174,11 +185,19 @@ public static class Step242Exporter
var repContextId = writer.AddRawEntity($"(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNIT_ASSIGNED_CONTEXT(({lengthUnitId},{planeAngleUnitId},{solidAngleUnitId})){uncertaintyContext}REPRESENTATION_CONTEXT('3','3D'))");
var shapeRepresentationId = writer.AddEntity("SHAPE_REPRESENTATION", Step242TextWriter.String(options.ProductName), Step242TextWriter.List(brepId), Step242TextWriter.Ref(repContextId));
writer.AddEntity("SHAPE_DEFINITION_REPRESENTATION", Step242TextWriter.Ref(shapeId), Step242TextWriter.Ref(shapeRepresentationId));
- EmitSemanticPmi(writer, shapeId, shapeRepresentationId, repContextId, lengthUnitId, advancedFaceIds, semanticPmi);
+ IReadOnlyList<KernelDiagnostic> importedPmiDiagnostics = [];
+ IReadOnlyDictionary<string, string>? importedDatumEntities = null;
+ if (options.ImportedPmi is { } importedPmi)
+ {
+ var transferred = importedPmi.Emit(writer, body, shapeId, shapeRepresentationId, repContextId, lengthUnitId, brepId, advancedFaceIds, edgeCurveIds, out importedDatumEntities);
+ if (!transferred.IsSuccess) return KernelResult<string>.Failure(transferred.Diagnostics);
+ importedPmiDiagnostics = transferred.Diagnostics;
+ }
+ EmitSemanticPmi(writer, shapeId, shapeRepresentationId, repContextId, lengthUnitId, advancedFaceIds, semanticPmi, importedDatumEntities);
return KernelResult<string>.Success(
writer.Build(options.HeaderMetadata),
- normalizationDiagnostics.Concat(preflight is null ? [] : ToKernelDiagnostics(preflight, errorsAsWarnings: true)).ToArray());
+ normalizationDiagnostics.Concat(importedPmiDiagnostics).Concat(preflight is null ? [] : ToKernelDiagnostics(preflight, errorsAsWarnings: true)).ToArray());
}
private static void EmitAuxiliaryVertexPointForVertexlessAnalyticBody(Step242TextWriter writer, BrepBody body, TopologyModel model)
@@ -474,34 +493,40 @@ public static class Step242Exporter
string repContextId,
string lengthUnitId,
IReadOnlyDictionary<FaceId, string> advancedFaceIds,
- IReadOnlyList<Step242SemanticPmi>? semanticPmi)
+ IReadOnlyList<Step242SemanticPmi>? semanticPmi, IReadOnlyDictionary<string, string>? importedDatums = null)
{
if (semanticPmi is null || semanticPmi.Count == 0) return;
var datumEntities = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
+ foreach (var imported in importedDatums ?? new Dictionary<string, string>()) datumEntities.Add(imported.Key, imported.Value);
+ var datumAspects = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var datum in semanticPmi.OfType<Step242SemanticPmiDatum>())
- datumEntities[datum.Label] = EmitDatumSemanticPmi(writer, shapeId, datum);
+ {
+ datumEntities[datum.Label] = EmitDatumSemanticPmi(writer, shapeId, datum, out var featureAspect);
+ datumAspects[datum.Label] = featureAspect;
+ }
foreach (var item in semanticPmi)
{
+ string? boundAspect = item is Step242SemanticPmiDatum d ? datumAspects[d.Label] : null;
switch (item)
{
case Step242SemanticPmiDatum:
break;
case Step242SemanticPmiHole hole:
- EmitHoleSemanticPmi(writer, shapeId, repContextId, lengthUnitId, hole);
+ boundAspect = EmitHoleSemanticPmi(writer, shapeId, repContextId, lengthUnitId, hole);
break;
case Step242SemanticPmiDimension dimension:
- EmitDimensionSemanticPmi(writer, shapeId, repContextId, lengthUnitId, dimension);
+ boundAspect = EmitDimensionSemanticPmi(writer, shapeId, repContextId, lengthUnitId, dimension);
break;
case Step242SemanticPmiNote note:
EmitNoteSemanticPmi(writer.AddEntity, Step242TextWriter.Ref(shapeId), note);
break;
case Step242SemanticPmiGeometricTolerance tolerance:
- EmitGeometricToleranceSemanticPmi(writer, shapeId, lengthUnitId, tolerance, datumEntities);
+ boundAspect = EmitGeometricToleranceSemanticPmi(writer, shapeId, lengthUnitId, tolerance, datumEntities);
break;
}
- EmitGeometricItemAssociations(writer, shapeId, shapeRepresentationId, advancedFaceIds, item);
+ EmitGeometricItemAssociations(writer, shapeId, shapeRepresentationId, advancedFaceIds, item, boundAspect);
}
}
@@ -510,7 +535,7 @@ public static class Step242Exporter
string shapeId,
string shapeRepresentationId,
IReadOnlyDictionary<FaceId, string> advancedFaceIds,
- Step242SemanticPmi item)
+ Step242SemanticPmi item, string? boundAspect = null)
{
if (item.GeometricFaceIds.Count == 0) return;
var target = item switch
@@ -519,7 +544,7 @@ public static class Step242Exporter
Step242SemanticPmiNote note => note.Target,
_ => item.FeatureId
};
- var aspectId = writer.AddEntity(
+ var aspectId = boundAspect ?? writer.AddEntity(
"SHAPE_ASPECT",
Step242TextWriter.String($"firmament-geometric-target:{target}"),
Step242TextWriter.String($"semantic geometry binding target={target}"),
@@ -538,7 +563,7 @@ public static class Step242Exporter
}
}
- private static void EmitHoleSemanticPmi(
+ private static string EmitHoleSemanticPmi(
Step242TextWriter writer,
string shapeId,
string repContextId,
@@ -548,7 +573,7 @@ public static class Step242Exporter
var featureShapeAspectId = writer.AddEntity(
"SHAPE_ASPECT",
Step242TextWriter.String($"firmament-feature:{hole.FeatureId}"),
- Step242TextWriter.String("semantic cylindrical sheet feature"),
+ Step242TextWriter.String($"semantic cylindrical sheet feature target={hole.FeatureId}"),
Step242TextWriter.Ref(shapeId),
Step242TextWriter.BooleanLogical(true));
var propertyDefinitionId = writer.AddEntity(
@@ -559,7 +584,7 @@ public static class Step242Exporter
var measureItemId = writer.AddEntity(
"MEASURE_REPRESENTATION_ITEM",
Step242TextWriter.String("diameter"),
- Step242TextWriter.Number(hole.Diameter),
+ Step242TextWriter.PmiNumber(hole.Diameter),
Step242TextWriter.Ref(lengthUnitId));
var representationId = writer.AddEntity(
"SHAPE_DIMENSION_REPRESENTATION",
@@ -572,14 +597,15 @@ public static class Step242Exporter
if (hole.Depth.HasValue)
{
- var depthItemId = writer.AddEntity("MEASURE_REPRESENTATION_ITEM", Step242TextWriter.String("depth"), Step242TextWriter.Number(hole.Depth.Value), Step242TextWriter.Ref(lengthUnitId));
+ var depthItemId = writer.AddEntity("MEASURE_REPRESENTATION_ITEM", Step242TextWriter.String("depth"), Step242TextWriter.PmiNumber(hole.Depth.Value), Step242TextWriter.Ref(lengthUnitId));
var depthRepId = writer.AddEntity("SHAPE_DIMENSION_REPRESENTATION", Step242TextWriter.String($"depth:{hole.FeatureId}"), Step242TextWriter.List(depthItemId), Step242TextWriter.Ref(repContextId));
var depthPropertyDefinitionId = writer.AddEntity("PROPERTY_DEFINITION", Step242TextWriter.String($"depth:{hole.FeatureId}"), Step242TextWriter.String("semantic PMI depth"), Step242TextWriter.Ref(featureShapeAspectId));
writer.AddEntity("PROPERTY_DEFINITION_REPRESENTATION", Step242TextWriter.Ref(depthPropertyDefinitionId), Step242TextWriter.Ref(depthRepId));
}
+ return featureShapeAspectId;
}
- private static string EmitDatumSemanticPmi(Step242TextWriter writer, string shapeId, Step242SemanticPmiDatum datum)
+ private static string EmitDatumSemanticPmi(Step242TextWriter writer, string shapeId, Step242SemanticPmiDatum datum, out string featureAspect)
{
// Retain the established generic SHAPE_ASPECT contract for existing AP242
// consumers while also emitting the formal AP242 datum entities below.
@@ -595,6 +621,7 @@ public static class Step242Exporter
Step242TextWriter.String($"semantic datum {datum.DatumKind} target={datum.Target}"),
Step242TextWriter.Ref(shapeId),
Step242TextWriter.BooleanLogical(true));
+ featureAspect = featureId;
var datumId = writer.AddEntity(
"DATUM",
Step242TextWriter.String($"firmament-datum-reference:{datum.Label}"),
@@ -608,7 +635,7 @@ public static class Step242Exporter
return datumId;
}
- private static void EmitDimensionSemanticPmi(
+ private static string EmitDimensionSemanticPmi(
Step242TextWriter writer,
string shapeId,
string repContextId,
@@ -617,11 +644,12 @@ public static class Step242Exporter
{
var aspectId = writer.AddEntity("SHAPE_ASPECT", Step242TextWriter.String($"firmament-feature:{dimension.FeatureId}"), Step242TextWriter.String($"semantic {dimension.DimensionKind} dimension target={dimension.FeatureId}"), Step242TextWriter.Ref(shapeId), Step242TextWriter.BooleanLogical(true));
var propertyId = writer.AddEntity("PROPERTY_DEFINITION", Step242TextWriter.String($"dimension:{dimension.Name}:{dimension.FeatureId}"), Step242TextWriter.String($"semantic PMI {dimension.DimensionKind} dimension"), Step242TextWriter.Ref(aspectId));
- var valueId = writer.AddEntity("MEASURE_REPRESENTATION_ITEM", Step242TextWriter.String(dimension.DimensionKind.ToLowerInvariant()), Step242TextWriter.Number(dimension.Value), Step242TextWriter.Ref(lengthUnitId));
+ var valueId = writer.AddEntity("MEASURE_REPRESENTATION_ITEM", Step242TextWriter.String(dimension.DimensionKind.ToLowerInvariant()), Step242TextWriter.PmiNumber(dimension.Value), Step242TextWriter.Ref(lengthUnitId));
var representationId = writer.AddEntity("SHAPE_DIMENSION_REPRESENTATION", Step242TextWriter.String($"dimension:{dimension.Name}"), Step242TextWriter.List(valueId), Step242TextWriter.Ref(repContextId));
writer.AddEntity("PROPERTY_DEFINITION_REPRESENTATION", Step242TextWriter.Ref(propertyId), Step242TextWriter.Ref(representationId));
EmitBilateralToleranceRepresentation(writer, aspectId, repContextId, lengthUnitId, $"dimension_tolerance:{dimension.Name}", dimension.TolerancePlus, dimension.ToleranceMinus);
EmitQuantitySemanticPmi(writer, aspectId, dimension.FeatureId, dimension.Quantity);
+ return aspectId;
}
private static void EmitBilateralToleranceRepresentation(
@@ -636,8 +664,8 @@ public static class Step242Exporter
if (!tolerancePlus.HasValue && !toleranceMinus.HasValue) return;
var plus = tolerancePlus ?? toleranceMinus!.Value;
var minus = toleranceMinus ?? tolerancePlus!.Value;
- var plusId = writer.AddEntity("MEASURE_REPRESENTATION_ITEM", Step242TextWriter.String("tolerance_plus"), Step242TextWriter.Number(plus), Step242TextWriter.Ref(lengthUnitId));
- var minusId = writer.AddEntity("MEASURE_REPRESENTATION_ITEM", Step242TextWriter.String("tolerance_minus"), Step242TextWriter.Number(minus), Step242TextWriter.Ref(lengthUnitId));
+ var plusId = writer.AddEntity("MEASURE_REPRESENTATION_ITEM", Step242TextWriter.String("tolerance_plus"), Step242TextWriter.PmiNumber(plus), Step242TextWriter.Ref(lengthUnitId));
+ var minusId = writer.AddEntity("MEASURE_REPRESENTATION_ITEM", Step242TextWriter.String("tolerance_minus"), Step242TextWriter.PmiNumber(minus), Step242TextWriter.Ref(lengthUnitId));
var representationId = writer.AddEntity("SHAPE_DIMENSION_REPRESENTATION", Step242TextWriter.String(stableName), Step242TextWriter.List(plusId, minusId), Step242TextWriter.Ref(repContextId));
var propertyId = writer.AddEntity("PROPERTY_DEFINITION", Step242TextWriter.String(stableName), Step242TextWriter.String("semantic PMI bilateral tolerance"), Step242TextWriter.Ref(aspectId));
writer.AddEntity("PROPERTY_DEFINITION_REPRESENTATION", Step242TextWriter.Ref(propertyId), Step242TextWriter.Ref(representationId));
@@ -649,25 +677,38 @@ public static class Step242Exporter
writer.AddEntity("PROPERTY_DEFINITION", Step242TextWriter.String($"quantity:{target}"), Step242TextWriter.String(quantity.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)), Step242TextWriter.Ref(aspectId));
}
- private static void EmitGeometricToleranceSemanticPmi(
+ private static string EmitGeometricToleranceSemanticPmi(
Step242TextWriter writer,
string shapeId,
string lengthUnitId,
Step242SemanticPmiGeometricTolerance tolerance,
IReadOnlyDictionary<string, string> datumEntities)
{
- if (!tolerance.ToleranceKind.Equals("Position", StringComparison.OrdinalIgnoreCase)) return;
+ var kind = Step242GeometricToleranceKinds.Find(tolerance.ToleranceKind)!; // Validated before serialization.
var targetAspectId = writer.AddEntity("COMPOSITE_SHAPE_ASPECT", Step242TextWriter.String($"firmament-target:{tolerance.FeatureId}"), Step242TextWriter.String($"semantic target quantity={tolerance.Quantity?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "unspecified"}"), Step242TextWriter.Ref(shapeId), Step242TextWriter.BooleanLogical(true));
- var magnitudeId = writer.AddRawEntity($"(LENGTH_MEASURE_WITH_UNIT()MEASURE_REPRESENTATION_ITEM()MEASURE_WITH_UNIT(LENGTH_MEASURE({Step242TextWriter.Number(tolerance.Value)}),{lengthUnitId})REPRESENTATION_ITEM({Step242TextWriter.String("position tolerance")}))");
+ var magnitudeId = writer.AddRawEntity($"(LENGTH_MEASURE_WITH_UNIT()MEASURE_REPRESENTATION_ITEM()MEASURE_WITH_UNIT(LENGTH_MEASURE({Step242TextWriter.PmiNumber(tolerance.Value)}),{lengthUnitId})REPRESENTATION_ITEM({Step242TextWriter.String(kind.Name + " tolerance")}))");
var compartments = new List<string>();
foreach (var label in tolerance.DatumReferences)
{
if (!datumEntities.TryGetValue(label, out var datumId)) continue;
compartments.Add(writer.AddEntity("DATUM_REFERENCE_COMPARTMENT", Step242TextWriter.String(""), "$", Step242TextWriter.Ref(shapeId), Step242TextWriter.BooleanLogical(false), Step242TextWriter.Ref(datumId), "$"));
}
- var datumSystemId = writer.AddEntity("DATUM_SYSTEM", Step242TextWriter.String($"firmament-datum-system:{tolerance.Name}"), "$", Step242TextWriter.Ref(shapeId), Step242TextWriter.BooleanLogical(false), Step242TextWriter.List(compartments.ToArray()));
- writer.AddRawEntity($"(GEOMETRIC_TOLERANCE({Step242TextWriter.String(tolerance.Name)},{Step242TextWriter.String($"semantic position target={tolerance.FeatureId}")},{magnitudeId},{targetAspectId})GEOMETRIC_TOLERANCE_WITH_DATUM_REFERENCE(({datumSystemId}))POSITION_TOLERANCE())");
+ var datumClause = "";
+ if (compartments.Count > 0)
+ {
+ var datumSystemId = writer.AddEntity("DATUM_SYSTEM", Step242TextWriter.String($"firmament-datum-system:{tolerance.Name}"), "$", Step242TextWriter.Ref(shapeId), Step242TextWriter.BooleanLogical(false), Step242TextWriter.List(compartments.ToArray()));
+ datumClause = $"GEOMETRIC_TOLERANCE_WITH_DATUM_REFERENCE(({datumSystemId}))";
+ }
+ var modifiers = tolerance.Modifiers.Count == 0 ? "" : "GEOMETRIC_TOLERANCE_WITH_MODIFIERS((" + string.Join(",", tolerance.Modifiers.Select(m => Step242TextWriter.Enum(Step242GeometricToleranceKinds.Modifiers[m]))) + "))";
+ var components = new[] { $"GEOMETRIC_TOLERANCE({Step242TextWriter.String(tolerance.Name)},{Step242TextWriter.String($"semantic {kind.Name} target={tolerance.FeatureId}")},{magnitudeId},{targetAspectId})", datumClause, modifiers, kind.Entity + "()" }.Where(s => s.Length > 0).Order(StringComparer.Ordinal);
+ var controlId = writer.AddRawEntity("(" + string.Concat(components) + ")");
+ if (tolerance.ZoneForm is { } zone)
+ {
+ var formId = writer.AddEntity("TOLERANCE_ZONE_FORM", Step242TextWriter.String(Step242GeometricToleranceKinds.ZoneForms[zone]));
+ writer.AddEntity("TOLERANCE_ZONE", "''", "$", shapeId, ".F.", Step242TextWriter.List(controlId), formId);
+ }
EmitQuantitySemanticPmi(writer, targetAspectId, tolerance.FeatureId, tolerance.Quantity);
+ return targetAspectId;
}
internal static void EmitNoteSemanticPmi(Func<string, string[], string> addEntity, string shapeReference, Step242SemanticPmiNote note)
diff --git a/Aetheris.Kernel.Core/Step242/Step242ForeignPmiReader.cs b/Aetheris.Kernel.Core/Step242/Step242ForeignPmiReader.cs
new file mode 100644
index 00000000..22c37ac1
--- /dev/null
+++ b/Aetheris.Kernel.Core/Step242/Step242ForeignPmiReader.cs
@@ -0,0 +1,174 @@
+namespace Aetheris.Kernel.Core.Step242;
+
+/// <summary>Read semantic AP242 controls by their schema relationships, independently of vendor names.</summary>
+internal sealed class Step242ForeignPmiReader
+{
+ private readonly Step242ParsedDocument document;
+ private readonly Dictionary<int, Step242ParsedEntity> entities;
+ private readonly Dictionary<int, List<int>> aspectLinks = [];
+ private readonly Dictionary<int, List<int>> aspectGeometry = [];
+ private readonly Dictionary<int, HashSet<int>> edgeFaces = [];
+ private readonly Dictionary<int, int> dimensionRepresentations = [];
+ private readonly Dictionary<int, int> dimensionTolerances = [];
+ private readonly Dictionary<int, List<string>> zoneForms = [];
+ private readonly HashSet<int> advancedZones = [];
+ internal Step242ForeignPmiReader(Step242ParsedDocument document)
+ {
+ this.document = document;
+ entities = document.Entities.ToDictionary(e => e.Id);
+ foreach (var entity in document.Entities)
+ {
+ if (Step242SubsetDecoder.TryGetConstructor(entity.Instance, "SHAPE_ASPECT_RELATIONSHIP") is { } link
+ && Ref(link.Arguments.ElementAtOrDefault(2)) is { } a && Ref(link.Arguments.ElementAtOrDefault(3)) is { } b)
+ { Add(aspectLinks, a, b); Add(aspectLinks, b, a); }
+ if (entity.Name == "GEOMETRIC_ITEM_SPECIFIC_USAGE" && Ref(entity.Arguments.ElementAtOrDefault(2)) is { } aspect)
+ foreach (var geometry in Refs(entity.Arguments.ElementAtOrDefault(4))) Add(aspectGeometry, aspect, geometry);
+ if (entity.Name == "DIMENSIONAL_CHARACTERISTIC_REPRESENTATION" && Ref(entity.Arguments.ElementAtOrDefault(0)) is { } dimension && Ref(entity.Arguments.ElementAtOrDefault(1)) is { } representation)
+ dimensionRepresentations[dimension] = representation;
+ if (entity.Name == "PLUS_MINUS_TOLERANCE" && Ref(entity.Arguments.ElementAtOrDefault(0)) is { } tolerance && Ref(entity.Arguments.ElementAtOrDefault(1)) is { } controlled)
+ dimensionTolerances[controlled] = tolerance;
+ if (entity.Name == "TOLERANCE_ZONE" && Ref(entity.Arguments.ElementAtOrDefault(5)) is { } form && entities.TryGetValue(form, out var zoneForm) && Str(zoneForm.Arguments.FirstOrDefault()) is { } formName)
+ foreach (var target in Refs(entity.Arguments.ElementAtOrDefault(4)))
+ { if (!zoneForms.TryGetValue(target, out var forms)) zoneForms[target] = forms = []; forms.Add(formName); }
+ if (entity.Name.EndsWith("ZONE_DEFINITION", StringComparison.Ordinal) || entity.Name.EndsWith("TOLERANCE_ZONE", StringComparison.Ordinal) && entity.Name != "TOLERANCE_ZONE")
+ foreach (var reference in Step242PmiTransfer.References(entity.Instance)) advancedZones.Add(reference);
+ }
+ foreach (var face in document.Entities.Where(e => e.Name == "ADVANCED_FACE"))
+ {
+ var pending = new Stack<int>(Step242PmiTransfer.References(face.Instance)); var seen = new HashSet<int>();
+ while (pending.TryPop(out var id))
+ {
+ if (!seen.Add(id) || !entities.TryGetValue(id, out var entity)) continue;
+ if (entity.Name == "EDGE_CURVE")
+ { if (!edgeFaces.TryGetValue(id, out var faces)) edgeFaces[id] = faces = []; faces.Add(face.Id); continue; }
+ if (entity.Name is "FACE_OUTER_BOUND" or "FACE_BOUND" or "EDGE_LOOP" or "ORIENTED_EDGE")
+ foreach (var child in Step242PmiTransfer.References(entity.Instance)) pending.Push(child);
+ }
+ }
+ }
+ internal IReadOnlyList<Step242SemanticPmiInspectionItem> Read(IReadOnlyList<Step242SemanticPmiInspectionItem> existing)
+ {
+ var result = new List<Step242SemanticPmiInspectionItem>(); var skip = existing.Select(i => i.EntityId).ToHashSet();
+ foreach (var entity in entities.Values.OrderBy(e => e.Id))
+ {
+ if (skip.Contains(entity.Id)) continue;
+ if (Step242SubsetDecoder.TryGetConstructor(entity.Instance, "DATUM") is { } datum)
+ {
+ var label = Str(datum.Arguments.ElementAtOrDefault(4));
+ if (label is null || existing.Any(i => i.Kind == "Datum" && i.Name == label)) continue;
+ result.Add(Item(entity.Id, "Datum", label, entity.Id, null) with { GeometricFaceEntityIds = Faces(entity.Id) });
+ continue;
+ }
+ var geometric = Step242PmiTransfer.GeometricTolerance(entity);
+ var kind = Step242GeometricToleranceKinds.All.FirstOrDefault(k => Step242SubsetDecoder.TryGetConstructor(entity.Instance, k.Entity) is not null);
+ if (geometric is not null)
+ {
+ var target = Ref(geometric.Arguments.ElementAtOrDefault(3));
+ var value = Ref(geometric.Arguments.ElementAtOrDefault(2)) is { } magnitude ? Measure(magnitude) : null;
+ var frames = DatumFrames(entity);
+ var modifiers = Step242SubsetDecoder.TryGetConstructor(entity.Instance, "GEOMETRIC_TOLERANCE_WITH_MODIFIERS") is { } modified ? Enums(modified.Arguments.FirstOrDefault()).ToArray() : [];
+ var constructors = entity.Instance is Step242ComplexEntityInstance complex ? complex.Constructors : [entity.Instance.PrimaryConstructor];
+ var basic = kind is not null && constructors.All(c => c.Name == kind.Entity || c.Name is "GEOMETRIC_TOLERANCE" or "GEOMETRIC_TOLERANCE_WITH_DATUM_REFERENCE" or "GEOMETRIC_TOLERANCE_WITH_MODIFIERS")
+ && frames.All(f => f.PresentationSupported) && !advancedZones.Contains(entity.Id)
+ && (zoneForms.GetValueOrDefault(entity.Id) ?? []).All(form => Step242GeometricToleranceKinds.ZoneForms.Values.Contains(form))
+ && !entities.Values.Any(e => e.Name == "TOLERANCE_ZONE" && advancedZones.Contains(e.Id) && Refs(e.Arguments.ElementAtOrDefault(4)).Contains(entity.Id));
+ result.Add(Item(entity.Id, kind?.Name ?? "GeometricTolerance", Str(geometric.Arguments.ElementAtOrDefault(0)) ?? $"tolerance-{entity.Id}", target, value) with
+ { DatumReferences = frames.SelectMany(frame => frame.Labels).ToArray(), DatumReferenceFrames = frames, Modifiers = modifiers, ZoneForms = zoneForms.GetValueOrDefault(entity.Id) ?? [], PresentationSupported = basic });
+ continue;
+ }
+ if (entity.Name is "DIMENSIONAL_SIZE" or "ANGULAR_SIZE" or "DIMENSIONAL_LOCATION" or "ANGULAR_LOCATION" or "DIRECTED_DIMENSIONAL_LOCATION")
+ {
+ var location = entity.Name is "DIMENSIONAL_LOCATION" or "ANGULAR_LOCATION" or "DIRECTED_DIMENSIONAL_LOCATION";
+ var definition = Step242SubsetDecoder.TryGetConstructor(entity.Instance, location ? "DIMENSIONAL_LOCATION" : "DIMENSIONAL_SIZE") ?? entity.Instance.PrimaryConstructor;
+ var target = Ref(definition.Arguments.FirstOrDefault());
+ var targets = location ? definition.Arguments.Skip(2).OfType<Step242EntityReference>().Select(r => r.TargetId).Take(2).ToArray() : target is { } id ? [id] : [];
+ var representation = dimensionRepresentations.GetValueOrDefault(entity.Id);
+ var measureIds = entities.TryGetValue(representation, out var rep) ? Refs(rep.Arguments.ElementAtOrDefault(1)).ToArray() : [];
+ var measured = measureIds.Select(Measure).FirstOrDefault(v => v.HasValue);
+ var lower = default(double?); var upper = default(double?);
+ if (dimensionTolerances.TryGetValue(entity.Id, out var toleranceId) && entities.TryGetValue(toleranceId, out var tolerance) && tolerance.Name == "TOLERANCE_VALUE")
+ {
+ lower = Ref(tolerance.Arguments.ElementAtOrDefault(0)) is { } lo ? Measure(lo) : null;
+ upper = Ref(tolerance.Arguments.ElementAtOrDefault(1)) is { } hi ? Measure(hi) : null;
+ }
+ var dimensionKind = Str(definition.Arguments.ElementAtOrDefault(location ? 0 : 1)) ?? "Length";
+ var name = targets.Select(id => entities.GetValueOrDefault(id)?.Arguments.FirstOrDefault()).OfType<Step242StringValue>().Select(s => s.Value).FirstOrDefault(s => s.Length > 0) ?? $"dimension-{entity.Id}";
+ result.Add(Item(entity.Id, "Dimension", name, targets.FirstOrDefault(), measured) with
+ { DimensionKind = dimensionKind, ValueUnit = entity.Name is "ANGULAR_SIZE" or "ANGULAR_LOCATION" ? "rad" : "mm", GeometricFaceEntityIds = targets.SelectMany(Faces).Distinct().Order().ToArray(),
+ GeometricItemEntityIds = targets.SelectMany(GeometryItems).Distinct().Order().ToArray(), TolerancePlus = upper, ToleranceMinus = lower.HasValue ? -lower.Value : null,
+ PresentationSupported = !measureIds.Any(id => entities.TryGetValue(id, out var measure) && Step242SubsetDecoder.TryGetConstructor(measure.Instance, "QUALIFIED_REPRESENTATION_ITEM") is not null) });
+ }
+ }
+ return result;
+ }
+ private Step242SemanticPmiInspectionItem Item(int id, string kind, string name, int? target, double? value)
+ => new(id, kind, name, target.HasValue ? $"shape-aspect:#{target}" : "", value, null, null, null, [], null)
+ { GeometricFaceEntityIds = target.HasValue ? Faces(target.Value) : [], GeometricItemEntityIds = target.HasValue ? GeometryItems(target.Value) : [] };
+ private IReadOnlyList<int> Faces(int aspect)
+ => GeometryItems(aspect).SelectMany(geometry => entities.GetValueOrDefault(geometry)?.Name == "ADVANCED_FACE"
+ ? [geometry] : edgeFaces.GetValueOrDefault(geometry) ?? []).Distinct().Order().ToArray();
+ private IReadOnlyList<int> GeometryItems(int aspect)
+ {
+ var pending = new Stack<int>([aspect]); var seen = new HashSet<int>(); var geometry = new HashSet<int>();
+ while (pending.TryPop(out var id))
+ {
+ if (!seen.Add(id)) continue;
+ geometry.UnionWith(aspectGeometry.GetValueOrDefault(id) ?? []);
+ foreach (var linked in aspectLinks.GetValueOrDefault(id) ?? []) pending.Push(linked);
+ }
+ return geometry.Order().ToArray();
+ }
+ private IReadOnlyList<Step242PmiDatumFrame> DatumFrames(Step242ParsedEntity entity)
+ {
+ var clause = Step242SubsetDecoder.TryGetConstructor(entity.Instance, "GEOMETRIC_TOLERANCE_WITH_DATUM_REFERENCE");
+ var frames = new List<Step242PmiDatumFrame>();
+ var roots = Refs(clause?.Arguments.FirstOrDefault()).ToArray();
+ // AP214 datum references are a SET ordered by priority; AP242 constituents are a LIST.
+ if (roots.All(id => entities.GetValueOrDefault(id)?.Name == "DATUM_REFERENCE"))
+ roots = roots.OrderBy(id => (entities[id].Arguments.FirstOrDefault() as Step242NumberValue)?.Value ?? double.MaxValue).ToArray();
+ foreach (var id in roots)
+ {
+ if (!entities.TryGetValue(id, out var system)) continue;
+ var compartments = system.Name == "DATUM_SYSTEM" ? Refs(system.Arguments.ElementAtOrDefault(4)) : new[] { id };
+ foreach (var compartmentId in compartments)
+ {
+ var labels = new List<string>(); var modifiers = new List<string>(); var seen = new HashSet<int>();
+ var supported = true;
+ void Walk(int current)
+ {
+ if (!seen.Add(current) || !entities.TryGetValue(current, out var datum)) return;
+ if (Step242SubsetDecoder.TryGetConstructor(datum.Instance, "DATUM") is { } definition)
+ { if (Str(definition.Arguments.ElementAtOrDefault(4)) is { } label) labels.Add(label); return; }
+ if (datum.Name == "DATUM_REFERENCE_MODIFIER_WITH_VALUE") { supported = false; return; }
+ if (datum.Name is not ("DATUM_REFERENCE" or "DATUM_REFERENCE_COMPARTMENT" or "DATUM_REFERENCE_ELEMENT" or "COMMON_DATUM")) return;
+ if (datum.Name is "COMMON_DATUM" or "DATUM_REFERENCE_ELEMENT") supported = false;
+ modifiers.AddRange(datum.Arguments.SelectMany(Enums));
+ foreach (var child in Step242PmiTransfer.References(datum.Instance)) Walk(child);
+ }
+ Walk(compartmentId); frames.Add(new(frames.Count + 1, labels, modifiers) { PresentationSupported = supported });
+ }
+ }
+ return frames;
+ }
+ internal double? Measure(int id)
+ {
+ if (!entities.TryGetValue(id, out var entity)) return null;
+ var measure = Step242SubsetDecoder.TryGetConstructor(entity.Instance, "MEASURE_WITH_UNIT") ?? entity.Instance.PrimaryConstructor;
+ var unitIndex = measure.Name == "MEASURE_REPRESENTATION_ITEM" ? 2 : 1;
+ var valueIndex = measure.Name == "MEASURE_REPRESENTATION_ITEM" ? 1 : 0;
+ var value = Number(measure.Arguments.ElementAtOrDefault(valueIndex));
+ if (value is null) return null;
+ if (Ref(measure.Arguments.ElementAtOrDefault(unitIndex)) is { } unit && entities.TryGetValue(unit, out var u) && Step242SubsetDecoder.TryGetConstructor(u.Instance, "LENGTH_UNIT") is not null)
+ return Step242LengthUnitNormalizer.TryResolveMetresPerUnit(entities, unit, [], out var metres) ? Step242LengthUnitNormalizer.ScalePmiMeasure(value.Value, metres * 1000d) : null;
+ if (Ref(measure.Arguments.ElementAtOrDefault(unitIndex)) is { } angleUnit && document.TryResolvePlaneAngleUnitScale(angleUnit, [], out var radians)) return value * radians;
+ if (Ref(measure.Arguments.ElementAtOrDefault(unitIndex)) is { } compoundUnit && entities.GetValueOrDefault(compoundUnit)?.Name == "DERIVED_UNIT")
+ return Step242LengthUnitNormalizer.TryResolvePmiScale(entities, compoundUnit, [], out var scale) ? Step242LengthUnitNormalizer.ScalePmiMeasure(value.Value, scale) : null;
+ return value;
+ }
+ private static double? Number(Step242Value? value) => value switch { Step242NumberValue n => n.Value, Step242TypedValue t => t.Arguments.Select(Number).FirstOrDefault(v => v.HasValue), _ => null };
+ private static int? Ref(Step242Value? value) => value is Step242EntityReference r ? r.TargetId : null;
+ private static string? Str(Step242Value? value) => value is Step242StringValue s ? s.Value : null;
+ private static IEnumerable<int> Refs(Step242Value? value) => value switch { Step242EntityReference r => [r.TargetId], Step242ListValue list => list.Items.SelectMany(Refs), _ => [] };
+ private static IEnumerable<string> Enums(Step242Value? value) => value switch { Step242EnumValue e => [e.Value], Step242ListValue list => list.Items.SelectMany(Enums), _ => [] };
+ private static void Add(Dictionary<int, List<int>> map, int key, int value) { if (!map.TryGetValue(key, out var values)) map[key] = values = []; values.Add(value); }
+}
diff --git a/Aetheris.Kernel.Core/Step242/Step242GeometricToleranceKinds.cs b/Aetheris.Kernel.Core/Step242/Step242GeometricToleranceKinds.cs
new file mode 100644
index 00000000..f9f2dc5f
--- /dev/null
+++ b/Aetheris.Kernel.Core/Step242/Step242GeometricToleranceKinds.cs
@@ -0,0 +1,35 @@
+namespace Aetheris.Kernel.Core.Step242;
+
+/// <summary>The explicitly admitted semantic controls. They annotate geometry; they do not solve or modify it.</summary>
+public static class Step242GeometricToleranceKinds
+{
+ public sealed record Descriptor(string Name, string Entity, bool RequiresDatum, bool AllowsDatum);
+ public static IReadOnlyList<Descriptor> All { get; } = [
+ new("Straightness", "STRAIGHTNESS_TOLERANCE", false, false), new("Flatness", "FLATNESS_TOLERANCE", false, false),
+ new("Roundness", "ROUNDNESS_TOLERANCE", false, false), new("Cylindricity", "CYLINDRICITY_TOLERANCE", false, false),
+ new("Parallelism", "PARALLELISM_TOLERANCE", true, true), new("Perpendicularity", "PERPENDICULARITY_TOLERANCE", true, true),
+ new("Angularity", "ANGULARITY_TOLERANCE", true, true), new("Position", "POSITION_TOLERANCE", false, true),
+ new("LineProfile", "LINE_PROFILE_TOLERANCE", false, true), new("SurfaceProfile", "SURFACE_PROFILE_TOLERANCE", false, true),
+ new("CircularRunout", "CIRCULAR_RUNOUT_TOLERANCE", true, true), new("TotalRunout", "TOTAL_RUNOUT_TOLERANCE", true, true) ];
+ public static Descriptor? Find(string kind) => All.FirstOrDefault(item => item.Name.Equals(kind switch { "Parallel" => "Parallelism", "Perpendicular" => "Perpendicularity", _ => kind }, StringComparison.OrdinalIgnoreCase));
+ public static IReadOnlyDictionary<string, string> Modifiers { get; } = new Dictionary<string, string>(StringComparer.Ordinal)
+ {
+ ["MaximumMaterial"] = "MAXIMUM_MATERIAL_REQUIREMENT", ["LeastMaterial"] = "LEAST_MATERIAL_REQUIREMENT",
+ ["FreeState"] = "FREE_STATE", ["CommonZone"] = "COMMON_ZONE", ["Statistical"] = "STATISTICAL_TOLERANCE"
+ };
+ public static IReadOnlyDictionary<string, string> ZoneForms { get; } = new Dictionary<string, string>(StringComparer.Ordinal)
+ { ["Cylindrical"] = "cylindrical or circular", ["Spherical"] = "spherical", ["BetweenSurfaces"] = "between two equidistant surfaces" };
+ internal static string? Validate(Step242SemanticPmiGeometricTolerance tolerance, IReadOnlySet<string> datums)
+ {
+ var kind = Find(tolerance.ToleranceKind);
+ if (kind is null) return $"Unknown control '{tolerance.ToleranceKind}'.";
+ if (!double.IsFinite(tolerance.Value) || tolerance.Value < 0) return "Tolerance must be finite and nonnegative.";
+ if (kind.RequiresDatum && tolerance.DatumReferences.Count == 0 || !kind.AllowsDatum && tolerance.DatumReferences.Count > 0) return $"Invalid datum references for {kind.Name}.";
+ if (tolerance.DatumReferences.Count > 3 || tolerance.DatumReferences.Distinct(StringComparer.OrdinalIgnoreCase).Count() != tolerance.DatumReferences.Count
+ || tolerance.DatumReferences.Any(label => !datums.Contains(label))) return "Datum references must resolve uniquely in precedence order (up to three).";
+ if (tolerance.Modifiers.Any(m => !Modifiers.ContainsKey(m)) || tolerance.Modifiers.Distinct().Count() != tolerance.Modifiers.Count
+ || tolerance.Modifiers.Contains("MaximumMaterial") && tolerance.Modifiers.Contains("LeastMaterial")) return "Unknown, duplicate or contradictory control modifiers.";
+ if (tolerance.ZoneForm is { } form && !ZoneForms.ContainsKey(form)) return "Unknown tolerance zone form.";
+ return null;
+ }
+}
diff --git a/Aetheris.Kernel.Core/Step242/Step242Importer.cs b/Aetheris.Kernel.Core/Step242/Step242Importer.cs
index 8725db2a..02784c09 100644
--- a/Aetheris.Kernel.Core/Step242/Step242Importer.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242Importer.cs
@@ -136,6 +136,8 @@ public static class Step242Importer
}
var orchestrator = ImportOrchestrator.CreateDefault();
var result = orchestrator.Import(new ImportRequest(stepText, policy)).BodyResult;
+ if (result.IsSuccess && result.Value is not null)
+ result.Value.SourceStepTextHash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(stepText)));
if (memoizable && result.IsSuccess && result.Value is not null)
{
var retained = result.Value.Clone();
@@ -958,7 +960,7 @@ public static class Step242Importer
}
geometry.AddCurve(curveGeometryId, bindCurveResult.Value.CurveGeometry);
- bindings.AddEdgeBinding(new EdgeGeometryBinding(edgeId, curveGeometryId, bindCurveResult.Value.TrimInterval, edgeSameSense));
+ bindings.AddEdgeBinding(new EdgeGeometryBinding(edgeId, curveGeometryId, bindCurveResult.Value.TrimInterval, edgeSameSense) { SourceStepEntityId = edgeCurveEntity.Id });
return KernelResult<EdgeId>.Success(edgeId);
}
diff --git a/Aetheris.Kernel.Core/Step242/Step242LengthUnitNormalizer.cs b/Aetheris.Kernel.Core/Step242/Step242LengthUnitNormalizer.cs
index 3103180c..ada52530 100644
--- a/Aetheris.Kernel.Core/Step242/Step242LengthUnitNormalizer.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242LengthUnitNormalizer.cs
@@ -11,6 +11,42 @@ namespace Aetheris.Kernel.Core.Step242;
internal static class Step242LengthUnitNormalizer
{
private const double MillimetresPerMetre = 1000d;
+ // Decimal unit arithmetic preserves authored decimal intent without imposing a precision grid.
+ // Very small/large values outside decimal's range retain the floating-point path, never zero by snapping.
+ internal static double ScalePmiMeasure(double value, double scale)
+ {
+ if (scale == 1d || value == 0d) return value;
+ if (decimal.TryParse(value.ToString("R", CultureInfo.InvariantCulture), NumberStyles.Float, CultureInfo.InvariantCulture, out var number)
+ && decimal.TryParse(scale.ToString("R", CultureInfo.InvariantCulture), NumberStyles.Float, CultureInfo.InvariantCulture, out var factor))
+ {
+ try { var product = number * factor; if (product != 0m) return (double)product; }
+ catch (OverflowException) { }
+ }
+ return value * scale;
+ }
+ /// <summary>Length normalization for semantic quantities, including area/volume derived units.
+ /// Non-length components retain their original definitions and contribute no scale change.</summary>
+ internal static bool TryResolvePmiScale(Dictionary<int, Step242ParsedEntity> entities, int unit, HashSet<int> stack, out double scale)
+ {
+ scale = 1d;
+ if (!stack.Add(unit) || !entities.TryGetValue(unit, out var entity)) return false;
+ if (Step242SubsetDecoder.TryGetConstructor(entity.Instance, "LENGTH_UNIT") is not null)
+ {
+ if (!TryResolveMetresPerUnit(entities, unit, [], out var metres)) return false;
+ scale = metres * 1000d; return double.IsFinite(scale) && scale > 0;
+ }
+ if (entity.Name != "DERIVED_UNIT") return true;
+ if (entity.Arguments.FirstOrDefault() is not Step242ListValue parts) return false;
+ foreach (var part in parts.Items)
+ {
+ if (part is not Step242EntityReference component || !entities.TryGetValue(component.TargetId, out var element)
+ || element.Name != "DERIVED_UNIT_ELEMENT" || element.Arguments.ElementAtOrDefault(0) is not Step242EntityReference child
+ || element.Arguments.ElementAtOrDefault(1) is not Step242NumberValue power || !double.IsFinite(power.Value)
+ || !TryResolvePmiScale(entities, child.TargetId, new(stack), out var factor)) return false;
+ scale *= double.Pow(factor, power.Value);
+ }
+ return double.IsFinite(scale) && scale > 0;
+ }
// Entity name -> zero-based argument indices holding a length (radii, semi-axes, vector magnitudes).
private static readonly Dictionary<string, int[]> ScalarLengthArguments = new(StringComparer.OrdinalIgnoreCase)
@@ -167,7 +203,7 @@ internal static class Step242LengthUnitNormalizer
return updated;
}
- private static bool TryResolveMetresPerUnit(Dictionary<int, Step242ParsedEntity> byId, int unitEntityId, HashSet<int> visited, out double metres)
+ internal static bool TryResolveMetresPerUnit(Dictionary<int, Step242ParsedEntity> byId, int unitEntityId, HashSet<int> visited, out double metres)
{
metres = default;
if (!visited.Add(unitEntityId) || !byId.TryGetValue(unitEntityId, out var unitEntity))
diff --git a/Aetheris.Kernel.Core/Step242/Step242PmiTransfer.cs b/Aetheris.Kernel.Core/Step242/Step242PmiTransfer.cs
new file mode 100644
index 00000000..5f0f83bb
--- /dev/null
+++ b/Aetheris.Kernel.Core/Step242/Step242PmiTransfer.cs
@@ -0,0 +1,267 @@
+using System.Globalization;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Diagnostics;
+using Aetheris.Kernel.Core.Results;
+using Aetheris.Kernel.Core.Topology;
+
+namespace Aetheris.Kernel.Core.Step242;
+
+/// <summary>Semantic AP242 annotation graph with source topology correspondence and an unchanged-body witness.
+/// Source presentation glyphs are excluded: they can contain inch text and must be regenerated from semantics.</summary>
+public sealed class Step242PmiTransfer
+{
+ private readonly Step242ParsedDocument document;
+ private readonly BrepBody witness;
+ private readonly Dictionary<int, Step242ParsedEntity> entities;
+ private readonly HashSet<int> selected = [];
+ private readonly HashSet<int> solidGeometry = [];
+ private readonly HashSet<int> primaryProductShapes = [];
+ private readonly HashSet<int> solidRepresentations = [];
+ private readonly Dictionary<string, int> datumEntities;
+ public IReadOnlyList<string> DatumLabels => datumEntities.Keys.ToArray();
+ public int SemanticRecordCount { get; }
+ public bool HasSourcePresentation { get; }
+
+ private Step242PmiTransfer(Step242ParsedDocument document, BrepBody body)
+ {
+ this.document = document; witness = body.Clone();
+ entities = document.Entities.ToDictionary(e => e.Id);
+ foreach (var representation in document.Entities.Where(ContainsSolidDirectly)) solidRepresentations.Add(representation.Id);
+ bool expanded;
+ do
+ {
+ expanded = false;
+ foreach (var relation in document.Entities.Where(e => Has(e, "SHAPE_REPRESENTATION_RELATIONSHIP")
+ && !Has(e, "REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION")))
+ {
+ var definition = Step242SubsetDecoder.TryGetConstructor(relation.Instance, "REPRESENTATION_RELATIONSHIP") ?? relation.Instance.PrimaryConstructor;
+ var related = definition.Arguments.Skip(2).OfType<Step242EntityReference>().Select(r => r.TargetId).ToArray();
+ if (related.Any(solidRepresentations.Contains))
+ foreach (var id in related) expanded |= solidRepresentations.Add(id);
+ }
+ } while (expanded);
+ foreach (var definition in document.Entities.Where(e => e.Name == "SHAPE_DEFINITION_REPRESENTATION"))
+ if (definition.Arguments.ElementAtOrDefault(0) is Step242EntityReference shape
+ && entities.TryGetValue(shape.TargetId, out var productShape) && productShape.Name == "PRODUCT_DEFINITION_SHAPE"
+ && productShape.Arguments.ElementAtOrDefault(2) is Step242EntityReference product
+ && entities.TryGetValue(product.TargetId, out var owner) && Has(owner, "PRODUCT_DEFINITION")
+ && definition.Arguments.ElementAtOrDefault(1) is Step242EntityReference representation
+ && entities.TryGetValue(representation.TargetId, out var rep) && IsSolidRepresentation(rep))
+ primaryProductShapes.Add(shape.TargetId);
+ var pendingGeometry = new Stack<int>(document.Entities.Where(e => e.Name is "MANIFOLD_SOLID_BREP" or "BREP_WITH_VOIDS").Select(e => e.Id));
+ while (pendingGeometry.TryPop(out var geometryId))
+ if (solidGeometry.Add(geometryId) && entities.TryGetValue(geometryId, out var geometry))
+ foreach (var child in References(geometry.Instance)) pendingGeometry.Push(child);
+ foreach (var entity in document.Entities.Where(IsSemanticRoot)) selected.Add(entity.Id);
+ SemanticRecordCount = selected.Count;
+ if (SemanticRecordCount > 0 && document.Entities.Count(e => e.Name is "MANIFOLD_SOLID_BREP" or "BREP_WITH_VOIDS") != 1)
+ throw new PmiTransferException("pmi-source-solid-scope-unsupported: Semantic transfer requires exactly one exact solid; product/occurrence PMI needs an assembly-aware transfer.");
+ HasSourcePresentation = document.Entities.Any(e => e.Name.StartsWith("ANNOTATION_", StringComparison.Ordinal)
+ || e.Name is "DRAUGHTING_MODEL" or "TESSELLATED_ANNOTATION_OCCURRENCE");
+ // Follow semantic dependencies and inverse association owners. Never pull graphical glyphs
+ // into the semantic graph merely because they also reference a shape aspect.
+ bool changed;
+ do
+ {
+ changed = false;
+ foreach (var id in selected.ToArray())
+ {
+ if (IsBoundary(entities[id])) continue;
+ foreach (var reference in References(entities[id].Instance))
+ {
+ if (!entities.ContainsKey(reference)) throw new PmiTransferException($"Missing annotation dependency #{reference} from #{id}.");
+ changed |= selected.Add(reference);
+ }
+ }
+ foreach (var entity in document.Entities.Where(IsAssociation))
+ if (References(entity.Instance).Any(id => selected.Contains(id) && !IsBoundary(entities[id]))) changed |= selected.Add(entity.Id);
+ } while (changed);
+ var semanticDependencies = selected.Where(id => !IsBoundary(entities[id]) &&
+ (IsSemanticRoot(entities[id]) || entities[id].Name.Contains("SHAPE_ASPECT", StringComparison.Ordinal)
+ || entities[id].Name.StartsWith("DATUM_", StringComparison.Ordinal) || entities[id].Name is "SHAPE_DIMENSION_REPRESENTATION" or "TOLERANCE_ZONE")).ToHashSet();
+ var omitted = document.Entities.FirstOrDefault(e => !selected.Contains(e.Id)
+ && !IsPresentation(e) && References(e.Instance).Any(semanticDependencies.Contains));
+ if (omitted is not null) throw new PmiTransferException($"Annotation owner #{omitted.Id} ({omitted.Name}) is not yet qualified for transfer; retaining a partial semantic graph would lose intent.");
+ if (SemanticRecordCount > 0 && primaryProductShapes.Count != 1)
+ throw new PmiTransferException("pmi-source-product-scope-unsupported: Cannot identify a unique product definition for the exact solid.");
+ datumEntities = document.Entities.Select(e => (Entity: e, Datum: Step242SubsetDecoder.TryGetConstructor(e.Instance, "DATUM")))
+ .Where(item => selected.Contains(item.Entity.Id) && item.Datum?.Arguments.ElementAtOrDefault(4) is Step242StringValue { Value.Length: > 0 })
+ .GroupBy(item => ((Step242StringValue)item.Datum!.Arguments[4]).Value, StringComparer.OrdinalIgnoreCase)
+ .Where(group => group.Count() == 1).ToDictionary(group => group.Key, group => group.Single().Entity.Id, StringComparer.Ordinal);
+ }
+
+ public static KernelResult<Step242PmiTransfer> Read(string source, BrepBody body)
+ {
+ var sourceHash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(source)));
+ if (body.SourceStepTextHash != sourceHash)
+ return Failure<Step242PmiTransfer>("pmi-source-body-mismatch", "The body must come from Step242Importer.ImportBody on this exact source. Matching entity numbers alone do not prove annotation ownership.");
+ var parsed = Step242SubsetParser.Parse(source);
+ if (!parsed.IsSuccess) return KernelResult<Step242PmiTransfer>.Failure(parsed.Diagnostics);
+ try
+ {
+ var transfer = new Step242PmiTransfer(parsed.Value, body);
+ foreach (var entity in parsed.Value.Entities)
+ {
+ var tolerance = GeometricTolerance(entity);
+ if (tolerance is null) continue;
+ if (tolerance.Arguments.ElementAtOrDefault(2) is not Step242EntityReference magnitude || !transfer.entities.TryGetValue(magnitude.TargetId, out var measure))
+ throw new PmiTransferException($"Tolerance #{entity.Id} has no typed magnitude.");
+ var value = Step242SubsetDecoder.TryGetConstructor(measure.Instance, "MEASURE_WITH_UNIT") ?? measure.Instance.PrimaryConstructor;
+ if (value.Arguments.ElementAtOrDefault(0) is not Step242TypedValue { Name: "LENGTH_MEASURE" or "POSITIVE_LENGTH_MEASURE", Arguments: [Step242NumberValue number] }
+ || !double.IsFinite(number.Value) || number.Value < 0
+ || value.Arguments.ElementAtOrDefault(1) is not Step242EntityReference unit || !transfer.entities.TryGetValue(unit.TargetId, out var unitEntity) || !Has(unitEntity, "LENGTH_UNIT"))
+ throw new PmiTransferException($"Tolerance #{entity.Id} requires a finite nonnegative length measure with a declared length unit.");
+ }
+ if (transfer.SemanticRecordCount == 0 && transfer.HasSourcePresentation)
+ return Failure<Step242PmiTransfer>("pmi-semantic-representation-missing", "Source has graphical annotations without a supported semantic representation; metric regeneration cannot be proved.");
+ return KernelResult<Step242PmiTransfer>.Success(transfer);
+ }
+ catch (PmiTransferException error) { return Failure<Step242PmiTransfer>("pmi-source-dependency-invalid", error.Message); }
+ }
+
+ internal KernelResult<bool> Emit(Step242TextWriter writer, BrepBody body, string shape, string representation,
+ string context, string millimetreUnit, string brep, IReadOnlyDictionary<FaceId, string> faces, IReadOnlyDictionary<EdgeId, string> edges,
+ out IReadOnlyDictionary<string, string> emittedDatums)
+ {
+ emittedDatums = new Dictionary<string, string>();
+ if (!Unchanged(body)) return Failure<bool>("pmi-source-body-changed", "Imported semantic PMI requires unchanged geometry and topology. Rebind annotations explicitly after editing, or request geometryOnly before editing.");
+ try
+ {
+ var mapping = new Dictionary<int, string>();
+ foreach (var face in body.Bindings.FaceBindings)
+ if (face.SourceStepEntityId is { } id && faces.TryGetValue(face.FaceId, out var target) && !mapping.TryAdd(id, target))
+ throw new PmiTransferException($"Source face #{id} has multiple descendants; annotation rebinding is not qualified for split topology.");
+ foreach (var edge in body.Bindings.EdgeBindings)
+ if (edge.SourceStepEntityId is { } id && edges.TryGetValue(edge.EdgeId, out var target) && !mapping.TryAdd(id, target))
+ throw new PmiTransferException($"Source edge #{id} has multiple descendants; annotation rebinding is not qualified for split topology.");
+ foreach (var id in selected)
+ {
+ var entity = entities[id];
+ if (Has(entity, "LENGTH_UNIT")) { mapping[id] = millimetreUnit; continue; }
+ if (Has(entity, "GLOBAL_UNIT_ASSIGNED_CONTEXT")) { mapping[id] = context; continue; }
+ if (IsProductShape(entity)) { mapping[id] = shape; continue; }
+ if (IsSolidRepresentation(entity)) { mapping[id] = representation; continue; }
+ if (entity.Name is "MANIFOLD_SOLID_BREP" or "BREP_WITH_VOIDS") { mapping[id] = brep; continue; }
+ if (entity.Name is "ADVANCED_FACE" or "EDGE_CURVE" && solidGeometry.Contains(id) && !mapping.ContainsKey(id))
+ throw new PmiTransferException($"Source geometry #{id} ({entity.Name}) has no proved topology correspondence.");
+ }
+ var copied = selected.Where(id => !mapping.ContainsKey(id)).Order().ToArray();
+ if (document.SourceMillimetresPerUnit != 1d && copied.Any(id => entities[id].Name == "PCURVE"))
+ throw new PmiTransferException("pmi-source-auxiliary-pcurve-units-unsupported: Auxiliary PMI surfaces carry non-metric pcurves whose length domains cannot yet be normalized safely.");
+ for (var i = 0; i < copied.Length; i++) mapping[copied[i]] = $"#{writer.EntityCount + i + 1}";
+ // Materialize everything before mutating the writer: a rejected transfer emits no partial graph.
+ var instances = copied.Select(id => Serialize(entities[id].Instance, mapping)).ToArray();
+ foreach (var instance in instances) writer.AddRawEntity(instance);
+ emittedDatums = datumEntities.ToDictionary(item => item.Key, item => mapping[item.Value], StringComparer.Ordinal);
+ IReadOnlyList<KernelDiagnostic> warnings = HasSourcePresentation ? [new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Warning,
+ "pmi-source-presentation-excluded: Semantic PMI, units and geometry associations were retained. Foreign graphical glyphs were excluded; regenerate metric labels from semantic PMI.", "Step242.Pmi")] : [];
+ return KernelResult<bool>.Success(true, warnings);
+ }
+ catch (PmiTransferException error) { return Failure<bool>("pmi-source-transfer-unsupported", error.Message); }
+ }
+
+ private bool Unchanged(BrepBody body) =>
+ witness.Topology.Vertices.SequenceEqual(body.Topology.Vertices) && witness.Topology.Edges.SequenceEqual(body.Topology.Edges)
+ && witness.Topology.Coedges.SequenceEqual(body.Topology.Coedges) && witness.Topology.Loops.SequenceEqual(body.Topology.Loops)
+ && witness.Topology.Faces.SequenceEqual(body.Topology.Faces) && witness.Topology.Shells.SequenceEqual(body.Topology.Shells)
+ && witness.Topology.Bodies.SequenceEqual(body.Topology.Bodies)
+ && witness.Geometry.Curves.SequenceEqual(body.Geometry.Curves) && witness.Geometry.Surfaces.SequenceEqual(body.Geometry.Surfaces)
+ && witness.Bindings.FaceBindings.SequenceEqual(body.Bindings.FaceBindings) && witness.Bindings.EdgeBindings.SequenceEqual(body.Bindings.EdgeBindings)
+ && witness.Bindings.PcurveBindings.SequenceEqual(body.Bindings.PcurveBindings)
+ && witness.Topology.Vertices.All(v => witness.TryGetVertexPoint(v.Id, out var before) == body.TryGetVertexPoint(v.Id, out var after) && before == after);
+
+ internal static Step242EntityConstructor? GeometricTolerance(Step242ParsedEntity entity) =>
+ Step242SubsetDecoder.TryGetConstructor(entity.Instance, "GEOMETRIC_TOLERANCE")
+ ?? (entity.Instance is Step242SimpleEntityInstance && entity.Name.EndsWith("_TOLERANCE", StringComparison.Ordinal)
+ && entity.Name != "PLUS_MINUS_TOLERANCE" ? entity.Instance.PrimaryConstructor : null);
+
+ internal static bool IsSemanticRoot(Step242ParsedEntity e) => GeometricTolerance(e) is not null
+ || Has(e, "DIMENSIONAL_SIZE") || Has(e, "DIMENSIONAL_LOCATION") || Has(e, "DATUM_FEATURE")
+ || e.Name is "DIMENSIONAL_SIZE" or "ANGULAR_SIZE" or "DIMENSIONAL_LOCATION" or "DIRECTED_DIMENSIONAL_LOCATION" or "ANGULAR_LOCATION" or "DATUM_FEATURE" or "DATUM_TARGET" or "PLACED_DATUM_TARGET_FEATURE" or "DATUM"
+ or "DATUM_SYSTEM" or "DATUM_REFERENCE" or "DATUM_REFERENCE_COMPARTMENT" or "DATUM_REFERENCE_ELEMENT"
+ || e.Name == "PROPERTY_DEFINITION" && e.Arguments.FirstOrDefault() is Step242StringValue name
+ && new[] { "diameter:", "dimension:", "note:" }.Any(prefix => name.Value.StartsWith(prefix, StringComparison.Ordinal))
+ // Compatibility with prior Aetheris exports: these named association aspects were
+ // separate from the property aspect. Preserve their explicit native identity receipt.
+ || e.Name == "SHAPE_ASPECT" && e.Arguments.FirstOrDefault() is Step242StringValue aspectName
+ && aspectName.Value.StartsWith("firmament-geometric-target:", StringComparison.Ordinal);
+ private static bool IsAssociation(Step242ParsedEntity e) => e.Name is
+ "SHAPE_ASPECT_RELATIONSHIP" or "SHAPE_ASPECT_DERIVING_RELATIONSHIP" or "GEOMETRIC_ITEM_SPECIFIC_USAGE"
+ or "DIMENSIONAL_CHARACTERISTIC_REPRESENTATION" or "PLUS_MINUS_TOLERANCE" or "TOLERANCE_ZONE"
+ or "TOLERANCE_ZONE_DEFINITION" or "PROJECTED_ZONE_DEFINITION" or "RUNOUT_ZONE_DEFINITION"
+ or "GEOMETRIC_TOLERANCE_RELATIONSHIP" or "PROPERTY_DEFINITION_REPRESENTATION" or "MEASURE_QUALIFICATION"
+ or "QUALIFIED_REPRESENTATION_ITEM" or "PROPERTY_DEFINITION" or "ID_ATTRIBUTE" or "NAME_ATTRIBUTE" or "DESCRIPTION_ATTRIBUTE"
+ or "FEATURE_FOR_DATUM_TARGET_RELATIONSHIP" or "SHAPE_DEFINITION_REPRESENTATION"
+ // Retain auxiliary face ownership so an importer cannot mistake a datum face for
+ // an orphan belonging to the material solid.
+ or "OPEN_SHELL" or "CLOSED_SHELL";
+ private static bool IsPresentation(Step242ParsedEntity e) => e.Name.Contains("ANNOTATION", StringComparison.Ordinal)
+ || e.Name.Contains("DRAUGHTING", StringComparison.Ordinal) || e.Name.Contains("PRESENTATION", StringComparison.Ordinal)
+ || e.Name is "STYLED_ITEM" or "OVER_RIDING_STYLED_ITEM" or "INVISIBILITY";
+ private bool IsSolidRepresentation(Step242ParsedEntity e) => solidRepresentations.Contains(e.Id);
+ private bool ContainsSolidDirectly(Step242ParsedEntity e) => e.Name is "SHAPE_REPRESENTATION" or "ADVANCED_BREP_SHAPE_REPRESENTATION"
+ && e.Arguments.ElementAtOrDefault(1) is Step242ListValue list
+ && list.Items.OfType<Step242EntityReference>().Any(r => entities.TryGetValue(r.TargetId, out var item) && item.Name is "MANIFOLD_SOLID_BREP" or "BREP_WITH_VOIDS");
+ // Auxiliary datum geometry may own separate products. Preserve those graphs; only the
+ // product that owns the exact solid is rebound to the output part.
+ private bool IsProductShape(Step242ParsedEntity e) => primaryProductShapes.Contains(e.Id);
+ private bool IsBoundary(Step242ParsedEntity e) => Has(e, "LENGTH_UNIT") || Has(e, "GLOBAL_UNIT_ASSIGNED_CONTEXT")
+ || e.Name is "ADVANCED_FACE" or "EDGE_CURVE" && solidGeometry.Contains(e.Id)
+ || e.Name is "MANIFOLD_SOLID_BREP" or "BREP_WITH_VOIDS" || IsProductShape(e) || IsSolidRepresentation(e);
+ private static bool Has(Step242ParsedEntity e, string kind) => Step242SubsetDecoder.TryGetConstructor(e.Instance, kind) is not null;
+ internal static IEnumerable<int> References(Step242EntityInstance instance) => Constructors(instance).SelectMany(c => c.Arguments).SelectMany(References);
+ private static IEnumerable<int> References(Step242Value value) => value switch
+ { Step242EntityReference r => [r.TargetId], Step242ListValue list => list.Items.SelectMany(References), Step242TypedValue typed => typed.Arguments.SelectMany(References), _ => [] };
+ private static IEnumerable<Step242EntityConstructor> Constructors(Step242EntityInstance instance) => instance is Step242ComplexEntityInstance complex ? complex.Constructors : [instance.PrimaryConstructor];
+
+ private string Serialize(Step242EntityInstance instance, Dictionary<int, string> mapping)
+ {
+ var constructors = Constructors(instance).Select(constructor => Serialize(constructor, mapping));
+ return instance is Step242ComplexEntityInstance ? "(" + string.Concat(constructors) + ")" : constructors.Single();
+ }
+ private string Serialize(Step242EntityConstructor constructor, Dictionary<int, string> mapping)
+ {
+ var arguments = constructor.Arguments.ToArray();
+ var unitIndex = constructor.Name == "MEASURE_REPRESENTATION_ITEM" ? 2 : 1;
+ var valueIndex = constructor.Name == "MEASURE_REPRESENTATION_ITEM" ? 1 : 0;
+ if ((constructor.Name.EndsWith("MEASURE_WITH_UNIT", StringComparison.Ordinal) || constructor.Name == "MEASURE_REPRESENTATION_ITEM")
+ && arguments.ElementAtOrDefault(unitIndex) is Step242EntityReference compoundUnit && entities.TryGetValue(compoundUnit.TargetId, out var compound)
+ && compound.Name == "DERIVED_UNIT")
+ {
+ if (!Step242LengthUnitNormalizer.TryResolvePmiScale(entities, compoundUnit.TargetId, [], out var compoundScale))
+ throw new PmiTransferException($"pmi-source-compound-unit-unsupported: Cannot resolve compound unit #{compoundUnit.TargetId}.");
+ if (compoundScale != 1d) arguments[valueIndex] = ScaleMeasure(arguments[valueIndex], compoundScale);
+ }
+ if (arguments.ElementAtOrDefault(valueIndex) is Step242TypedValue { Name: "LENGTH_MEASURE" or "POSITIVE_LENGTH_MEASURE" }
+ && (arguments.ElementAtOrDefault(unitIndex) is not Step242EntityReference declaredUnit || !entities.TryGetValue(declaredUnit.TargetId, out var declared) || !Has(declared, "LENGTH_UNIT")))
+ throw new PmiTransferException("Typed PMI length measure requires a resolvable named length unit.");
+ if (constructor.Name is "MEASURE_WITH_UNIT" or "LENGTH_MEASURE_WITH_UNIT" or "POSITIVE_LENGTH_MEASURE_WITH_UNIT" or "UNCERTAINTY_MEASURE_WITH_UNIT" or "MEASURE_REPRESENTATION_ITEM"
+ && arguments.ElementAtOrDefault(unitIndex) is Step242EntityReference unit && entities.TryGetValue(unit.TargetId, out var unitEntity) && Has(unitEntity, "LENGTH_UNIT"))
+ {
+ if (!Step242LengthUnitNormalizer.TryResolveMetresPerUnit(entities, unit.TargetId, [], out var metres))
+ throw new PmiTransferException($"Cannot resolve length unit #{unit.TargetId} for {constructor.Name}.");
+ arguments[valueIndex] = ScaleMeasure(arguments[valueIndex], metres * 1000d);
+ }
+ return constructor.Name + "(" + string.Join(",", arguments.Select(value => Serialize(value, mapping))) + ")";
+ }
+ private static Step242Value ScaleMeasure(Step242Value value, double scale) => value switch
+ {
+ Step242NumberValue n when double.IsFinite(n.Value * scale) => new Step242NumberValue(Step242LengthUnitNormalizer.ScalePmiMeasure(n.Value, scale)),
+ Step242TypedValue t when t.Name is "LENGTH_MEASURE" or "POSITIVE_LENGTH_MEASURE" or "AREA_MEASURE" or "VOLUME_MEASURE" && t.Arguments.Count == 1 => t with { Arguments = [ScaleMeasure(t.Arguments[0], scale)] },
+ _ => throw new PmiTransferException("Length-valued PMI measure is malformed or incompatible with its unit.")
+ };
+ private static string Serialize(Step242Value value, Dictionary<int, string> mapping) => value switch
+ {
+ Step242EntityReference r => mapping.TryGetValue(r.TargetId, out var id) ? id : throw new PmiTransferException($"Missing transfer mapping for #{r.TargetId}."),
+ Step242StringValue s => Step242TextWriter.String(s.Value),
+ Step242NumberValue n => n.Value.ToString("R", CultureInfo.InvariantCulture),
+ Step242EnumValue e => Step242TextWriter.Enum(e.Value),
+ Step242BooleanValue b => Step242TextWriter.BooleanLogical(b.Value),
+ Step242OmittedValue omitted => omitted.IsDerived ? "*" : "$",
+ Step242ListValue list => "(" + string.Join(",", list.Items.Select(item => Serialize(item, mapping))) + ")",
+ Step242TypedValue t => t.Name + "(" + string.Join(",", t.Arguments.Select(item => Serialize(item, mapping))) + ")",
+ _ => throw new PmiTransferException("Unsupported STEP annotation value.")
+ };
+ private sealed class PmiTransferException(string message) : Exception(message);
+ private static KernelResult<T> Failure<T>(string code, string message) => KernelResult<T>.Failure([new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, $"{code}: {message}", "Step242.Pmi")]);
+}
diff --git a/Aetheris.Kernel.Core/Step242/Step242SemanticPmi.cs b/Aetheris.Kernel.Core/Step242/Step242SemanticPmi.cs
index 83ee12ae..c75a6824 100644
--- a/Aetheris.Kernel.Core/Step242/Step242SemanticPmi.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242SemanticPmi.cs
@@ -44,4 +44,8 @@ public sealed record Step242SemanticPmiGeometricTolerance(
string ToleranceKind,
double Value,
IReadOnlyList<string> DatumReferences,
- int? Quantity = null) : Step242SemanticPmi(FeatureId);
+ int? Quantity = null) : Step242SemanticPmi(FeatureId)
+{
+ public IReadOnlyList<string> Modifiers { get; init; } = [];
+ public string? ZoneForm { get; init; }
+}
diff --git a/Aetheris.Kernel.Core/Step242/Step242SemanticPmiInspector.cs b/Aetheris.Kernel.Core/Step242/Step242SemanticPmiInspector.cs
index 9700d3b8..f0828061 100644
--- a/Aetheris.Kernel.Core/Step242/Step242SemanticPmiInspector.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242SemanticPmiInspector.cs
@@ -1,5 +1,10 @@
namespace Aetheris.Kernel.Core.Step242;
+public sealed record Step242PmiDatumFrame(int Precedence, IReadOnlyList<string> Labels, IReadOnlyList<string> Modifiers)
+{
+ public bool PresentationSupported { get; init; } = true;
+}
+
public sealed record Step242SemanticPmiInspectionItem(
int EntityId,
string Kind,
@@ -13,9 +18,17 @@ public sealed record Step242SemanticPmiInspectionItem(
string? Text)
{
public IReadOnlyList<int> GeometricFaceEntityIds { get; init; } = [];
+ /// <summary>Direct AP242 usage items, including edges, solid bodies and auxiliary datum geometry.
+ /// Face adjacency is a separate presentation projection, not the source association identity.</summary>
+ public IReadOnlyList<int> GeometricItemEntityIds { get; init; } = [];
public string? DimensionKind { get; init; }
public string? AuthoredName { get; init; }
public double? Depth { get; init; }
+ public IReadOnlyList<string> Modifiers { get; init; } = [];
+ public IReadOnlyList<Step242PmiDatumFrame> DatumReferenceFrames { get; init; } = [];
+ public IReadOnlyList<string> ZoneForms { get; init; } = [];
+ public string ValueUnit { get; init; } = "mm";
+ public bool PresentationSupported { get; init; } = true;
}
public sealed record Step242SemanticPmiInspectionResult(
@@ -25,7 +38,7 @@ public sealed record Step242SemanticPmiInspectionResult(
{
public int DatumCount => Items.Count(item => item.Kind == "Datum");
public int DimensionCount => Items.Count(item => item.Kind is "Diameter" or "Dimension");
- public int GeometricToleranceCount => Items.Count(item => item.Kind == "Position");
+ public int GeometricToleranceCount => Items.Count(item => Step242GeometricToleranceKinds.Find(item.Kind) is not null || item.Kind == "GeometricTolerance");
public int AnnotationCount => Items.Count(item => item.Kind == "Annotation");
}
@@ -43,7 +56,8 @@ public static class Step242SemanticPmiInspector
var document = parsed.Value;
var entities = document.Entities.ToDictionary(entity => entity.Id);
- var representations = BuildRepresentations(document, entities);
+ var schemaReader = new Step242ForeignPmiReader(document);
+ var representations = BuildRepresentations(document, entities, schemaReader);
var aspectTargets = BuildAspectTargets(document);
var geometricAssociations = BuildGeometricAssociations(document, aspectTargets);
var quantities = BuildQuantities(document);
@@ -111,15 +125,26 @@ public static class Step242SemanticPmiInspector
items.Add(new(entity.Id, "Position", name, target, magnitude, null, null, Quantity(quantities, target), datumReferences, null));
}
- return new(true, items.OrderBy(item => item.EntityId).Select(item => item with
+ var native = items.Select(item => item with
{
- GeometricFaceEntityIds = geometricAssociations.GetValueOrDefault(item.Target) ?? []
- }).ToArray(), []);
+ GeometricFaceEntityIds = geometricAssociations.GetValueOrDefault(item.Target) ?? [],
+ GeometricItemEntityIds = geometricAssociations.GetValueOrDefault(item.Target) ?? []
+ }).ToArray();
+ var foreign = schemaReader.Read(native.Where(i => i.Kind != "Position").ToArray());
+ var positions = foreign.Where(i => i.Kind == "Position").ToDictionary(i => i.EntityId);
+ var combined = native.Select(item => positions.TryGetValue(item.EntityId, out var detailed) ? item with
+ { Modifiers = detailed.Modifiers, DatumReferenceFrames = detailed.DatumReferenceFrames, DatumReferences = detailed.DatumReferences, ZoneForms = detailed.ZoneForms,
+ Target = item.Target.Length > 0 ? item.Target : detailed.Target,
+ Value = detailed.Value,
+ PresentationSupported = detailed.PresentationSupported,
+ GeometricItemEntityIds = detailed.GeometricItemEntityIds,
+ GeometricFaceEntityIds = detailed.GeometricFaceEntityIds.Count > 0 ? detailed.GeometricFaceEntityIds : item.GeometricFaceEntityIds } : item);
+ return new(true, combined.Concat(foreign.Where(item => native.All(n => n.EntityId != item.EntityId))).OrderBy(item => item.EntityId).ToArray(), []);
}
private static Dictionary<string, IReadOnlyList<double>> BuildRepresentations(
Step242ParsedDocument document,
- IReadOnlyDictionary<int, Step242ParsedEntity> entities)
+ IReadOnlyDictionary<int, Step242ParsedEntity> entities, Step242ForeignPmiReader measures)
{
var result = new Dictionary<string, IReadOnlyList<double>>(StringComparer.Ordinal);
foreach (var entity in document.Entities)
@@ -130,7 +155,7 @@ public static class Step242SemanticPmiInspector
continue;
result[name] = list.Items.OfType<Step242EntityReference>()
.Where(reference => entities.ContainsKey(reference.TargetId))
- .Select(reference => FirstNumber(entities[reference.TargetId].Instance))
+ .Select(reference => measures.Measure(reference.TargetId))
.Where(value => value.HasValue)
.Select(value => value!.Value)
.ToArray();
@@ -146,7 +171,7 @@ public static class Step242SemanticPmiInspector
var constructor = Step242SubsetDecoder.TryGetConstructor(entity.Instance, "SHAPE_ASPECT")
?? Step242SubsetDecoder.TryGetConstructor(entity.Instance, "COMPOSITE_SHAPE_ASPECT")
?? Step242SubsetDecoder.TryGetConstructor(entity.Instance, "DATUM_FEATURE");
- if (constructor is not null) result[entity.Id] = Target(String(constructor, 1));
+ if (constructor is not null && Target(String(constructor, 1)) is { Length: > 0 } target) result[entity.Id] = target;
}
return result;
}
diff --git a/Aetheris.Kernel.Core/Step242/Step242SubsetParser.cs b/Aetheris.Kernel.Core/Step242/Step242SubsetParser.cs
index 9b9243e0..40239647 100644
--- a/Aetheris.Kernel.Core/Step242/Step242SubsetParser.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242SubsetParser.cs
@@ -359,7 +359,7 @@ internal static class Step242SubsetParser
private Step242Value ReadDerivedOmitted()
{
Expect('*');
- return Step242OmittedValue.Instance;
+ return Step242OmittedValue.Derived;
}
private Step242Value ReadList()
@@ -661,7 +661,7 @@ internal sealed class Step242ParsedDocument
return 1d;
}
- private bool TryResolvePlaneAngleUnitScale(int unitEntityId, HashSet<int> visited, out double scale)
+ internal bool TryResolvePlaneAngleUnitScale(int unitEntityId, HashSet<int> visited, out double scale)
{
scale = default;
if (!visited.Add(unitEntityId) || !_entitiesById.TryGetValue(unitEntityId, out var unitEntity))
@@ -753,5 +753,7 @@ internal sealed record Step242TypedValue(string Name, IReadOnlyList<Step242Value
internal sealed record Step242OmittedValue : Step242Value
{
+ public bool IsDerived { get; init; }
public static Step242OmittedValue Instance { get; } = new();
+ public static Step242OmittedValue Derived { get; } = new() { IsDerived = true };
}
diff --git a/Aetheris.Kernel.Core/Step242/Step242TextWriter.cs b/Aetheris.Kernel.Core/Step242/Step242TextWriter.cs
index e2498993..79bdf790 100644
--- a/Aetheris.Kernel.Core/Step242/Step242TextWriter.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242TextWriter.cs
@@ -6,6 +6,7 @@ namespace Aetheris.Kernel.Core.Step242;
internal sealed class Step242TextWriter
{
private readonly List<string> _entities = [];
+ internal int EntityCount => _entities.Count;
// Export-local, exact serialized equality: no tolerance matching or topology coalescing.
// Names and references participate in the key; child geometry is interned first.
private readonly Dictionary<string, string> _immutableGeometry = new(StringComparer.Ordinal);
@@ -70,6 +71,7 @@ internal sealed class Step242TextWriter
// Thirteen fractional digits keep exported geometry well below kernel tolerances while
// suppressing the final-bit libm variation that can otherwise change STEP bytes by OS.
public static string Number(double value) => value.ToString("0.#############", CultureInfo.InvariantCulture);
+ internal static string PmiNumber(double value) => value.ToString("R", CultureInfo.InvariantCulture);
public static string BooleanLogical(bool value) => value ? ".T." : ".F.";
diff --git a/Aetheris.Kernel.Firmament.Tests/ExplicitGdtTests.cs b/Aetheris.Kernel.Firmament.Tests/ExplicitGdtTests.cs
new file mode 100644
index 00000000..197ef480
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/ExplicitGdtTests.cs
@@ -0,0 +1,110 @@
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.Visualization;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class ExplicitGdtTests
+{
+ private static string Fixture(string relative)
+ {
+ var directory = new DirectoryInfo(AppContext.BaseDirectory);
+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;
+ return Path.Combine(directory!.FullName, relative);
+ }
+ private static string Source() => File.ReadAllText(Fixture("fixtures/Canonical/PMI/explicit-gdt.firmament"));
+ [Fact]
+ public void ImportedNistPmiSurvivesAndAuthoredControlReusesItsExistingDatums()
+ {
+ var path = Fixture("fixtures/Canonical/PMI/nist-ctc01-passthrough.firmament");
+ var build = FirmamentBuildAndExport.CompileSource(File.ReadAllText(path), Path.GetDirectoryName(path));
+ Assert.True(build.IsSuccess, string.Join(";", build.Diagnostics.Select(d => d.Message)));
+ var inspection = Step242SemanticPmiInspector.Inspect(build.Value.StepText);
+ // CTC-01 has four complex controls and two simple inherited tolerance entities.
+ Assert.Equal(3, inspection.DatumCount); Assert.Equal(12, inspection.DimensionCount); Assert.Equal(7, inspection.GeometricToleranceCount);
+ var added = Assert.Single(inspection.Items, i => i.Name == "RevisionProfile");
+ Assert.Equal(new[] { "A", "B" }, added.DatumReferences); Assert.Equal(.1, added.Value);
+ Assert.NotEmpty(added.GeometricFaceEntityIds); Assert.Contains("FREE_STATE", added.Modifiers);
+ }
+ [Fact]
+ public void UnqualifiedImportedGeometryRemainsRejectedIndependentlyOfAuthoredPmi()
+ {
+ var path = Fixture("fixtures/Invalid/InlineStep/nist-ftc11-pmi-unqualified-geometry.invalid.firmfixture");
+ var source = File.ReadAllText(path);
+ foreach (var specimen in new[] { source, source[..source.IndexOf(" Pmi {", StringComparison.Ordinal)] + "}" })
+ {
+ var build = FirmamentBuildAndExport.CompileSource(specimen, Path.GetDirectoryName(path));
+ Assert.False(build.IsSuccess); Assert.Contains(build.Diagnostics, d => d.Message.Contains("firmament-inline-step-import-unqualified"));
+ }
+ }
+ [Fact]
+ public void ExplicitControlsBuildWithoutRequirementsAndPreserveGeometryAndFaceAssociations()
+ {
+ var source = Source();
+ var build = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(build.IsSuccess, string.Join(";", build.Diagnostics.Select(d => d.Message)));
+ var inspection = Step242SemanticPmiInspector.Inspect(build.Value.StepText);
+ Assert.True(inspection.Success); Assert.Equal(3, inspection.DatumCount); Assert.Equal(3, inspection.GeometricToleranceCount);
+ var flatness = Assert.Single(inspection.Items, i => i.Kind == "Flatness"); Assert.Equal(.03, flatness.Value);
+ var position = Assert.Single(inspection.Items, i => i.Kind == "Position");
+ Assert.Equal(.0254, position.Value); Assert.Equal(new[] { "A", "B", "C" }, position.DatumReferences);
+ Assert.Contains("MAXIMUM_MATERIAL_REQUIREMENT", position.Modifiers);
+ Assert.Equal(new[] { "cylindrical or circular" }, position.ZoneForms);
+ Assert.All(inspection.Items, i => Assert.NotEmpty(i.GeometricFaceEntityIds));
+ var withoutPmi = source[..source.IndexOf(" Pmi {", StringComparison.Ordinal)] + "}";
+ var baseline = FirmamentBuildAndExport.CompileSource(withoutPmi);
+ Assert.True(baseline.IsSuccess);
+ var body = Step242Importer.ImportBody(build.Value.StepText).Value;
+ var original = Step242Importer.ImportBody(baseline.Value.StepText).Value;
+ Assert.Equal(Step242Exporter.ExportBody(original).Value, Step242Exporter.ExportBody(body).Value);
+ Assert.Equal(6, PmiDisplayProjection.FromStep(build.Value.StepText).Count);
+ }
+ [Theory]
+ [InlineData("Flatness", false)] [InlineData("Straightness", false)] [InlineData("Roundness", false)] [InlineData("Cylindricity", false)]
+ [InlineData("Parallelism", true)] [InlineData("Perpendicularity", true)] [InlineData("Angularity", true)]
+ [InlineData("Position", true)] [InlineData("LineProfile", true)] [InlineData("SurfaceProfile", true)]
+ [InlineData("CircularRunout", true)] [InlineData("TotalRunout", true)]
+ public void EveryAdmittedControlHasSemanticReadback(string kind, bool datums)
+ {
+ var source = Source(); var start = source.IndexOf(" Flatness", StringComparison.Ordinal);
+ var target = kind is "Roundness" or "Cylindricity" or "CircularRunout" or "TotalRunout" or "Position" ? "face(Mount.Wall)" : "face(+Z)";
+ source = source[..start] + $" {kind} Control {{ target: {target} tolerance: 0.0254mm {(datums ? "datumRefs: [A, B, C]" : "")} }}\n }}\n}}";
+ var build = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(build.IsSuccess, string.Join(";", build.Diagnostics.Select(d => d.Message)));
+ var control = Assert.Single(Step242SemanticPmiInspector.Inspect(build.Value.StepText).Items, i => i.Kind == kind);
+ Assert.Equal(.0254, control.Value); Assert.NotEmpty(control.GeometricFaceEntityIds);
+ Assert.Equal(datums ? new[] { "A", "B", "C" } : [], control.DatumReferences);
+ }
+ [Theory]
+ [InlineData("datumRefs: [A, B, C]", "datumRefs: [A, Missing]", "pmi-unknown-datum")]
+ [InlineData("datumRefs: [A, B, C]", "datumRefs: [A, A]", "pmi-datum-precedence-invalid")]
+ [InlineData("modifiers: [MaximumMaterial]", "modifiers: [MaximumMaterial, LeastMaterial]", "pmi-modifier-invalid")]
+ [InlineData("tolerance: 0.0254mm", "tolerance: 0.001in", "pmi-tolerance")]
+ [InlineData("target: face(+Z) tolerance: 0.03mm", "target: face(+Z) tolerance: 0.01mm datumRefs: [A]", "pmi-datum-not-applicable")]
+ public void InvalidControlsRejectAdmission(string from, string to, string code)
+ {
+ var source = Source().Replace(from, to, StringComparison.Ordinal);
+ var parsed = FirmamentV2Parser.Parse(source);
+ Assert.False(parsed.IsSuccess); Assert.Contains(parsed.Diagnostics, d => d.Contains(code, StringComparison.Ordinal));
+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ }
+ [Fact]
+ public void NumericalPrecisionWitnessDoesNotRoundATinyToleranceToZero()
+ {
+ // Precision qualification only, not a proposed manufacturing specification.
+ var build = FirmamentBuildAndExport.CompileSource(Source().Replace("tolerance: 0.03mm", "tolerance: 0.00000000000000001mm", StringComparison.Ordinal));
+ Assert.True(build.IsSuccess, string.Join(";", build.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(1e-17, Assert.Single(Step242SemanticPmiInspector.Inspect(build.Value.StepText).Items, i => i.Kind == "Flatness").Value);
+ }
+ [Theory]
+ [InlineData("Cylindrical", "Ø0.0254")]
+ [InlineData("Spherical", "SØ0.0254")]
+ [InlineData("BetweenSurfaces", "BetweenSurfaces 0.0254")]
+ public void EveryAuthoredZoneFormSurvivesPresentation(string zone, string text)
+ {
+ var build = FirmamentBuildAndExport.CompileSource(Source().Replace("zone: Cylindrical", "zone: " + zone, StringComparison.Ordinal));
+ Assert.True(build.IsSuccess, string.Join(";", build.Diagnostics.Select(d => d.Message)));
+ var label = Assert.Single(PmiDisplayProjection.FromStep(build.Value.StepText), item => item.Kind == "Position");
+ Assert.Contains(text, label.Text);
+ }
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2ParserTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2ParserTests.cs
index 5a9f2e8f..31d1e5b2 100644
--- a/Aetheris.Kernel.Firmament.Tests/FirmamentV2ParserTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2ParserTests.cs
@@ -947,20 +947,20 @@ model:
}
[Fact]
- public void FirmamentV2P2_ExportDeferredFlatness_IsReportedAndBuildRejectedDeterministically()
+ public void FirmamentV2_ImportedFlatness_IsAdmittedAndEmitted()
{
- var fixture = FixturePath("Compatibility/LegacyAliases/Invalid/InlineStep/inline-step-v2-record-pmi-export-deferred-flatness.invalid.firmfixture");
- var parse = FirmamentV2Parser.Parse(Source("Compatibility/LegacyAliases/Invalid/InlineStep/inline-step-v2-record-pmi-export-deferred-flatness.invalid.firmfixture"), Path.GetDirectoryName(fixture));
+ var fixture = FixturePath("Compatibility/LegacyAliases/Valid/InlineStep/inline-step-v2-record-pmi-flatness.valid.firmfixture");
+ var parse = FirmamentV2Parser.Parse(Source("Compatibility/LegacyAliases/Valid/InlineStep/inline-step-v2-record-pmi-flatness.valid.firmfixture"), Path.GetDirectoryName(fixture));
var report = FirmamentV2ValidationReportBuilder.Build(parse, fixture);
var pmi = Assert.Single(report.Pmi);
Assert.Equal("flatness", pmi.Kind);
- Assert.Equal("deferred", pmi.ExportSupport);
- Assert.Equal("export-deferred", pmi.Status);
+ Assert.Equal("supported", pmi.ExportSupport);
+ Assert.Equal("valid", pmi.Status);
- var build = FirmamentBuildAndExport.Run(fixture, Path.Combine(Path.GetTempPath(), "aetheris-flatness-deferred.step"));
- Assert.False(build.IsSuccess);
- Assert.Contains(build.Diagnostics, d => d.Message.Contains("firmament-v2-pmi-export-deferred", StringComparison.Ordinal));
+ var build = FirmamentBuildAndExport.CompileSource(Source("Compatibility/LegacyAliases/Valid/InlineStep/inline-step-v2-record-pmi-flatness.valid.firmfixture"), Path.GetDirectoryName(fixture));
+ Assert.True(build.IsSuccess, string.Join(";", build.Diagnostics.Select(d => d.Message)));
+ Assert.Contains(Aetheris.Kernel.Core.Step242.Step242SemanticPmiInspector.Inspect(build.Value.StepText).Items, item => item.Kind == "Flatness");
}
[Fact]
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2ValidationReportTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2ValidationReportTests.cs
index 470a29db..b5b22eff 100644
--- a/Aetheris.Kernel.Firmament.Tests/FirmamentV2ValidationReportTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2ValidationReportTests.cs
@@ -15,14 +15,14 @@ public sealed class FirmamentV2ValidationReportTests
Assert.Equal(2, report.Summary.ConceptCount);
Assert.Equal(2, report.Summary.ValidConceptCount);
Assert.Equal(5, report.Summary.PmiRecordCount);
- Assert.Equal(2, report.Summary.ExportSupportedPmiCount);
- Assert.Equal(3, report.Summary.ExportDeferredPmiCount);
+ Assert.Equal(4, report.Summary.ExportSupportedPmiCount);
+ Assert.Equal(1, report.Summary.ExportDeferredPmiCount);
Assert.Equal(0, report.Summary.FatalDiagnosticCount);
Assert.Contains(report.Lets, l => l.Name == "MountingPattern.holeDiameter" && l.Tolerance is { Kind: "bilateral" });
Assert.Contains(report.Concepts, c => c.Kind == "feature" && c.Name == "mountHole" && c.Status == "valid" && c.Fields.Any(f => f.Name == "diameter" && f.HasTolerance));
Assert.Contains(report.Pmi, p => p.Name == "mountHoleDiameter" && p.ExportSupport == "supported" && p.Dimension?.Tolerance is not null);
- Assert.Contains(report.Pmi, p => p.Name == "baseFlatness" && p.ExportSupport == "deferred");
- Assert.Contains(report.Pmi, p => p.Name == "topParallel" && p.ExportSupport == "deferred" && p.DatumRefs.Contains("A"));
+ Assert.Contains(report.Pmi, p => p.Name == "baseFlatness" && p.ExportSupport == "supported");
+ Assert.Contains(report.Pmi, p => p.Name == "topParallel" && p.ExportSupport == "supported" && p.DatumRefs.Contains("A"));
Assert.Contains(report.Diagnostics, d => d.Code == FirmamentV2Parser.ToleranceDroppedThroughArithmetic && d.Severity == "warning");
}
@@ -101,14 +101,14 @@ public sealed class FirmamentV2ValidationReportTests
}
[Fact]
- public void ForgeCsA4_ConceptPmiObligation_MissingWarningDoesNotOverrideDeferredExportStatus()
+ public void ForgeCsA4_ConceptPmiObligation_MissingWarningDoesNotInvalidateSupportedGdt()
{
var report = Report("Regression/Language/valid/concept-pmi-obligation-with-deferred-export.valid.firmfixture");
- Assert.Equal("valid-with-deferred-export", report.Status);
+ Assert.Equal("valid", report.Status);
Assert.Single(report.ConceptPmiObligations, obligation => obligation.Status == "missing");
Assert.Contains(report.Diagnostics, d => d.Code == "forge.pmi.obligation.missing" && d.Severity == "warning");
- Assert.Contains(report.Pmi, p => p.ExportSupport == "deferred");
+ Assert.All(report.Pmi, p => Assert.Equal("supported", p.ExportSupport));
}
[Fact]
diff --git a/Aetheris.Kernel.Firmament.Tests/ImportedPartPmiTests.cs b/Aetheris.Kernel.Firmament.Tests/ImportedPartPmiTests.cs
index 436f4c2b..07ea4846 100644
--- a/Aetheris.Kernel.Firmament.Tests/ImportedPartPmiTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/ImportedPartPmiTests.cs
@@ -48,15 +48,18 @@ public sealed class ImportedPartPmiTests
Assert.Contains(built.Diagnostics, d => d.Message.Contains("imported-pmi-target-kind"));
}
[Fact]
- public void ExistingImportedAnnotations_AreRejectedInsteadOfSilentlyStripped()
+ public void ExistingImportedAnnotations_ArePreservedWithTheirTargets()
{
var built = FirmamentBuildAndExport.CompileSource(Source(), Path.Combine(Repo(), "fixtures/Regression/ImportedPartPmi"));
Assert.True(built.IsSuccess);
var source = Source().Replace("../../../testdata/firmament/inline-step/canonical-through-hole.step", "annotated.step");
source = source[..source.IndexOf(" Pmi {", StringComparison.Ordinal)] + "}";
var imported = FirmamentBuildAndExport.CompileSource(source, resources: new Dictionary<string, string> { ["annotated.step"] = built.Value.StepText });
- Assert.False(imported.IsSuccess);
- Assert.Contains(imported.Diagnostics, d => d.Message.Contains("existing-pmi-unsupported"));
+ Assert.True(imported.IsSuccess, string.Join(";", imported.Diagnostics.Select(d => d.Message)));
+ var before = Step242SemanticPmiInspector.Inspect(built.Value.StepText);
+ var after = Step242SemanticPmiInspector.Inspect(imported.Value.StepText);
+ Assert.Equal(before.DatumCount, after.DatumCount); Assert.Equal(before.DimensionCount, after.DimensionCount);
+ Assert.All(after.Items, annotation => Assert.NotEmpty(annotation.GeometricFaceEntityIds));
}
[Fact]
public void ImportedTopology_UsesProvenanceRatherThanEntityLineOrder()
diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyModuleMaterialization.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyModuleMaterialization.cs
index edff09f2..d2274dac 100644
--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyModuleMaterialization.cs
+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyModuleMaterialization.cs
@@ -35,6 +35,11 @@ internal static partial class AssemblyDefinitionMaterializer
if (reference.Module is null)
{
var text = graph.Asset(reference.Path);
+ if (!reference.GeometryOnly && ImportedStepSemantics.HasAnnotations(text))
+ {
+ diagnostics.Add(new("firmament-step-source-pmi-unsupported", "Imported part PMI is not promoted into an assembly. Use geometryOnly: true explicitly, or re-export the annotated part separately.") { SourceSpan = reference.Origin });
+ return null;
+ }
var imported = reference.ImportedBody is { } retained
? Aetheris.Kernel.Core.Results.KernelResult<Aetheris.Kernel.Core.Brep.BrepBody>.Success(retained.Clone()) : Step242Importer.ImportBody(text);
if (!imported.IsSuccess)
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
index b0fa346c..608fc542 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
@@ -233,18 +233,32 @@ public static partial class FirmamentBuildAndExport
private static KernelResult<bool> VerifyV2PmiExportParity(string source, string? sourceDirectory, FirmamentStepExportResult export,
IReadOnlyDictionary<string, string>? resources = null)
{
- var parsed = FirmamentV2Parser.Parse(source, sourceDirectory, null, null, resources);
- if (!parsed.IsSuccess || parsed.Document is null) return KernelResult<bool>.Success(true);
- var pmi = parsed.Document.Pmi ?? [];
- if (pmi.Count == 0 && export.GeneratedSemanticPmi.Count == 0) return KernelResult<bool>.Success(true);
+ var document = export.RuntimeAdmissionDocument;
+ if (document is null)
+ {
+ var parsed = FirmamentV2Parser.Parse(source, sourceDirectory, null, null, resources);
+ if (!parsed.IsSuccess || parsed.Document is null) return KernelResult<bool>.Success(true);
+ document = parsed.Document;
+ }
+ var pmi = document.Pmi ?? [];
+ if (pmi.Count == 0 && export.GeneratedSemanticPmi.Count == 0 && !document.Solids.Any(s => s.InlineStep is { GeometryOnly: false })) return KernelResult<bool>.Success(true);
- var support = ValidateV2PmiExportSupport(parsed.Document);
+ var support = ValidateV2PmiExportSupport(document);
if (!support.IsSuccess) return support;
var expectedDatums = pmi.Count(record => record.Kind == FirmamentV2PmiKind.DatumPlane) + export.GeneratedSemanticPmi.OfType<Step242SemanticPmiDatum>().Count();
var expectedDiameters = pmi.Count(record => record.Kind == FirmamentV2PmiKind.HoleDiameter) + export.GeneratedSemanticPmi.OfType<Step242SemanticPmiHole>().Count();
+ var expectedControls = pmi.Count(record => Step242GeometricToleranceKinds.Find(record.Kind.ToString()) is not null)
+ + export.GeneratedSemanticPmi.OfType<Step242SemanticPmiGeometricTolerance>().Count();
+ foreach (var imported in document.Solids.Select(s => s.InlineStep).OfType<FirmamentV2InlineStepRecord>().Where(s => !s.GeometryOnly))
+ {
+ var original = Step242SemanticPmiInspector.Inspect(imported.SourceText ?? File.ReadAllText(imported.NormalizedPath, Encoding.UTF8));
+ if (!original.Success) return KernelResult<bool>.Failure([new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,
+ "firmament-v2-pmi-source-inspection-failed: Cannot verify imported PMI parity.", "FirmamentV2.PmiExportParity")]);
+ expectedDatums += original.DatumCount; expectedDiameters += original.DimensionCount; expectedControls += original.GeometricToleranceCount;
+ }
var inspection = Step242SemanticPmiInspector.Inspect(export.StepText);
- if (inspection.Success && inspection.DatumCount == expectedDatums && inspection.DimensionCount == expectedDiameters)
+ if (inspection.Success && inspection.DatumCount == expectedDatums && inspection.DimensionCount == expectedDiameters && inspection.GeometricToleranceCount == expectedControls)
return KernelResult<bool>.Success(true);
var actualDatums = inspection.Success ? inspection.DatumCount : 0;
@@ -253,7 +267,7 @@ public static partial class FirmamentBuildAndExport
return KernelResult<bool>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(
Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed,
Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
- $"firmament-v2-pmi-export-evidence-mismatch: validation admitted {expectedDatums} datum and {expectedDiameters} diameter PMI records, but AP242 reinspection found {actualDatums} datum and {actualDiameters} diameter records.{detail}",
+ $"firmament-v2-pmi-export-evidence-mismatch: validation admitted {expectedDatums} datum, {expectedDiameters} dimension and {expectedControls} geometric-control records; AP242 reinspection found {actualDatums} datum, {actualDiameters} dimension and {inspection.GeometricToleranceCount} geometric-control records.{detail}",
"FirmamentV2.PmiExportParity")]);
}
@@ -2342,9 +2356,6 @@ public static partial class FirmamentBuildAndExport
}
var stepText = inlineStep.SourceText ?? File.ReadAllText(inlineStep.NormalizedPath, Encoding.UTF8);
- if (!inlineStep.GeometryOnly && (!inlineStep.CanonicalInput || ImportedStepSemantics.HasAnnotations(stepText)))
- return KernelResult<FirmamentStepExportResult>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed,
- KernelDiagnosticSeverity.Error, "firmament-v2-inline-step-existing-pmi-unsupported: Source annotation passthrough is not qualified for this STEP. Use the original Firmament/Helios workspace, or explicitly request geometryOnly: true to exclude imported annotations without changing the original file.", "FirmamentV2.InlineStep")]);
var import = inlineStep.RuntimeBody is { } admitted ? KernelResult<BrepBody>.Success(admitted.Clone()) : Step242Importer.ImportBody(stepText);
if (!import.IsSuccess)
{
@@ -2361,12 +2372,25 @@ public static partial class FirmamentBuildAndExport
}
var semanticPmi = BuildV2SemanticPmi(document, [], solid.Name, body: import.Value);
+ Step242PmiTransfer? importedPmi = null;
+ if (!inlineStep.GeometryOnly && ImportedStepSemantics.HasAnnotations(stepText))
+ {
+ var original = Step242SemanticPmiInspector.Inspect(stepText);
+ var declared = (document.Pmi ?? []).Select(p => p.Name).ToHashSet(StringComparer.Ordinal);
+ if (original.Items.Any(item => declared.Contains(item.AuthoredName ?? item.Name)))
+ return KernelResult<FirmamentStepExportResult>.Failure([new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,
+ "firmament-v2-pmi-source-name-conflict: Authored PMI names must be distinct from retained source annotation names.", "FirmamentV2.Pmi")]);
+ var transfer = Step242PmiTransfer.Read(stepText, import.Value);
+ if (!transfer.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(transfer.Diagnostics);
+ importedPmi = transfer.Value;
+ }
var targetValidation = ValidateImportedPmiTargets(semanticPmi, import.Value);
if (!targetValidation.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(targetValidation.Diagnostics);
var export = Step242Exporter.ExportBody(import.Value, semanticPmi, new Step242ExportOptions
{
ProductName = solid.Name,
ApplicationName = "Aetheris.Firmament.InlineStep",
+ ImportedPmi = importedPmi,
BrepExportPreflightMode = inlineStep.SourceHashPin is null ? BrepExportPreflightMode.Audit : BrepExportPreflightMode.Enforce,
ImportedRecoveryToleranceMillimetres = inlineStep.ImportToleranceMillimetres ?? .001
});
@@ -2388,7 +2412,7 @@ public static partial class FirmamentBuildAndExport
InlineStepReplacementAssist: InlineStepReplacementAssistReportBuilder.Build(document))
{ RuntimeBody = import.Value, RuntimeBodySourceName = solid.Name, RuntimeAdmissionDocument = document },
inlineStep.GeometryOnly ? [new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Warning,
- "firmament-inline-step-source-semantics-excluded: geometryOnly explicitly excludes source annotations; geometry remains unchanged.", "FirmamentV2.InlineStep")] : []);
+ "firmament-inline-step-source-semantics-excluded: geometryOnly explicitly excludes source annotations; geometry remains unchanged.", "FirmamentV2.InlineStep")] : export.Diagnostics);
}
private static KernelResult<FirmamentStepExportResult>? TryExportV2ControlledSideHoleBody(FirmamentV2Document document)
@@ -2833,8 +2857,8 @@ public static partial class FirmamentBuildAndExport
// owner. A supported record kind does not imply every requested field exports.
internal static KernelDiagnostic? V2PmiExportRejection(FirmamentV2PmiKind kind, string name, FirmamentV2BoundPmiRecord? bound)
{
- var message = kind is not (FirmamentV2PmiKind.DatumPlane or FirmamentV2PmiKind.HoleDiameter)
- ? $"firmament-v2-pmi-export-deferred: AP242 export for PMI record '{name}' ({kind.ToString().ToLowerInvariant()}) is deferred; supported export records are datum and diameter."
+ var message = kind is not (FirmamentV2PmiKind.DatumPlane or FirmamentV2PmiKind.HoleDiameter) && Step242GeometricToleranceKinds.Find(kind.ToString()) is null
+ ? $"firmament-v2-pmi-export-deferred: AP242 export for PMI record '{name}' ({kind.ToString().ToLowerInvariant()}) is deferred; use Datum, HoleDiameter or an admitted geometric control."
: kind == FirmamentV2PmiKind.HoleDiameter && bound?.DatumRefs.Count > 0
? $"firmament-v2-pmi-datum-reference-export-unsupported: HoleDiameter '{name}' requests datum references that native size export cannot preserve. Export Datum separately; datum-referenced geometric controls require a qualified PMI capability."
: null;
@@ -2900,6 +2924,16 @@ public static partial class FirmamentBuildAndExport
var selector = TryResolveV2RecognizedRegionTarget(document, targetBinding, pmi.Target, out var recognizedDatumTarget) ? recognizedDatumTarget : ResolveV2DatumTarget(targetBinding, pmi.Target);
result.Add(new Step242SemanticPmiDatum(targetSolid, "plane", pmi.Name, selector));
}
+ else if (Step242GeometricToleranceKinds.Find(pmi.Kind.ToString()) is { } control && boundPmiByName.TryGetValue(pmi.Name, out var boundControl))
+ {
+ var feature = holeByName.TryGetValue(pmi.Target, out var hole) ? hole.FeatureId
+ : boundControl.HoleWallTarget is { } wall && holeByName.TryGetValue(wall.HoleName, out var wallFeature) ? wallFeature.FeatureId
+ : explicitFeatureIds?.GetValueOrDefault(pmi.Target) ?? $"{targetSolid}.{pmi.Name}";
+ var faces = body is not null && FirmamentSelectorResolver.ResolveUniquePlanarFace(body, ResolveV2DatumTarget(targetBinding, pmi.Target)) is { Count: > 0 } planarFaces
+ ? planarFaces.Select(id => id.Value).ToArray() : Array.Empty<int>();
+ result.Add(new Step242SemanticPmiGeometricTolerance(feature, pmi.Name, control.Name, boundControl.ControlTolerance!.NumericValue!.Value, boundControl.DatumRefs)
+ { Modifiers = boundControl.Modifiers, ZoneForm = boundControl.ZoneForm, GeometricFaceIds = faces });
+ }
}
return result.Select(item => item with
@@ -2908,8 +2942,8 @@ public static partial class FirmamentBuildAndExport
// The importer owns the source-entity -> BRep mapping; the exporter owns the inverse
// BRep -> emitted-entity mapping. Preserve both boundaries.
GeometricFaceIds = importedFaces.TryGetValue(item switch
- { Step242SemanticPmiDatum d => d.Label, Step242SemanticPmiHole h => h.Name ?? "", _ => "" }, out var faces)
- ? faces : item is Step242SemanticPmiDatum datum && body is not null
+ { Step242SemanticPmiDatum d => d.Label, Step242SemanticPmiHole h => h.Name ?? "", Step242SemanticPmiGeometricTolerance g => g.Name, _ => "" }, out var faces)
+ ? faces : item.GeometricFaceIds.Count > 0 ? item.GeometricFaceIds : item is Step242SemanticPmiDatum datum && body is not null
? FirmamentSelectorResolver.ResolveUniquePlanarFace(body, datum.Target).Select(id => id.Value).ToArray()
: (correspondence?.Descendants ?? [])
.Where(descendant => descendant.Face.HasValue
@@ -2931,6 +2965,12 @@ public static partial class FirmamentBuildAndExport
{
foreach (var item in items)
{
+ if (item is Step242SemanticPmiGeometricTolerance)
+ {
+ if (item.GeometricFaceIds.Count > 0 && item.GeometricFaceIds.All(id => body.Topology.Faces.Any(face => face.Id.Value == id))) continue;
+ return KernelResult<bool>.Failure([new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,
+ $"firmament-v2-imported-pmi-target-unresolved: '{item.FeatureId}' requires a proved imported face association.", "FirmamentV2.Pmi")]);
+ }
var required = item is Step242SemanticPmiDatum ? SurfaceGeometryKind.Plane : SurfaceGeometryKind.Cylinder;
if (item.GeometricFaceIds.Count == 0 || item.GeometricFaceIds.Any(id =>
!body.TryGetFaceSurface(new FaceId(id), out var surface) || surface?.Kind != required))
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentInterop/FirmamentV2DiagnosticAdapter.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentInterop/FirmamentV2DiagnosticAdapter.cs
index 1136f951..bd0d3da7 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentInterop/FirmamentV2DiagnosticAdapter.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentInterop/FirmamentV2DiagnosticAdapter.cs
@@ -63,6 +63,11 @@ public static class FirmamentV2DiagnosticAdapter
FirmamentV2Parser.PmiDimensionMissingTolerance => "PMI dimension resolves to a value without tolerance evidence.",
FirmamentV2Parser.ConceptMissingRequiredField => "Forge concept application is missing a required descriptor field.",
FirmamentV2Parser.PmiUnknownDatum => "PMI relation references an unknown datum.",
+ "firmament-v2-pmi-name-list-invalid" => "Use a datum or modifier name, or an ordered list of names such as [A, B, C].",
+ "firmament-v2-pmi-datum-precedence-invalid" => "datumRefs requires up to three distinct datum names in primary, secondary and tertiary order.",
+ "firmament-v2-pmi-datum-not-applicable" => "Form controls omit datums; orientation and runout controls require declared datum references.",
+ "firmament-v2-pmi-modifier-invalid" => "Use admitted, distinct modifiers. MaximumMaterial and LeastMaterial cannot be combined.",
+ "firmament-v2-pmi-zone-form-invalid" => "zone requires Cylindrical, Spherical or BetweenSurfaces.",
FirmamentV2Parser.ToleranceDroppedThroughArithmetic => "A toleranced value was used in arithmetic and only the nominal value was preserved.",
_ when diagnosticCode.StartsWith(FirmamentV2Parser.AssertVolumeKindUnsupported + ":", StringComparison.Ordinal)
=> "This part admits Assert Volume, Assert Bounds and Assert Topology. Assert ToleranceStackup belongs on an Assembly with dimensional relations.",
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs
index 8b5ce105..91f2d2bf 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs
@@ -282,6 +282,9 @@ public static class FirmamentSourceSpelling
Add("RotateLocal", "Axis Angle");
Add("Mate", "Interface Member At Gap Clocking Orientation Support");
Add("Note", "Target Text");
+ Add("Datum", "Target");
+ Add("HoleDiameter", "Target Value Dimension Tolerance Datum DatumRefs");
+ Add(string.Join(" ", Aetheris.Kernel.Core.Step242.Step242GeometricToleranceKinds.All.Select(k => k.Name)) + " Parallel Perpendicular", "Target Tolerance Datum DatumRefs Modifiers Zone");
Add("Appearance", "Color Metallic Roughness Opacity Emissive");
Add("Material", "Identity Appearance");
Add("Start End Corner RouteSite", "At On Radius");
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
index 17aa3042..5512a6ed 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
@@ -293,7 +293,8 @@ public sealed record FirmamentV2SemanticHoleDecl(
FirmamentV2BoundHolePlacement? Placement = null,
FirmamentV2SemanticHoleTermination? Termination = null,
IReadOnlyList<FirmamentV2AuthoredField>? AuthoredFields = null);
-public enum FirmamentV2PmiKind { HoleDiameter, DatumPlane, Distance, Flatness, Parallel, Perpendicular, Coplanar }
+public enum FirmamentV2PmiKind { HoleDiameter, DatumPlane, Distance, Flatness, Parallel, Perpendicular, Coplanar,
+ Straightness, Roundness, Cylindricity, Parallelism, Perpendicularity, Angularity, Position, LineProfile, SurfaceProfile, CircularRunout, TotalRunout }
public sealed record FirmamentV2PmiDecl(string Name, FirmamentV2PmiKind Kind, string Target, double? Value = null);
public sealed record FirmamentV2PmiBlock(IReadOnlyList<FirmamentV2PmiRecord> Records, FirmamentV2SourceSpan SourceSpan);
public sealed record FirmamentV2PmiRecord(FirmamentV2PmiKind Kind, string Name, IReadOnlyDictionary<string, FirmamentV2PmiField> Fields, FirmamentV2SourceSpan SourceSpan, FirmamentV2BoundPmiRecord? Bound = null, FirmamentV2PmiProjection? Projection = null);
@@ -302,6 +303,8 @@ public sealed record FirmamentV2BoundPmiBlock(IReadOnlyList<FirmamentV2BoundPmiR
public sealed record FirmamentV2BoundPmiRecord(FirmamentV2PmiKind Kind, string Name, IReadOnlyList<string> Targets, FirmamentV2LiteralValue? DimensionValue, FirmamentV2Tolerance? DimensionTolerance, FirmamentV2LiteralValue? ControlTolerance, IReadOnlyList<string> DatumRefs, FirmamentV2SourceSpan SourceSpan, string? ProjectionSource = null, FirmamentV2HoleWallSelector? HoleWallTarget = null)
{
public IReadOnlyList<FirmamentV2ValueOrigin> DimensionOrigins { get; init; } = [];
+ public IReadOnlyList<string> Modifiers { get; init; } = [];
+ public string? ZoneForm { get; init; }
}
/// <summary>Reusable, validated dimensional intent. Only equality of a semantic feature property
/// to a length expectation is admitted in Preview 1.</summary>
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index d4fa71db..1c2d0da5 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -2386,6 +2386,10 @@ public static partial class FirmamentV2Parser
var recordNames = new HashSet<string>(StringComparer.Ordinal);
var datumLabels = new HashSet<string>(StringComparer.Ordinal);
var knownDatums = new HashSet<string>(StringComparer.Ordinal);
+ foreach (var imported in solids.Values.Select(s => s.InlineStep).OfType<FirmamentV2InlineStepRecord>().Where(s => !s.GeometryOnly && s.SourceText is not null))
+ knownDatums.UnionWith(Aetheris.Kernel.Core.Step242.Step242SemanticPmiInspector.Inspect(imported.SourceText!).Items
+ .Where(item => item.Kind == "Datum").GroupBy(item => item.Name, StringComparer.Ordinal).Where(group => group.Count() == 1).Select(group => group.Key));
+ var importedDatums = knownDatums.ToHashSet(StringComparer.Ordinal);
var letMap = boundLets.ToDictionary(l => l.Name, StringComparer.Ordinal);
var recordMap = boundLetRecords.ToDictionary(r => r.Name, StringComparer.Ordinal);
var holeNames = modifyBlocks.SelectMany(m => m.SemanticHoles).Select(h => h.Name).Concat(additionalHoleNames ?? []).ToHashSet(StringComparer.Ordinal);
@@ -2398,6 +2402,7 @@ public static partial class FirmamentV2Parser
var name = em.Groups["name"].Value;
if (!TryPmiKind(kindRaw, out var kind)) { diagnostics.Add(PmiUnknownRecordKind); diagnostics.Add(PmiKindUnknown); continue; }
if (kind == FirmamentV2PmiKind.DatumPlane && !datumLabels.Add(name)) { diagnostics.Add(PmiDuplicateDatum); }
+ if (kind == FirmamentV2PmiKind.DatumPlane && importedDatums.Contains(name)) diagnostics.Add("firmament-v2-pmi-source-name-conflict");
if (!recordNames.Add(name)) { diagnostics.Add(PmiDuplicateRecord); diagnostics.Add(PmiDuplicateName); continue; }
var entryOpen = body.IndexOf('{', em.Index);
var entryClose = FindMatchingBrace(body, entryOpen);
@@ -2410,12 +2415,12 @@ public static partial class FirmamentV2Parser
if (!TryBindPmiRecord(record, solids, modifyBlocks, regionByTarget, aliases, holeNames, letMap, recordMap, knownDatums, diagnostics, out var b)) continue;
bound.Add(b);
if (kind == FirmamentV2PmiKind.DatumPlane) knownDatums.Add(name);
- if (kind is FirmamentV2PmiKind.DatumPlane or FirmamentV2PmiKind.HoleDiameter)
- legacy.Add(new FirmamentV2PmiDecl(name, kind, b.Targets[0], b.DimensionValue?.NumericValue));
+ if (b.Targets.Count > 0)
+ legacy.Add(new FirmamentV2PmiDecl(name, kind, b.Targets[0], b.DimensionValue?.NumericValue ?? b.ControlTolerance?.NumericValue));
}
var block = new FirmamentV2PmiBlock(records, new FirmamentV2SourceSpan(match.Index, close - match.Index + 1));
- var boundBlock = new FirmamentV2BoundPmiBlock(bound.Where(r => r.Kind == FirmamentV2PmiKind.DatumPlane).ToArray(), bound.Where(r => r.Kind is FirmamentV2PmiKind.HoleDiameter or FirmamentV2PmiKind.Distance).ToArray(), bound.Where(r => r.Kind is FirmamentV2PmiKind.Flatness or FirmamentV2PmiKind.Parallel or FirmamentV2PmiKind.Perpendicular or FirmamentV2PmiKind.Coplanar).ToArray(), diagnostics.Where(d => d.StartsWith("firmament-v2-pmi-", StringComparison.Ordinal)).ToArray());
+ var boundBlock = new FirmamentV2BoundPmiBlock(bound.Where(r => r.Kind == FirmamentV2PmiKind.DatumPlane).ToArray(), bound.Where(r => r.Kind is FirmamentV2PmiKind.HoleDiameter or FirmamentV2PmiKind.Distance).ToArray(), bound.Where(r => r.Kind is not (FirmamentV2PmiKind.DatumPlane or FirmamentV2PmiKind.HoleDiameter or FirmamentV2PmiKind.Distance)).ToArray(), diagnostics.Where(d => d.StartsWith("firmament-v2-pmi-", StringComparison.Ordinal)).ToArray());
return (legacy, block, boundBlock);
}
@@ -2431,8 +2436,6 @@ public static partial class FirmamentV2Parser
if (statement is not FieldSyntax field) { diagnostics.Add(PmiUnsupported); continue; }
var n = NormalizePmiField(field.Name.Text);
var v = body.Substring(field.Value.Span.Start, field.Value.Span.Length).Trim();
- if (n == "datum" && field.Value is SequenceSyntax && v.StartsWith("[", StringComparison.Ordinal) && v.EndsWith("]", StringComparison.Ordinal))
- v = v[1..^1].Trim();
if (fields.ContainsKey(n)) { diagnostics.Add(PmiDuplicateField); continue; }
fields[n] = new(n, v, new FirmamentV2SourceSpan(baseOffset + field.Span.Start, field.Span.Length), null);
}
@@ -2462,15 +2465,23 @@ public static partial class FirmamentV2Parser
"Tolerance" => "tolerance",
"Datum" => "datum",
"DatumRefs" => "datum",
+ "datumRefs" => "datum",
+ "Modifiers" => "modifiers",
+ "Zone" => "zone",
_ => raw
};
- private static bool TryPmiKind(string raw, out FirmamentV2PmiKind kind) { kind = raw switch { "diameter"=>FirmamentV2PmiKind.HoleDiameter, "datum"=>FirmamentV2PmiKind.DatumPlane, "distance"=>FirmamentV2PmiKind.Distance, "flatness"=>FirmamentV2PmiKind.Flatness, "parallel"=>FirmamentV2PmiKind.Parallel, "perpendicular"=>FirmamentV2PmiKind.Perpendicular, "coplanar"=>FirmamentV2PmiKind.Coplanar, _=>default }; return raw is "diameter" or "datum" or "distance" or "flatness" or "parallel" or "perpendicular" or "coplanar"; }
+ private static bool TryPmiKind(string raw, out FirmamentV2PmiKind kind)
+ => Enum.TryParse(raw switch { "diameter" => "HoleDiameter", "datum" => "DatumPlane", "distance" => "Distance", "flatness" => "Flatness",
+ "parallel" => "Parallel", "perpendicular" => "Perpendicular", "coplanar" => "Coplanar", _ => raw }, false, out kind) && Enum.IsDefined(kind);
private static void ValidatePmiFieldSet(string kind, string name, IReadOnlyDictionary<string,FirmamentV2PmiField> fields, List<string> diagnostics)
{
string[] required = kind switch { "datum"=>["target"], "diameter"=> fields.ContainsKey("dimension") ? ["target","dimension"] : fields.ContainsKey("diameter") ? ["target","diameter"] : ["target","value"], "distance"=>["targetA","targetB","dimension"], "flatness"=>["target","tolerance"], "parallel" or "perpendicular" or "coplanar"=>["target","datum","tolerance"], _=>[] };
- var allowed = required.Concat(kind=="diameter"?["tolerance","diameter","value","dimension","datum"]:[]).ToHashSet(StringComparer.Ordinal);
+ if (TryPmiKind(kind, out var parsedKind) && Aetheris.Kernel.Core.Step242.Step242GeometricToleranceKinds.Find(parsedKind.ToString()) is { } control)
+ required = control.RequiresDatum ? ["target", "datum", "tolerance"] : ["target", "tolerance"];
+ var allowed = required.Concat(kind=="diameter"?["tolerance","diameter","value","dimension","datum"]:[])
+ .Concat(Aetheris.Kernel.Core.Step242.Step242GeometricToleranceKinds.Find(parsedKind.ToString()) is not null ? ["datum", "modifiers", "zone"] : []).ToHashSet(StringComparer.Ordinal);
foreach (var r in required) if (!fields.ContainsKey(r)) diagnostics.Add(PmiMissingRequiredField);
foreach (var f in fields.Keys) if (!allowed.Contains(f)) diagnostics.Add(PmiUnknownField);
}
@@ -2488,7 +2499,7 @@ public static partial class FirmamentV2Parser
ValidateTarget(t, r.Kind, solids, regions, aliases, holeNames, diagnostics);
continue;
}
- if (r.Kind != FirmamentV2PmiKind.HoleDiameter) { diagnostics.Add($"{HoleWallConsumerInvalid}:{r.Name}"); continue; }
+ if (r.Kind != FirmamentV2PmiKind.HoleDiameter && Aetheris.Kernel.Core.Step242.Step242GeometricToleranceKinds.Find(r.Kind.ToString()) is null) { diagnostics.Add($"{HoleWallConsumerInvalid}:{r.Name}"); continue; }
var owners = modifyBlocks.Where(block => block.SemanticHoles.Any(hole => hole.Name == holeName)).Select(block => block.TargetSolid).Distinct(StringComparer.Ordinal).ToArray();
if (owners.Length > 1) diagnostics.Add($"{HoleWallAmbiguous}:{holeName}");
else if (owners.Length == 0) diagnostics.Add($"{(solids.ContainsKey(holeName) ? HoleWallNotHole : HoleWallUnknownHole)}:{holeName}");
@@ -2505,22 +2516,41 @@ public static partial class FirmamentV2Parser
if (r.Kind == FirmamentV2PmiKind.HoleDiameter && dim.NumericValue is <= 0) { diagnostics.Add(PmiDiameterInvalid); return false; }
if (dimTol is null && Field(r,"diameter") is null && Field(r,"value") is null) { diagnostics.Add(PmiDimensionMissingTolerance); return false; }
}
- if (r.Kind is FirmamentV2PmiKind.Flatness or FirmamentV2PmiKind.Parallel or FirmamentV2PmiKind.Perpendicular or FirmamentV2PmiKind.Coplanar)
+ var geometricControl = Aetheris.Kernel.Core.Step242.Step242GeometricToleranceKinds.Find(r.Kind.ToString());
+ if (geometricControl is not null || r.Kind == FirmamentV2PmiKind.Coplanar)
{ if (Field(r,"tolerance") is string t && TryParsePmiLength(NormalizePmiLengthLiteral(t), diagnostics, out var lit)) ctlTol=lit; else diagnostics.Add(PmiToleranceTypeMismatch); }
- if (r.Kind is FirmamentV2PmiKind.Parallel or FirmamentV2PmiKind.Perpendicular or FirmamentV2PmiKind.Coplanar)
- { var d=Field(r,"datum"); if (d is null || !datums.Contains(d)) diagnostics.Add(PmiUnknownDatum); else datumRefs.Add(d); }
+ if (geometricControl is not null || r.Kind == FirmamentV2PmiKind.Coplanar)
+ {
+ datumRefs.AddRange(PmiNames(Field(r, "datum"), diagnostics));
+ if (datumRefs.Any(d => !datums.Contains(d))) diagnostics.Add(PmiUnknownDatum);
+ if (datumRefs.Count > 3 || datumRefs.Distinct().Count() != datumRefs.Count) diagnostics.Add("firmament-v2-pmi-datum-precedence-invalid");
+ if (geometricControl is { RequiresDatum: true } && datumRefs.Count == 0 || geometricControl is { AllowsDatum: false } && datumRefs.Count > 0) diagnostics.Add("firmament-v2-pmi-datum-not-applicable");
+ }
if (r.Kind == FirmamentV2PmiKind.HoleDiameter && Field(r,"datum") is string datum)
- { if (!datums.Contains(datum)) diagnostics.Add(PmiUnknownDatum); else datumRefs.Add(datum); }
+ { foreach (var name in PmiNames(datum, diagnostics)) if (!datums.Contains(name)) diagnostics.Add(PmiUnknownDatum); else datumRefs.Add(name); }
var dimensionSource = Field(r, "dimension");
var dimensionBinding = dimensionSource is null ? null : ResolveBoundLet(dimensionSource, lets, records);
bound=new(r.Kind,r.Name,targets,dim,dimTol,ctlTol,datumRefs,r.SourceSpan,
ProjectionSource: dimensionBinding?.Origins.Any(o => o.Binding == dimensionSource) == true ? dimensionSource
: dimensionBinding?.Origins.FirstOrDefault()?.Binding ?? dimensionSource, HoleWallTarget: wallTarget)
- { DimensionOrigins = dimensionBinding?.Origins ?? [] };
+ { DimensionOrigins = dimensionBinding?.Origins ?? [], Modifiers = PmiNames(Field(r, "modifiers"), diagnostics), ZoneForm = Field(r, "zone") };
+ if (bound.ZoneForm is { } zone && !Aetheris.Kernel.Core.Step242.Step242GeometricToleranceKinds.ZoneForms.ContainsKey(zone)) diagnostics.Add("firmament-v2-pmi-zone-form-invalid");
+ if (bound.Modifiers.Any(m => !Aetheris.Kernel.Core.Step242.Step242GeometricToleranceKinds.Modifiers.ContainsKey(m))
+ || bound.Modifiers.Distinct().Count() != bound.Modifiers.Count
+ || bound.Modifiers.Contains("MaximumMaterial") && bound.Modifiers.Contains("LeastMaterial")) diagnostics.Add("firmament-v2-pmi-modifier-invalid");
return !diagnostics.Any(x => (x.StartsWith("firmament-v2-pmi-", StringComparison.Ordinal) && x is not PmiUnsupported)
|| x.StartsWith("firmament-v2-hole-wall-", StringComparison.Ordinal));
}
private static string? Field(FirmamentV2PmiRecord r,string name)=>r.Fields.TryGetValue(name,out var f)?f.Source:null;
+ private static IReadOnlyList<string> PmiNames(string? source, List<string> diagnostics)
+ {
+ if (source is null) return [];
+ var parsed = FirmamentSyntaxParser.ParseExpression(source);
+ var values = parsed.Expression is SequenceSyntax sequence ? sequence.Items.Select(a => a.Value).ToArray() : [parsed.Expression];
+ if (parsed.Diagnostics.Count > 0 || values.Any(value => value is not ReferenceSyntax))
+ { diagnostics.Add("firmament-v2-pmi-name-list-invalid"); return []; }
+ return values.Cast<ReferenceSyntax>().Select(value => value.Name.Text).ToArray();
+ }
private static FirmamentV2BoundLet? ResolveBoundLet(string s,IReadOnlyDictionary<string,FirmamentV2BoundLet> lets,IReadOnlyDictionary<string,FirmamentV2BoundLetRecord> records){var m=DottedReferenceRegex.Match(s); if(m.Success&&records.TryGetValue(m.Groups["record"].Value,out var rec)&&rec.Fields.TryGetValue(m.Groups["field"].Value,out var f))return f; return lets.TryGetValue(s,out var l)?l:null;}
private static string NormalizePmiLengthLiteral(string s) => Regex.Replace(s.Trim(), @"(?<=\d)\s+(?=mm$)", "", RegexOptions.CultureInvariant);
private static bool TryParsePmiLength(string s,List<string> d,out FirmamentV2LiteralValue lit){lit=null!; var v=ParseLetLiteral(FirmamentV2PrimitiveType.Length,s,d); if(v is null){d.Add(PmiToleranceTypeMismatch); return false;} if(v.NumericValue is < 0){ d.Add(PmiDiameterInvalid); return false; } lit=v; return true;}
@@ -2569,12 +2599,6 @@ public static partial class FirmamentV2Parser
return false;
}
- if (!solid.InlineStep.CanonicalInput)
- {
- diagnostics.Add(PmiImportedTargetRequiresCanonicalStep);
- return false;
- }
-
if (!solid.InlineStep.TopologyMap.TryResolveFaceEntity(entity, out _))
{
diagnostics.Add(InlineStepUnknownFace);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs
index 3a2f12a6..03264441 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs
@@ -44,6 +44,8 @@ public sealed record FirmamentV2ValidationConceptField(string Name, string Type,
public sealed record FirmamentV2ValidationPmiRecord(string Kind, string Name, string Status, string ExportSupport, string? Target, IReadOnlyList<string> Targets, IReadOnlyList<string> DatumRefs, FirmamentV2ValidationDimension? Dimension, string? Reason, IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics, string? ProjectionSource = null, string? SourceConstraintKind = null, string? SourceSubject = null, string? ValidationStatus = null, string? Provenance = null)
{
public IReadOnlyList<FirmamentV2ValueOrigin> DimensionOrigins { get; init; } = [];
+ public IReadOnlyList<string> Modifiers { get; init; } = [];
+ public string? Zone { get; init; }
}
public sealed record FirmamentV2ValidationDimension(string Nominal, FirmamentV2ValidationTolerance? Tolerance);
public sealed record FirmamentV2ValidationConceptPmiObligation(string Kind, string SourceConcept, string? SourceName, string? Target, string? ExpectedDimensionField, string Status, string Severity, string? MatchedPmi = null, string? DiagnosticCode = null);
@@ -254,7 +256,7 @@ public static class FirmamentV2ValidationReportBuilder
constraint is null ? null : "dimensional-equality",
constraint is null ? null : constraint.Subject + "." + constraint.Property,
constraint is null ? null : constraint.ValidationSucceeded ? "succeeded" : "failed",
- constraint?.ExpectedProvenance) { DimensionOrigins = boundRecord?.DimensionOrigins ?? [] };
+ constraint?.ExpectedProvenance) { DimensionOrigins = boundRecord?.DimensionOrigins ?? [], Modifiers = boundRecord?.Modifiers ?? [], Zone = boundRecord?.ZoneForm };
}).ToArray();
}
@@ -371,7 +373,7 @@ public static class FirmamentV2ValidationReportBuilder
? Convert.ToString(value.Value, CultureInfo.InvariantCulture) ?? string.Empty
: FormatNumber(value.NumericValue ?? 0) + value.Unit;
- private static string FormatNumber(double value) => value.ToString("0.############", CultureInfo.InvariantCulture);
+ private static string FormatNumber(double value) => value.ToString("R", CultureInfo.InvariantCulture);
private static string TypeName(FirmamentV2PrimitiveType type) => type.ToString().ToLowerInvariant();
@@ -389,16 +391,8 @@ public static class FirmamentV2ValidationReportBuilder
FirmamentBuildAndExport.V2PmiExportRejection(kind, boundRecord?.Name ?? "unbound", boundRecord) is not null
? "deferred" : boundRecord is null ? "supported-when-target-resolves" : "supported";
- private static readonly IReadOnlyDictionary<string, string> ExportMatrix = new Dictionary<string, string>(StringComparer.Ordinal)
- {
- ["datum"] = "supported-when-target-resolves",
- ["diameter"] = "supported-when-target-resolves",
- ["distance"] = "deferred",
- ["flatness"] = "deferred",
- ["parallel"] = "deferred",
- ["perpendicular"] = "deferred",
- ["coplanar"] = "deferred"
- };
+ private static readonly IReadOnlyDictionary<string, string> ExportMatrix = Enum.GetValues<FirmamentV2PmiKind>()
+ .ToDictionary(KindName, kind => ExportSupport(kind, null), StringComparer.Ordinal);
private sealed record FirmamentV2ConceptPmiObligationEvaluation(
IReadOnlyList<FirmamentV2ValidationConceptPmiObligation> Obligations,
diff --git a/Aetheris.Kernel.Firmament/Modules/FirmamentModuleGraph.cs b/Aetheris.Kernel.Firmament/Modules/FirmamentModuleGraph.cs
index 4d8fe430..1c3a2379 100644
--- a/Aetheris.Kernel.Firmament/Modules/FirmamentModuleGraph.cs
+++ b/Aetheris.Kernel.Firmament/Modules/FirmamentModuleGraph.cs
@@ -37,6 +37,7 @@ internal sealed partial class FirmamentModuleGraph
DeclarationSyntax? Export, string Definition, SemanticSourceSpan Origin)
{
internal BrepBody? ImportedBody { get; init; }
+ internal bool GeometryOnly { get; init; }
internal SemanticSourceSpan DeclarationOrigin { get; init; } = Export is null ? Origin : new(Path,Export.Span.Start,Export.Span.Length);
}
internal sealed record Edit(FirmamentV2SourceSpan Span, string Text);
@@ -215,8 +216,8 @@ internal sealed partial class FirmamentModuleGraph
if (locator is null) continue;
var path = Resolve(module, locator, adapter.Name.Text, origin);
if (path is null) continue;
- if (adapter.Name.Text == "Step" && !geometryOnly && ImportedStepSemantics.HasAnnotations(Asset(path)))
- { Error("firmament-step-source-pmi-unsupported", "Imported annotation passthrough is not qualified. Explicitly request geometryOnly: true to exclude source PMI while retaining the original file.", origin); continue; }
+ if (adapter.Name.Text == "Step" && kind.Name.Text == "Assembly" && !geometryOnly && ImportedStepSemantics.HasAnnotations(Asset(path)))
+ { Error("firmament-step-source-pmi-unsupported", "Single-part PMI transfer is supported; imported assembly-wide PMI transfer requires explicit geometryOnly: true until product/occurrence associations are qualified.", origin); continue; }
Module? child = null; DeclarationSyntax? declaration = null;
if (adapter.Name.Text == "Firmament")
{
@@ -239,9 +240,9 @@ internal sealed partial class FirmamentModuleGraph
declaration = child.Syntax.Statements.OfType<DeclarationSyntax>().Single(d => d.Type.Name.Text == "Assembly");
export = declaration.Name!.Text;
}
- var identity = "__Module_" + Hash(IdentityPath(path) + "\0" + kind.Name.Text + "\0" + export)[..20];
+ var identity = "__Module_" + Hash(IdentityPath(path) + "\0" + kind.Name.Text + "\0" + export + (geometryOnly ? "\0geometryOnly" : ""))[..20];
var reference = new Reference(identity, kind.Name.Text, path, child, declaration, export ?? "", origin)
- { DeclarationOrigin = declaration is null ? origin : DeclarationOrigin(declaration) };
+ { DeclarationOrigin = declaration is null ? origin : DeclarationOrigin(declaration), GeometryOnly = geometryOnly };
references.TryAdd(identity, reference);
InventoryBindings.Add(new(inventory.Name.Text+"."+field.Name.Text,kind.Name.Text,path,export ?? "",identity,origin)
{ MetadataType = metadata?.Type, Metadata = metadata?.Fields ?? new Dictionary<string,string>(), GeometryOnly = geometryOnly });
diff --git a/Aetheris.Kernel.Firmament/Visualization/PmiDisplayProjection.cs b/Aetheris.Kernel.Firmament/Visualization/PmiDisplayProjection.cs
index e97f450a..426f7984 100644
--- a/Aetheris.Kernel.Firmament/Visualization/PmiDisplayProjection.cs
+++ b/Aetheris.Kernel.Firmament/Visualization/PmiDisplayProjection.cs
@@ -52,7 +52,9 @@ public static class PmiDisplayProjection
var result = new List<PmiDisplayAnnotation>();
foreach (var item in inspection.Items)
{
- if (item.Kind is not ("Datum" or "Diameter"))
+ if (!item.PresentationSupported)
+ throw new InvalidOperationException($"pmi-display-parameters-unsupported: '{item.Name}' retains advanced semantic parameters that this 3D label path cannot yet display completely.");
+ if (item.Kind is not ("Datum" or "Diameter" or "Dimension") && Step242GeometricToleranceKinds.Find(item.Kind) is null)
throw new InvalidOperationException($"pmi-display-kind-unsupported: {item.Kind} '{item.Name}' has no qualified 3D callout yet.");
var targets = item.GeometricFaceEntityIds.Where(id => sourceFaces.TryGetValue(id, out var face)
&& patches.TryGetValue(face, out var patch) && patch.Positions.Count > 0 && patch.TriangleIndices.Count >= 3)
@@ -63,7 +65,7 @@ public static class PmiDisplayProjection
// A section planner can partition one physical cylindrical wall.
// Admit only a connected set on the same analytic cylinder, and
// retain every associated patch in the highlight and leaders.
- if (targets.Length != 1 && (item.Kind != "Diameter" || !OneCylindricalWall(body, targets)))
+ if (targets.Length != 1 && (item.Kind is "Datum" or "Diameter") && (item.Kind != "Diameter" || !OneCylindricalWall(body, targets)))
throw new InvalidOperationException($"pmi-display-target-multiple-unsupported: '{item.Name}' requires a multi-face presentation.");
var internalEdges = targets.SelectMany(p => body.Topology.GetFace(p.FaceId).LoopIds
.SelectMany(id => body.Topology.GetLoop(id).CoedgeIds).Select(id => body.Topology.GetCoedge(id).EdgeId).Distinct())
@@ -84,8 +86,20 @@ public static class PmiDisplayProjection
double[] anchor = P(anchorPoint);
var stem = anchorPoint + normal * target.StemLength;
string N(double value) => value.ToString("G9", CultureInfo.InvariantCulture);
- var text = item.Kind == "Datum" ? $"[{item.Name}]" : $"Ø{N(item.Value!.Value)}"
- + (item.TolerancePlus.HasValue && item.ToleranceMinus.HasValue ? $" +{N(item.TolerancePlus.Value)}/-{N(item.ToleranceMinus.Value)}" : "") + " mm";
+ string Modifier(string value) => value switch { "MAXIMUM_MATERIAL_REQUIREMENT" => "(M)", "LEAST_MATERIAL_REQUIREMENT" => "(L)", "FREE_STATE" => "(F)", "COMMON_ZONE" => "CZ", "STATISTICAL_TOLERANCE" => "ST", _ => value };
+ var datumLabels = item.DatumReferenceFrames.Count > 0 ? item.DatumReferenceFrames.Select(frame => string.Join("-", frame.Labels) + string.Concat(frame.Modifiers.Select(Modifier))) : item.DatumReferences;
+ var zoneLabels = string.Join(" ", item.ZoneForms.Select(form => form switch
+ {
+ "cylindrical or circular" => "Ø", "spherical" => "SØ",
+ "between two equidistant surfaces" => "BetweenSurfaces ",
+ _ => throw new InvalidOperationException($"pmi-display-zone-unsupported: '{item.Name}' has unsupported zone form '{form}'.")
+ }));
+ if (item.Kind != "Datum" && item.Value is null) throw new InvalidOperationException($"pmi-display-value-unresolved: '{item.Name}' has no semantic magnitude.");
+ var text = item.Kind == "Datum" ? $"[{item.Name}]" : Step242GeometricToleranceKinds.Find(item.Kind) is not null
+ ? $"{item.Kind} | " + zoneLabels + $"{N(item.Value!.Value)} mm" + string.Concat(item.Modifiers.Select(Modifier))
+ + (item.DatumReferences.Count > 0 ? " | " + string.Join(" | ", datumLabels) : "")
+ : (item.Kind == "Diameter" || item.DimensionKind?.Equals("diameter", StringComparison.OrdinalIgnoreCase) == true ? "Ø" : (item.DimensionKind ?? "Length") + " ") + N(item.Value!.Value)
+ + (item.TolerancePlus.HasValue && item.ToleranceMinus.HasValue ? $" +{N(item.TolerancePlus.Value)}/-{N(item.ToleranceMinus.Value)}" : "") + " " + item.ValueUnit;
var outlines = PlanarTextProfiles.PresentationContours(text, height);
var lines = new List<double[][]> { new[] { anchor, P(stem), new[] { label[0] - height, label[1], label[2] }, label } };
foreach (var witness in witnesses.Skip(1))
@@ -122,7 +136,7 @@ public static class PmiDisplayProjection
BrepBody body, DisplayTessellationResult tessellation, DisplayFaceMeshPatch patch, string kind, double height, double[] label, IReadOnlySet<Aetheris.Kernel.Core.Topology.EdgeId> internalEdges)
{
body.TryGetFaceSurfaceGeometry(patch.FaceId, out var surface);
- if (kind == "Datum" && surface?.Plane is PlaneSurface plane)
+ if (surface?.Plane is PlaneSurface plane)
{
// The largest triangle incircle is a bounded, deterministic interior witness.
// A vertex average of the whole face can land in a hole or outside a concavity.
@@ -141,7 +155,7 @@ public static class PmiDisplayProjection
corners.SelectMany(_ => V(normal)).ToArray(), [0,1,2,0,2,3], [corners.Append(corners[0]).Select(P).ToArray(),
[P(lifted - u * size), P(lifted + u * size)], [P(lifted - v * size), P(lifted + v * size)]]) { SurfaceOffset = offset });
}
- if (kind == "Diameter" && surface?.Cylinder is CylinderSurface cylinder)
+ if (surface?.Cylinder is CylinderSurface cylinder)
{
// Unwrap each admitted display triangle locally, including the periodic seam.
// Select a substantial triangle away from the end rims; use the label-facing
diff --git a/docs/development/reports/2026-10/pmi-passthrough-and-explicit-gdt.md b/docs/development/reports/2026-10/pmi-passthrough-and-explicit-gdt.md
new file mode 100644
index 00000000..5005a68a
--- /dev/null
+++ b/docs/development/reports/2026-10/pmi-passthrough-and-explicit-gdt.md
@@ -0,0 +1,172 @@
+# Semantic PMI transfer and explicit GD&T
+
+Date: 2026-10-27
+
+## Behavior and ownership
+
+An unchanged single-solid `InlineStep` now carries its semantic AP242 annotation
+graph into the emitted part. Transfer retains formal dimensions, allowances,
+controls, modifiers, ordered datum systems, zone definitions and source geometry
+associations. Unique imported datum labels can be used by added author controls.
+Assembly components still require explicit geometry-only import when annotated;
+part requirements are not implicitly promoted into assembly requirements.
+An explicit geometry-only dependency contributes its exclusion policy to the
+module receipt identity, so it cannot alias an annotation-retaining binding of
+the same source bytes. This changes the semantic receipt, not the imported shape.
+
+Firmament's existing PMI parser/binder admits twelve explicit controls:
+Straightness, Flatness, Roundness, Cylindricity, Parallelism, Perpendicularity,
+Angularity, Position, LineProfile, SurfaceProfile, CircularRunout and TotalRunout.
+These are annotations, not geometry constraints. A shared registry owns control
+kinds and field admission. Unknown fields, unresolved/duplicate datum references,
+inapplicable datums and contradictory modifiers reject. Source GD&T can retain
+advanced forms beyond the bounded authoring syntax.
+
+`Step242PmiTransfer` owns dependency closure, unit normalization and topology
+rebinding. It requires an exact-source import receipt and unchanged-body witness.
+It rejects missing dependencies, unknown incoming semantic owners, ambiguous
+solid ownership and unmapped/split source topology. Auxiliary datum products and
+shells retain their own ownership rather than becoming material-body faces.
+Native emitters now associate GISU directly with the actual annotation feature.
+Vendor-independent readback follows formal AP242 relationships; unnamed shape
+aspects no longer collapse into a shared empty-name target.
+Inspection also exposes direct usage-item identities separately from inferred
+face adjacency. The regression oracle compares physical edge witnesses, not
+temporary edge allocation numbers that change during reimport.
+
+Length measures use their own declared unit, independently of geometry units.
+`0.001 inch` becomes `0.0254 mm`; no authoring grid or fixed-decimal formatter is
+applied to PMI. Derived units preserve length exponents. Angular units remain
+separate. The geometry number writer and engineering lowerers are unchanged.
+
+Foreign graphical glyphs are excluded with `pmi-source-presentation-excluded`:
+their text can still contain inch values. Common supported labels regenerate
+from semantic records. Unsupported or incomplete advanced 3D presentation rejects;
+it does not silently remove datum or zone parameters. Source camera/font/layout
+preservation, graphical-only transfer, topology-edit migration and assembly-wide
+PMI transfer remain outside this capability.
+
+## Regression witnesses
+
+- [Explicit controls](../../../../fixtures/Canonical/PMI/explicit-gdt.firmament):
+ a practical plate/hole with three datums and three controls; removing PMI emits
+ the same geometry.
+- [Imported CTC-01 plus an authored control](../../../../fixtures/Canonical/PMI/nist-ctc01-passthrough.firmament):
+ retains source semantics and binds the added surface-profile control to existing
+ A/B datums. This is a transfer witness, not an approved manufacturing revision.
+- FTC-11's unqualified trims still reject through normal compilation, with or
+ without added PMI. The interchange graph tests do not waive that admission gate.
+- The old flatness refusal fixture is now a valid legacy-spelling fixture with
+ real STEP round-trip and unchanged-volume evidence.
+- Independent unit specimens cover inch geometry, mixed geometry/PMI units,
+ derived length exponents and very small nonzero tolerances. Tiny tolerances are
+ numerical precision tests, not suggested manufacturing requirements.
+
+## Qualification method
+
+The core corpus tests use `Step242Corpus` for all original imports. Each source
+graph is transferred, reparsed and reimported. Checks cover dependency closure,
+semantic-root counts, normalized values and allowances, modifiers, datum order,
+zone forms and individual target correspondence. Auxiliary targets are tracked
+separately from the material body. Geometry emission before/after adding PMI must
+have an identical STEP geometry prefix; topology counts and surface families must
+also survive reimport. This is not a claim of byte-identical vendor STEP output.
+
+A separate real-CLI run validates every NIST specimen, builds and analyzes each
+admitted source, and compares rejected files against explicit geometry-only
+admission. Existing geometry refusals are classified separately from PMI transfer
+failures. Tessellated-only source is not silently treated as an exact solid.
+
+### NIST results through the real CLI
+
+The run covers all 17 stored specimens. Five pass validation, build and analysis;
+the remaining twelve reproduce the existing geometry admission refusal with
+`geometryOnly: true` as well. There are no PMI-specific admission failures or
+validate/build disagreements in this run.
+
+| Specimen | Normal compilation | Datums / dimensions / controls |
+|---|---|---|
+| CTC-01 e1 | Admitted | 3 / 12 / 6 |
+| CTC-02 e2 | Existing geometry admission refusal | — |
+| CTC-03 e2 | Admitted | 6 / 10 / 13 |
+| CTC-04 e1 | Existing geometry admission refusal | — |
+| CTC-05 e1 | Admitted | 4 / 6 / 10 |
+| FTC-06 e2 | Existing geometry admission refusal | — |
+| FTC-07 e2 | Existing geometry admission refusal | — |
+| FTC-08 e1-tg | Tessellated source; existing geometry admission refusal | — |
+| FTC-08 e2 | Existing geometry admission refusal | — |
+| FTC-09 e1 | Admitted | 8 / 22 / 31 |
+| FTC-10 e2 | Existing geometry admission refusal | — |
+| FTC-11 e2 | Existing geometry admission refusal | — |
+| STC-06 e3 | Existing geometry admission refusal | — |
+| STC-07 e3 | Existing geometry admission refusal | — |
+| STC-08 e3 | Existing geometry admission refusal | — |
+| STC-09 e3 | Admitted | 8 / 22 / 27 |
+| STC-10 e2 | Existing geometry admission refusal | — |
+
+All sixteen exact-source semantic graph round trips pass at the core interchange
+layer, including the files rejected by normal engineering geometry admission.
+Those core results do not qualify their trims for production compilation.
+The combined CTC-01 fixture builds through the CLI with 3 datums, 12 dimensions
+and 7 controls, including its new control. The explicit authoring fixture builds
+with 3 datums and 3 controls.
+
+Raw source specimens, STEP outputs, per-command JSON and corpus classification
+are retained under ignored `artifacts/local/pmi-qualification/`.
+
+### Build and regression evidence
+
+Windows, .NET SDK 10.0.401; serial builds with node reuse and shared compilation
+disabled. Final results:
+
+| Check | Result |
+|---|---|
+| Complete solution Release build | 0 errors; 38 existing warnings |
+| Focused core transfer tests | 25 passed, including 16 exact NIST specimens |
+| Core fast lane | 1,136 passed |
+| Complete solution regression | 6,192 passed, 0 failed, 2 skipped across 20 suites |
+| Firmament suite within the full run | 3,283 passed |
+| Browser SDK managed/WASM rebuild | Passed |
+| SDK bridge contract tests | 19 passed |
+| `git diff --check` | Passed |
+
+The two skips are existing optional Drawing Notes rasterizer tests requiring
+`AETHERIS_TEST_PDFTOPPM`; no .NET suite was omitted. Native tests exercise annotation
+projection and annotated GLB geometry-buffer retention. This pass did not perform
+a live Helios/WebGPU UI playtest or external STEP-tool certification.
+
+The final gate was:
+
+```powershell
+dotnet build Aetheris.slnx -c Release -m:1 -nr:false -p:UseSharedCompilation=false
+dotnet test Aetheris.Kernel.Core.Tests -c Release --no-build -m:1 -nr:false --filter "Category!=SlowCorpus"
+dotnet test Aetheris.slnx -c Release --no-build -m:1 -nr:false -- RunConfiguration.MaxCpuCount=1
+```
+
+Logs are under ignored `artifacts/local/pmi-*.log`. The CLI corpus snapshot uses
+the same kernel DLL hash as the final build. No task-owned .NET hosts remained
+after qualification.
+
+## Code review and verdict
+
+Reviewed parser/binder/export ownership, diagnostic propagation, geometry-number
+formatting, source identity, module exclusion policy and browser consumption.
+No new Firmament parser route, source rewrite system, geometric constraint solver
+or native dependency was introduced. Source semantic readback, authoring admission
+and emission share the existing AP242/PMI owners and the common control registry.
+
+**Success for the bounded capability.** Semantic transfer and explicit GD&T work
+through normal compilation for admitted geometry, with precision and association
+evidence. Remaining NIST geometry admission refusals, advanced presentation,
+topology-edit rebinding and assembly-wide transfer are explicit limits rather
+than successful-looking omissions.
+
+## References
+
+The test data comes from the
+[NIST MBE PMI validation and conformance project](https://www.nist.gov/ctl/smart-connected-systems-division/smart-connected-manufacturing-systems-group/mbe-pmi-0).
+Schema interpretation was checked against
+[STEP Tools' tolerance model](https://downloads.steptools.com/docs/stp_aim/stix_tolerance.html)
+and the
+[CAx-IF semantic PMI recommended practices](https://www.mbx-if.org/home/wp-content/uploads/2024/06/rec_pracs_pmi_v408.pdf).
+This is corpus qualification, not third-party AP242 or GD&T certification.
diff --git a/docs/public/firmament/inventory.md b/docs/public/firmament/inventory.md
index 83960b30..e35d031e 100644
--- a/docs/public/firmament/inventory.md
+++ b/docs/public/firmament/inventory.md
@@ -44,10 +44,13 @@ fallback that normalizes ambiguous multiplicity to a flat assembly. Missing or
ambiguous exports and kind mismatches reject. A Part still requires one body;
there is no implicit first-body selection.
-Imported annotation passthrough is not qualified. A STEP resource containing PMI
-rejects unless the binding explicitly says `Step("vendor/gearbox", geometryOnly:
-true)`. That exclusion is retained in the binding receipt; the original file is
-untouched. This permission does not relax geometry admission.
+An unchanged STEP Part consumed by `InlineStep` can retain
+[semantic PMI](pmi.md#imported-semantic-pmi-and-units). Raw STEP components
+materialized in an Assembly still require explicit
+`Step("vendor/gearbox", geometryOnly: true)` when the source contains PMI;
+part annotations are not promoted into assembly requirements. That exclusion
+is retained in the binding receipt; the original file is untouched. It does not
+relax geometry admission.
The normal spelling omits the extension. `Firmament("parts/bracket")` resolves
`.firmament` or `.firmasm`; `Step("vendor/bearing")` resolves `.step` or `.stp`.
diff --git a/docs/public/firmament/pmi.md b/docs/public/firmament/pmi.md
index ac6c007e..d1c56530 100644
--- a/docs/public/firmament/pmi.md
+++ b/docs/public/firmament/pmi.md
@@ -1,8 +1,108 @@
# Semantic PMI and AP242
-Firmament concepts and explicit PMI lower into the semantic engineering model, STEP AP242 product-definition entities, and Cadmata's semantic presentation. PMI records are measurable requirements; annotations are engineer-authored notes. Camera or label orientation is presentation state, not the requirement.
+PMI records manufacturing and inspection intent in STEP AP242. Explicit GD&T is
+annotation data: it attaches a typed control to geometry without changing the
+geometry, solving constraints, or proving that a manufacturing process can meet
+the tolerance. Camera and label placement are presentation state. Checked
+compile-time requirements can separately be projected into dimensional PMI.
-Native Model export supports `Datum` plane records and `HoleDiameter` records, including typed dimensional tolerances. The diameter record targets a named shaft hole; on a counterbore it means the shaft `diameter`, not `counterboreDiameter`. Other parsed PMI kinds may be reported as deferred and cannot be silently omitted by a successful build.
+Native Model export supports planar `Datum`, `HoleDiameter`, and the explicit
+geometric controls below. The diameter record targets a named shaft hole; on a
+counterbore it means the shaft `diameter`, not `counterboreDiameter`. Parsed kinds
+outside the admitted set, including `Distance` and `Coplanar`, remain rejected by
+normal export rather than silently omitted.
+
+## Explicit GD&T
+
+The complete buildable example is
+[`explicit-gdt.firmament`](../../../fixtures/Canonical/PMI/explicit-gdt.firmament).
+Its Box and Hole are ordinary construction. The following records annotate them
+independently of Concept requirements or dimensional projections:
+
+```firmament
+Pmi {
+ Datum A { target: face(-Z) }
+ Datum B { target: face(-X) }
+ Datum C { target: face(-Y) }
+ Flatness Seat { target: face(+Z) tolerance: 0.03mm }
+ Position MountLocation {
+ target: face(Mount.Wall)
+ tolerance: 0.0254mm
+ zone: Cylindrical
+ datumRefs: [A, B, C]
+ modifiers: [MaximumMaterial]
+ }
+}
+```
+
+| Controls | Datum references |
+|---|---|
+| `Straightness`, `Flatness`, `Roundness`, `Cylindricity` | Omitted |
+| `Parallelism`, `Perpendicularity`, `Angularity`, `CircularRunout`, `TotalRunout` | Required |
+| `Position`, `LineProfile`, `SurfaceProfile` | Optional |
+
+`target` must resolve to geometry. `tolerance` is a finite nonnegative Length in
+millimeters, including for `Angularity`; it describes a length-valued tolerance
+zone. `datumRefs` lists up to three distinct, previously declared datums in
+primary/secondary/tertiary order. Legacy `datum: A`, `Parallel` and `Perpendicular`
+spellings remain admitted. Form controls reject datum references.
+
+Optional `modifiers` admits `MaximumMaterial`, `LeastMaterial`, `FreeState`,
+`CommonZone` and `Statistical`. Unknown, duplicate or contradictory modifiers
+reject. Optional `zone` admits `Cylindrical`, `Spherical` and `BetweenSurfaces`.
+Omitting it does not invent an explicit zone form. The compiler validates the
+record and its references; the author remains responsible for selecting an
+appropriate control, feature, zone and modifier combination.
+
+Common-datum groups, datum-reference modifiers, composite frames, projected
+zone parameters and other advanced forms are not yet authoring syntax. Imported
+semantic forms can be retained as described below. Unknown fields reject.
+
+## Imported semantic PMI and units
+
+An unchanged `InlineStep` part retains source semantic PMI by default, together
+with its datum systems, modifiers, tolerance-zone definitions, dimensional
+allowances and proved geometry associations. Aetheris resolves source face and
+edge identities through importer provenance rather than entity ordering.
+Authored annotations may be added; their names must not collide with retained
+source annotation names.
+CLI `analyze --json` reports `geometricItemEntityIds` for the direct source usage
+items (faces, edges, solids or auxiliary datum geometry). Its
+`geometricFaceEntityIds` is the face projection used for presentation; an edge's
+adjacent faces do not replace its source association identity.
+Unique retained datum labels are available directly in an authored control's
+`datumRefs`; they bind to the imported AP242 datum entities rather than creating
+duplicate datums. See the complete
+[`nist-ctc01-passthrough.firmament`](../../../fixtures/Canonical/PMI/nist-ctc01-passthrough.firmament)
+witness. Existing source-integrity receipts (`sha256`, `textSha256`, or a project
+lock) still apply to foreign STEP inputs.
+
+Length-valued measures are normalized using their own declared units. An inch
+tolerance of `0.001` exports as `0.0254` mm. This conversion does **not** use the
+0.1 mm authoring placement grid or round away small tolerances. Angular units
+are separate. Firmament authoring itself continues to require metric lengths.
+
+Source graphical PMI is distinct from semantic PMI. Foreign glyphs are excluded
+with an explicit diagnostic because they may contain inch text; metric labels
+are regenerated from semantic records where the presentation path supports the
+target and all of its parameters. Advanced controls whose labels cannot be
+projected completely reject annotated 3D export rather than omit parameters.
+This does not preserve a vendor's camera, font or label arrangement.
+Graphical-only annotations reject default passthrough. Missing dependencies,
+unresolved units, unsupported compound measures, unmapped body topology and changed bodies reject. Derived
+units retain their dimensional exponents while their length components and values normalize to mm. Non-metric
+auxiliary PMI pcurves also reject when their parameter domains cannot be proved
+safe to normalize. Geometry-only editing of annotated imports still requires
+explicit `geometryOnly: true`; source-PMI migration through topology edits is
+not admitted.
+PMI transfer does not relax geometry admission: a file with unqualified imported
+trims still rejects normal compilation, even if its annotation graph can be
+transferred by the lower-level interchange API.
+
+`geometryOnly: true` explicitly excludes source PMI and reports that exclusion;
+it never modifies the original STEP file. Imported assembly-wide PMI and
+automatic promotion of part annotations into assembly requirements remain
+outside this single-part transfer path.
## Project a compile-time tolerance
@@ -49,8 +149,8 @@ A Datum may be exported separately. A `datum:`/`DatumRefs:` relationship on a
size record rejects normal compilation for every spelling, including legacy
literal records: native size export cannot preserve that association.
Parse-only analysis can bind it, but identifies the record as export-deferred
-at `ParsedNotBuilt`. Datum-referenced geometric controls need a separately
-qualified PMI capability. The shipped examples request independent datums and
+at `ParsedNotBuilt`. Use an explicit geometric control for a datum-referenced
+geometric requirement. The shipped size examples request independent datums and
size dimensions; they no longer request a relationship that was never emitted.
This is semantic product-definition PMI, recovered by `aetheris analyze`;
@@ -66,8 +166,8 @@ toleranced Length values from Static/Record data. It preserves nominal geometry,
allowances and binding origins. Its `Dimension` kinds are Thickness, Linear and
Diameter; targets are bound sheet regions, bends, parts and cuts, including
Pattern members. `DatumFeature` and `Position` retain the sheet exporter's datum
-relationships and geometric associations. Native Model's smaller GD&T capability
-set remains unchanged. See [sheet-metal layout and release syntax](sheet-metal.md#layout-requirements-and-release-data)
+relationships and geometric associations. Native Model explicit GD&T uses the
+controls described above. See [sheet-metal layout and release syntax](sheet-metal.md#layout-requirements-and-release-data)
and the [complete typed example](../../../fixtures/Regression/SheetMetalSemantics/modern-layout-release.firmament).
Use one owning Pmi block. Unknown kinds/fields, missing targets, duplicate blocks,
diff --git a/docs/public/firmament/step-import.md b/docs/public/firmament/step-import.md
index 7f0820ae..99cde3bd 100644
--- a/docs/public/firmament/step-import.md
+++ b/docs/public/firmament/step-import.md
@@ -9,7 +9,7 @@ Assembly with its existing hierarchy and transforms. `InlineStep` is the local
annotation/surgery binding for one body; it can use `from: Components.housing`
or a direct path. An optional generated dependency lock supplies its source pin,
so authors do not need to write SHA-256 strings. See the Inventory guide for lock
-commands, metadata and the explicit exclusion of imported PMI.
+commands, metadata and assembly imports' explicit source-PMI exclusion policy.
Helios also provides **Import STEP** for the bounded canonical `InlineStep` part
workflow described below. It retains the input as an immutable text asset and
@@ -27,9 +27,12 @@ imported geometry.
**Save workspace** downloads a `.helios.zip` containing the original STEP text
and Firmament source; **Open file** reopens it. Local checkpoints retain both too.
Cloud single-document saves cannot store these workspaces and refuse rather than
-omit the asset. Reopening an already annotated STEP as a new `InlineStep` is
-currently rejected explicitly: import of its existing semantic annotation layer
-is not qualified. Reopen the saved workspace to continue editing annotations.
+omit the asset. An unchanged `InlineStep` can retain an existing semantic PMI
+layer, normalize its length measures to millimetres, and add explicit controls.
+Foreign graphical glyphs are excluded with a warning; advanced semantic forms
+can be retained in STEP without promising their 3D label projection. See
+[PMI transfer and explicit GD&T](pmi.md#imported-semantic-pmi-and-units) for
+admission limits. Reopen a saved workspace to preserve its editable source layer.
The browser SDK accepts `.step`/`.stp` text assets in `projectDocuments`:
diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.md
index 84244ec8..2953994d 100644
--- a/docs/public/firmament/syntax.md
+++ b/docs/public/firmament/syntax.md
@@ -39,4 +39,5 @@ Model Plate {
| `schema`, `BodyState`, `MeshState`, `Inventory` | [Domains and modules](../reference/language/domains-and-modules.md) |
| Interfaces, mates, datums, motion | [Assemblies and motion](../reference/language/assemblies-and-motion.md) |
| `Assert`, `measure`, stack-ups | [Checks and measurement](../reference/language/checks.md) |
+| Explicit GD&T, datum precedence, metric PMI passthrough | [Semantic PMI](pmi.md) |
| Older V1 forms | [Reading older source](../reference/language/compatibility.md) |
diff --git a/fixtures/Canonical/PMI/explicit-gdt.firmament b/fixtures/Canonical/PMI/explicit-gdt.firmament
new file mode 100644
index 00000000..ed028906
--- /dev/null
+++ b/fixtures/Canonical/PMI/explicit-gdt.firmament
@@ -0,0 +1,21 @@
+Model AnnotatedPlate {
+ units: mm
+ Box Body { size: [60mm, 40mm, 8mm] }
+ Modify Body {
+ Hole<Shaft> Mount { on: +Z center: Point2(0mm, 0mm) diameter: 8mm end: ThroughAll }
+ }
+ Pmi {
+ Datum A { target: face(-Z) }
+ Datum B { target: face(-X) }
+ Datum C { target: face(-Y) }
+ Flatness Seat { target: face(+Z) tolerance: 0.03mm }
+ Perpendicularity Side { target: face(+X) tolerance: 0.02mm datumRefs: [A] }
+ Position MountLocation {
+ target: face(Mount.Wall)
+ tolerance: 0.0254mm
+ zone: Cylindrical
+ datumRefs: [A, B, C]
+ modifiers: [MaximumMaterial]
+ }
+ }
+}
diff --git a/fixtures/Canonical/PMI/nist-ctc01-passthrough.firmament b/fixtures/Canonical/PMI/nist-ctc01-passthrough.firmament
new file mode 100644
index 00000000..b0b72cff
--- /dev/null
+++ b/fixtures/Canonical/PMI/nist-ctc01-passthrough.firmament
@@ -0,0 +1,17 @@
+// Semantic-transfer witness, not an approved manufacturing revision of the NIST part.
+Model AnnotatedNistPart {
+ units: mm
+ InlineStep Source {
+ path: "../../../testdata/step242/nist/CTC/nist_ctc_01_asme1_ap242-e1.stp"
+ textSha256: "341cea888fb316673ed683e59391c11b4f96cff2542d9387e135f06682dbd745"
+ importTolerance: 0.1mm
+ }
+ Pmi {
+ SurfaceProfile RevisionProfile {
+ target: Source.face("#766")
+ tolerance: 0.1mm
+ datumRefs: [A, B]
+ modifiers: [FreeState]
+ }
+ }
+}
diff --git a/fixtures/Compatibility/LegacyAliases/Invalid/InlineStep/inline-step-v2-record-pmi-export-deferred-flatness.invalid.firmfixture b/fixtures/Compatibility/LegacyAliases/Valid/InlineStep/inline-step-v2-record-pmi-flatness.valid.firmfixture
similarity index 55%
rename from fixtures/Compatibility/LegacyAliases/Invalid/InlineStep/inline-step-v2-record-pmi-export-deferred-flatness.invalid.firmfixture
rename to fixtures/Compatibility/LegacyAliases/Valid/InlineStep/inline-step-v2-record-pmi-flatness.valid.firmfixture
index bcc273ac..76eeac99 100644
--- a/fixtures/Compatibility/LegacyAliases/Invalid/InlineStep/inline-step-v2-record-pmi-export-deferred-flatness.invalid.firmfixture
+++ b/fixtures/Compatibility/LegacyAliases/Valid/InlineStep/inline-step-v2-record-pmi-flatness.valid.firmfixture
@@ -1,13 +1,14 @@
-// fixture-id: inline-step-v2-record-pmi-export-deferred-flatness
-// case: inline-step-v2-record-pmi-export-deferred-flatness
+// fixture-id: inline-step-v2-record-pmi-flatness
+// case: inline-step-v2-record-pmi-flatness
// category: InlineStep
// syntax-version: FirmamentV2
-// validity: invalid
+// validity: valid
// implementation: parser-backed
-// expected: invalid
-// expected-stage: deterministic rejection
-// expected-diagnostic: firmament-v2-pmi-export-deferred
-model InlineStepRecordPmiDeferredFlatness {
+// expected: valid
+// expected-stage: step-verified
+// feature-area: inline-step-pmi
+// expected-volume: 461.15044407846124
+model InlineStepRecordPmiFlatness {
units mm
solid part: InlineStep { path: "../../../../../testdata/firmament/inline-step/canonical-through-hole.step" }
recognize part { region baseFace { kind: datumPlane faces: ["#51"] confidence: high } }
diff --git a/fixtures/Invalid/InlineStep/nist-ftc11-pmi-unqualified-geometry.invalid.firmfixture b/fixtures/Invalid/InlineStep/nist-ftc11-pmi-unqualified-geometry.invalid.firmfixture
new file mode 100644
index 00000000..a1fc4e42
--- /dev/null
+++ b/fixtures/Invalid/InlineStep/nist-ftc11-pmi-unqualified-geometry.invalid.firmfixture
@@ -0,0 +1,21 @@
+// fixture-id: nist-ftc11-pmi-unqualified-geometry
+// validity: invalid
+// expected: invalid
+// expected-diagnostic: firmament-inline-step-import-unqualified
+// The semantic graph transfers at the kernel API, but normal builds retain the existing trim-admission gate.
+Model AnnotatedNistPart {
+ units: mm
+ InlineStep Source {
+ path: "../../../testdata/step242/nist/FTC/nist_ftc_11_asme1_ap242-e2.stp"
+ textSha256: "c1caa07cef540b600fb9b5aefd0fcd3e67595deb6a8a14191808f133b1ab654b"
+ importTolerance: 0.1mm
+ }
+ Pmi {
+ SurfaceProfile RevisionProfile {
+ target: Source.face("#1192")
+ tolerance: 1.2mm
+ datumRefs: [A, B]
+ modifiers: [FreeState]
+ }
+ }
+}