Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add drawing definition evidence and generation options

Yuechen Li48feae5b8bf8
diff --git a/Aetheris.CLI.Tests/DrawingGenerationCliTests.cs b/Aetheris.CLI.Tests/DrawingGenerationCliTests.cs
index 7fa7c503..644d95a2 100644
--- a/Aetheris.CLI.Tests/DrawingGenerationCliTests.cs
+++ b/Aetheris.CLI.Tests/DrawingGenerationCliTests.cs
@@ -14,9 +14,12 @@ public sealed class DrawingGenerationCliTests
{
using var stdout = new StringWriter(); using var stderr = new StringWriter();
var source = Path.Combine(root.FullName, "fixtures/Regression/DrawingGeneration/inspection-plate.firmament");
- Assert.Equal(0, CliRunner.Run(["drawing", "generate", source, "--out-dir", output, "--drawn-by", "Codex (AI)", "--date", "2026-10-18", "--json"], stdout, stderr));
+ Assert.Equal(0, CliRunner.Run(["drawing", "generate", source, "--out-dir", output, "--drawn-by", "Codex (AI)", "--date", "2026-10-18", "--linear-tolerance", "0.1", "--angular-tolerance", "0.5", "--material", "6061-T6 aluminium", "--json"], stdout, stderr));
using var json = JsonDocument.Parse(stdout.ToString()); var result = json.RootElement;
Assert.True(result.GetProperty("success").GetBoolean());
+ Assert.True(result.GetProperty("definition").GetProperty("nominalGeometryComplete").GetBoolean());
+ Assert.True(result.GetProperty("definition").GetProperty("dimensionalTolerancesComplete").GetBoolean());
+ Assert.False(result.GetProperty("definition").GetProperty("processCapabilityVerified").GetBoolean());
foreach (var key in new[] { "pdfPath", "svgPath", "pptxPath", "drawingIrPath", "validationPath" }) Assert.True(File.Exists(result.GetProperty(key).GetString()));
Assert.Equal(0, result.GetProperty("layout").GetProperty("failedAnnotationCount").GetInt32());
using var ir = JsonDocument.Parse(File.ReadAllText(result.GetProperty("drawingIrPath").GetString()!));
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index e7f9637d..b71d90bb 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -167,7 +167,7 @@ public static class CliRunner
private const string ExperimentalPrismaticCorpusUsage = "Usage: aetheris experimental prismatic-corpus --out-dir <dir> [--json]";
private const string ExperimentalPrismaticMapUsage = "Usage: aetheris experimental prismatic-map --case <case> --rows <N> --cols <N> --json";
private const string FeaUsage = "Usage: aetheris fea <analysis.firmament> [--lattice <nx,ny,nz>] [--rotate <x,y,z-degrees>] [--experimental-preconditioner <identity|jacobi|block-jacobi|ic0>] [--experimental-equilibration <true|false>] [--out-dir <directory>] [--json]";
- private const string DrawingUsage = "Usage: aetheris drawing <compile|generate> <drawing.firmament|part.firmament|model.step> --out-dir <directory> [--drawn-by <name> --date <yyyy-MM-dd>] [--checked-by <name> --checked-date <yyyy-MM-dd>] [--approved-by <name> --approved-date <yyyy-MM-dd>] [--json] | aetheris drawing <inspect|render|crop|notes> ...";
+ private const string DrawingUsage = "Usage: aetheris drawing <compile|generate> <drawing.firmament|part.firmament|model.step> --out-dir <directory> [--drawn-by <name> --date <yyyy-MM-dd>] [--checked-by <name> --checked-date <yyyy-MM-dd>] [--approved-by <name> --approved-date <yyyy-MM-dd>] [--json] | generate options: [--linear-tolerance <mm>] [--angular-tolerance <degrees>] [--material <name>] [--reference-only] | aetheris drawing <inspect|render|crop|notes> ...";
private const string SheetMetalUsage = "Usage: aetheris sheetmetal recognize <part.step> [--plan <recognition.json>] [--json] | aetheris sheetmetal recover-flat <part.step> --out-dir <directory> [--recognition-plan <recognition.json>] [--json] | aetheris sheetmetal compare-flat <recovered-flat.json> <native.firmament> [--semantic] [--json] | aetheris sheetmetal inspect <part.step|part.firmament> [--k-factor <0..1>] [--json] | aetheris sheetmetal paths <part.firmament> [--json] | aetheris sheetmetal recover <part.step> --out-dir <directory> [--json] | aetheris sheetmetal compare <part.step|part.firmament> <intent.firmament> [--semantic] [--json] | aetheris sheetmetal flatten <part.step|part.firmament> [--step <flat.step>] [--firmament <recovered.firmament>] [--svg <flat.svg>] [--k-factor <0..1>] [--json]";
private const string ExperimentalLoopChamferCorpusUsage = "Usage: aetheris experimental loop-chamfer-corpus --out-dir <dir> [--json]";
private const string SculptureUsage = "Usage: aetheris sculpture build <sol-1.sculpture.json> [--out <sol-1.step>] [--evidence <sol-1.evidence.json>] [--preview <sol-1.preview.svg>] [--json]";
@@ -1179,10 +1179,23 @@ Model CanonicalPanel {
string? output = null;
var json = false;
var signoffValues = new Dictionary<string, string>(StringComparer.Ordinal);
+ var generationOptions = new DrawingGenerationOptions();
for (var i = 2; i < args.Length; i++)
{
if (args[i] == "--out-dir" && i + 1 < args.Length) output = args[++i];
else if (args[i] == "--json") json = true;
+ else if (args[i] == "--reference-only") generationOptions = generationOptions with { ReferenceOnly = true };
+ else if (args[i] == "--material" && i + 1 < args.Length) generationOptions = generationOptions with { Material = args[++i] };
+ else if (args[i] == "--angular-tolerance" && i + 1 < args.Length)
+ {
+ var angle = double.TryParse(args[++i], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var parsedAngle) ? parsedAngle : double.NaN;
+ generationOptions = generationOptions with { AngularToleranceDegrees = angle };
+ }
+ else if (args[i] == "--linear-tolerance" && i + 1 < args.Length)
+ {
+ var tolerance = double.TryParse(args[++i], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var parsedTolerance) ? parsedTolerance : double.NaN;
+ generationOptions = generationOptions with { LinearToleranceMillimetres = tolerance };
+ }
else if (args[i] is "--drawn-by" or "--date" or "--checked-by" or "--checked-date" or "--approved-by" or "--approved-date" && i + 1 < args.Length)
signoffValues[args[i]] = args[++i];
else { stderr.WriteLine($"Unknown drawing option '{args[i]}'."); stderr.WriteLine(DrawingUsage); return 1; }
@@ -1192,7 +1205,9 @@ Model CanonicalPanel {
new(signoffValues.GetValueOrDefault("--drawn-by"), signoffValues.GetValueOrDefault("--date")),
new(signoffValues.GetValueOrDefault("--checked-by"), signoffValues.GetValueOrDefault("--checked-date")),
new(signoffValues.GetValueOrDefault("--approved-by"), signoffValues.GetValueOrDefault("--approved-date")));
- var result = args[0] == "generate" ? FirmamentDrawingCompiler.Generate(source, output, signoff) : FirmamentDrawingCompiler.Compile(source, output, signoff);
+ if (args[0] == "compile" && generationOptions != new DrawingGenerationOptions())
+ { stderr.WriteLine("drawing-authored-options-unsupported: Generation options apply to drawing generate; authored requirements belong in its metadata."); return 1; }
+ var result = args[0] == "generate" ? FirmamentDrawingCompiler.Generate(source, output, signoff, generationOptions) : FirmamentDrawingCompiler.Compile(source, output, signoff);
if (!result.IsSuccess)
{
if (json) stdout.WriteLine(JsonSerializer.Serialize(new { success = false, diagnostics = result.KernelDiagnostics().Select(d=>FirmamentBuildAdmissionValidation.Present(d,source,File.Exists(source)?File.ReadAllText(source):null)).ToArray() }, JsonOptions));
@@ -1200,8 +1215,10 @@ Model CanonicalPanel {
return 1;
}
var artifacts = result.Artifacts!;
- if (json) stdout.WriteLine(JsonSerializer.Serialize(new { success = true, artifacts.DrawingIrPath, artifacts.SvgPath, artifacts.PdfPath, artifacts.PptxPath, artifacts.ReviewPptxPath, artifacts.DfmReviewPptxPath, artifacts.ReviewIrPath, artifacts.ValidationPath, artifacts.PdfSha256, artifacts.DrawingIrSha256, artifacts.PptxSha256, pageCount = artifacts.Drawing.Pages.Count, layout = artifacts.Drawing.LayoutEvidence }, JsonOptions));
+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { success = true, artifacts.DrawingIrPath, artifacts.SvgPath, artifacts.PdfPath, artifacts.PptxPath, artifacts.ReviewPptxPath, artifacts.DfmReviewPptxPath, artifacts.ReviewIrPath, artifacts.ValidationPath, artifacts.PdfSha256, artifacts.DrawingIrSha256, artifacts.PptxSha256, pageCount = artifacts.Drawing.Pages.Count, layout = artifacts.Drawing.LayoutEvidence, definition = artifacts.Drawing.DefinitionEvidence }, JsonOptions));
else stdout.WriteLine($"Compiled Drawing '{artifacts.Drawing.Identity}' to PDF and native editable PPTX ({artifacts.Drawing.Pages.Count} A4 page(s)).");
+ if (!json && artifacts.Drawing.DefinitionEvidence is { } definition)
+ stdout.WriteLine($"Nominal geometry complete: {definition.NominalGeometryComplete}; dimensional tolerances complete: {definition.DimensionalTolerancesComplete}; material specified: {definition.MaterialSpecified}; process capability verified: {definition.ProcessCapabilityVerified}.");
return 0;
}
diff --git a/Aetheris.Kernel.Core/Brep/Queries/BrepRectangularPlateQuery.cs b/Aetheris.Kernel.Core/Brep/Queries/BrepRectangularPlateQuery.cs
new file mode 100644
index 00000000..b60fdd9b
--- /dev/null
+++ b/Aetheris.Kernel.Core/Brep/Queries/BrepRectangularPlateQuery.cs
@@ -0,0 +1,164 @@
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Geometry.Curves;
+using Aetheris.Kernel.Core.Geometry.Surfaces;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Topology;
+
+namespace Aetheris.Kernel.Core.Brep.Queries;
+
+public sealed record RectangularPlateHole(FaceId Wall, double X, double Y, double Diameter);
+public sealed record RectangularPlateDefinition(Point3D Origin, double Width, double Height, double Thickness,
+ IReadOnlyList<RectangularPlateHole> Holes, IReadOnlyList<FaceId> CoveredFaces)
+{
+ public IReadOnlyList<EdgeId> StockEdges { get; init; } = [];
+}
+
+/// <summary>Exact, deliberately closed recognition of an axis-aligned rectangular plate with
+/// separated circular Z-through holes. Every face/loop/edge must be accounted for. No sampled
+/// bounding box, feature history or display mesh is used to claim a complete definition.</summary>
+public static class BrepRectangularPlateQuery
+{
+ private const double Epsilon = 1e-7;
+ public static bool TryDefine(BrepBody body, out RectangularPlateDefinition? definition, out string reason)
+ {
+ definition = null;
+ reason = "Complete dimension planning currently requires six rectangular stock planes and disjoint circular Z-through holes.";
+ var planes = new List<(Face Face, PlaneSurface Plane, int Axis)>();
+ var walls = new List<(Face Face, CylinderSurface Cylinder)>();
+ if (body.Topology.Bodies.Count() != 1 || body.Topology.Shells.Count() != 1) return false;
+ if (body.FaceOrientationReport is { } orientation && orientation.Shells.Any(s => !s.IsClosedManifold || s.Qualification != FaceOrientationQualification.DerivedQualified))
+ { reason = "Complete dimensions require a qualified closed shell with resolved material-side orientation."; return false; }
+ foreach (var face in body.Topology.Faces)
+ {
+ if (!body.TryGetFaceSurfaceGeometry(face.Id, out var surface)) return false;
+ if (surface?.Plane is { } plane)
+ {
+ var n = plane.Normal.ToVector();
+ var axis = Axis(n);
+ if (axis < 0) return false;
+ planes.Add((face, plane, axis));
+ }
+ else if (surface?.Cylinder is { } cylinder && Axis(cylinder.Axis.ToVector()) == 2)
+ {
+ if (!body.Bindings.TryGetFaceBinding(face.Id, out var binding) || binding.Orientation.IsAlignedWithSurface) return false;
+ walls.Add((face, cylinder));
+ }
+ else return false;
+ }
+ if (planes.Count != 6 || Enumerable.Range(0, 3).Any(a => planes.Count(p => p.Axis == a) != 2)) return false;
+ double Coordinate(Point3D p, int axis) => axis == 0 ? p.X : axis == 1 ? p.Y : p.Z;
+ var min = Enumerable.Range(0, 3).Select(a => planes.Where(p => p.Axis == a).Min(p => Coordinate(p.Plane.Origin, a))).ToArray();
+ var max = Enumerable.Range(0, 3).Select(a => planes.Where(p => p.Axis == a).Max(p => Coordinate(p.Plane.Origin, a))).ToArray();
+ if (Enumerable.Range(0, 3).Any(a => max[a] - min[a] <= Epsilon)) return false;
+ var holes = new List<RectangularPlateHole>();
+ var ringEdges = new HashSet<EdgeId>();
+ foreach (var (face, cylinder) in walls)
+ {
+ if (face.LoopIds.Count != 1) return false;
+ var uses = body.Topology.GetLoop(face.LoopIds[0]).CoedgeIds.Select(body.Topology.GetCoedge).ToArray();
+ var edges = uses.Select(c => c.EdgeId).Distinct().ToArray();
+ if (uses.Length != 4 || edges.Length != 3) return false;
+ var circles = new List<(EdgeId Id, Circle3Curve Circle)>();
+ EdgeId? seam = null;
+ foreach (var edge in edges)
+ {
+ if (!body.TryGetEdgeCurveGeometry(edge, out var curve)) return false;
+ if (curve?.Circle3 is { } circle)
+ {
+ if (!body.Bindings.TryGetEdgeBinding(edge, out var binding) || binding.TrimInterval is not { } interval
+ || System.Math.Abs(System.Math.Abs(interval.End - interval.Start) - 2 * System.Math.PI) > Epsilon) return false;
+ circles.Add((edge, circle));
+ }
+ else if (curve?.Line3 is { } line && Axis(line.Direction.ToVector()) == 2) seam = edge;
+ else return false;
+ }
+ if (circles.Count != 2 || seam is null || uses.Count(c => c.EdgeId == seam) != 2) return false;
+ if (!BoundLineMatchesVertices(body, seam.Value, out var seamA, out var seamB)
+ || !Near(seamA.X, seamB.X) || !Near(seamA.Y, seamB.Y)
+ || !Near(System.Math.Min(seamA.Z, seamB.Z), min[2]) || !Near(System.Math.Max(seamA.Z, seamB.Z), max[2])
+ || !Near(System.Math.Sqrt(System.Math.Pow(seamA.X - cylinder.Origin.X, 2) + System.Math.Pow(seamA.Y - cylinder.Origin.Y, 2)), cylinder.Radius)) return false;
+ var ordered = circles.OrderBy(c => c.Circle.Center.Z).ToArray();
+ if (!Near(ordered[0].Circle.Center.Z, min[2]) || !Near(ordered[1].Circle.Center.Z, max[2])) return false;
+ foreach (var (id, circle) in circles)
+ {
+ if (!Near(circle.Radius, cylinder.Radius) || !Near(circle.Center.X, cylinder.Origin.X)
+ || !Near(circle.Center.Y, cylinder.Origin.Y) || Axis(circle.Normal.ToVector()) != 2) return false;
+ if (!ringEdges.Add(id)) return false;
+ var edge = body.Topology.GetEdge(id);
+ foreach (var vertex in new[] { edge.StartVertexId, edge.EndVertexId })
+ if (!body.TryGetVertexPoint(vertex, out var point) || !Near(point.Z, circle.Center.Z)
+ || !Near(System.Math.Sqrt(System.Math.Pow(point.X - circle.Center.X, 2) + System.Math.Pow(point.Y - circle.Center.Y, 2)), circle.Radius)) return false;
+ }
+ var x = cylinder.Origin.X; var y = cylinder.Origin.Y; var r = cylinder.Radius;
+ if (x - r <= min[0] + Epsilon || x + r >= max[0] - Epsilon || y - r <= min[1] + Epsilon || y + r >= max[1] - Epsilon) return false;
+ if (holes.Any(h => System.Math.Sqrt(System.Math.Pow(h.X - x, 2) + System.Math.Pow(h.Y - y, 2)) <= h.Diameter / 2 + r + Epsilon)) return false;
+ holes.Add(new(face.Id, x, y, 2 * r));
+ }
+ var stockEdges = new HashSet<EdgeId>();
+ var planeRingUses = new Dictionary<EdgeId, int>();
+ foreach (var (face, plane, axis) in planes)
+ {
+ var rectangles = 0;
+ foreach (var loopId in face.LoopIds)
+ {
+ var edges = body.Topology.GetLoop(loopId).CoedgeIds.Select(body.Topology.GetCoedge).Select(c => c.EdgeId).ToArray();
+ if (edges.Length == 1 && ringEdges.Contains(edges[0]) && axis == 2)
+ {
+ body.TryGetEdgeCurveGeometry(edges[0], out var ring);
+ if (!Near(ring!.Circle3!.Value.Center.Z, plane.Origin.Z)) return false;
+ planeRingUses[edges[0]] = planeRingUses.GetValueOrDefault(edges[0]) + 1;
+ continue;
+ }
+ if (edges.Length != 4 || edges.Distinct().Count() != 4) return false;
+ var corners = new HashSet<(int, int, int)>();
+ foreach (var id in edges)
+ {
+ if (!body.TryGetEdgeCurveGeometry(id, out var curve) || curve?.Kind != CurveGeometryKind.Line3) return false;
+ if (!BoundLineMatchesVertices(body, id, out var a, out var b)) return false;
+ foreach (var point in new[] { a, b })
+ {
+ var indices = new int[3];
+ for (var i = 0; i < 3; i++)
+ {
+ var value = Coordinate(point, i);
+ indices[i] = Near(value, min[i]) ? 0 : Near(value, max[i]) ? 1 : -1;
+ if (indices[i] < 0 || i == axis && !Near(value, Coordinate(plane.Origin, axis))) return false;
+ }
+ corners.Add((indices[0], indices[1], indices[2]));
+ }
+ if (Enumerable.Range(0, 3).Count(i => !Near(Coordinate(a, i), Coordinate(b, i))) != 1) return false;
+ stockEdges.Add(id);
+ }
+ if (corners.Count != 4) return false;
+ rectangles++;
+ }
+ if (rectangles != 1) return false;
+ }
+ if (stockEdges.Count != 12 || ringEdges.Any(e => planeRingUses.GetValueOrDefault(e) != 1)
+ || body.Topology.Edges.Count() != 12 + 3 * holes.Count) return false;
+ definition = new(new(min[0], min[1], min[2]), max[0] - min[0], max[1] - min[1], max[2] - min[2],
+ holes.OrderBy(h => h.Y).ThenBy(h => h.X).ToArray(), body.Topology.Faces.Select(f => f.Id).ToArray()) { StockEdges = stockEdges.OrderBy(e => e.Value).ToArray() };
+ reason = "Every face and boundary is covered by exact stock planes and full circular through-hole walls.";
+ return true;
+ }
+
+ private static bool Near(double a, double b) => System.Math.Abs(a - b) <= Epsilon;
+ private static bool BoundLineMatchesVertices(BrepBody body, EdgeId id, out Point3D a, out Point3D b)
+ {
+ a = default; b = default;
+ var edge = body.Topology.GetEdge(id);
+ if (!body.TryGetVertexPoint(edge.StartVertexId, out a) || !body.TryGetVertexPoint(edge.EndVertexId, out b)
+ || !body.TryGetEdgeCurveGeometry(id, out var curve) || curve?.Line3 is not { } line
+ || !body.Bindings.TryGetEdgeBinding(id, out var binding) || binding.TrimInterval is not { } interval) return false;
+ var start = line.Evaluate(interval.Start); var end = line.Evaluate(interval.End);
+ return (a - start).Length <= Epsilon && (b - end).Length <= Epsilon || (a - end).Length <= Epsilon && (b - start).Length <= Epsilon;
+ }
+ private static int Axis(Vector3D v)
+ {
+ const double angularEpsilon = 1e-12;
+ var values = new[] { System.Math.Abs(v.X), System.Math.Abs(v.Y), System.Math.Abs(v.Z) };
+ for (var i = 0; i < 3; i++)
+ if (System.Math.Abs(values[i] - 1) <= angularEpsilon && Enumerable.Range(0, 3).Where(a => a != i).All(a => values[a] <= angularEpsilon)) return i;
+ return -1;
+ }
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/DrawingDimensionPlanningTests.cs b/Aetheris.Kernel.Firmament.Tests/DrawingDimensionPlanningTests.cs
new file mode 100644
index 00000000..4663da40
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/DrawingDimensionPlanningTests.cs
@@ -0,0 +1,147 @@
+using Aetheris.Kernel.Firmament.Drawing;
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class DrawingDimensionPlanningTests
+{
+ [Fact]
+ public void PlateDefinitionCoversEveryFaceAndPrintsItsIndependentDimensions()
+ {
+ using var scratch = new Scratch();
+ var result = FirmamentDrawingCompiler.Generate(Fixture(), scratch.Path, null, new(false, .1, "6061-T6 aluminium", .5));
+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics));
+ var drawing = result.Artifacts!.Drawing; var definition = drawing.DefinitionEvidence!;
+ Assert.True(definition.NominalGeometryComplete); Assert.True(definition.DimensionalTolerancesComplete);
+ Assert.True(definition.MaterialSpecified); Assert.False(definition.ProcessCapabilityVerified);
+ Assert.Equal(16, definition.CoveredFaces.Distinct().Count()); Assert.Empty(definition.MissingRequirements);
+ Assert.True(definition.MinimumHoleWebAtDeclaredLimitsMillimetres > 10);
+ var page = Assert.Single(drawing.Pages);
+ Assert.Contains(page.Annotations, a => a.Identity == "dimension:Width" && a.EngineeringDisplay == "100 ±0.1");
+ Assert.Contains(page.Annotations, a => a.Identity == "dimension:Height" && a.EngineeringDisplay == "70 ±0.1");
+ Assert.Contains(page.Annotations, a => a.Identity == "dimension:Thickness" && a.EngineeringDisplay == "8 ±0.1");
+ var table = Assert.Single(page.Tables); Assert.Equal(DrawingTableKind.HoleCoordinates, table.Kind);
+ Assert.Equal(10, table.Rows.Count);
+ Assert.Contains(table.Rows, r => r.SequenceEqual(new[] { "H1", "14", "17", "D1" }));
+ Assert.Contains(table.Rows, r => r.SequenceEqual(new[] { "H10", "86", "53", "D1" }));
+ var group = Assert.Single(page.Annotations, a => a.Identity.StartsWith("group:", StringComparison.Ordinal));
+ Assert.Equal("D1: 10X Ø4 +0.05/-0.02 THRU", group.EngineeringDisplay);
+ var front = page.Views.Single(v => v.Identity == "FRONT");
+ Assert.Equal(10, front.Primitives.Count(p => p.Kind == DrawingPrimitiveKind.Hidden));
+ var datum = page.Annotations.Single(a => a.Kind == DrawingAnnotationKind.Datum);
+ Assert.Equal("FRONT", datum.AssignedView); Assert.Equal(front.GeometryBounds.Y, datum.ProjectedAnchor.Y, 8);
+ Assert.Equal(0, drawing.LayoutEvidence.TextTextCollisionsAfter + drawing.LayoutEvidence.TextModelCollisionsAfter + drawing.LayoutEvidence.TextLeaderCollisionsAfter);
+ using var presentation = DocumentFormat.OpenXml.Packaging.PresentationDocument.Open(result.Artifacts.PptxPath, false);
+ Assert.Empty(new DocumentFormat.OpenXml.Validation.OpenXmlValidator().Validate(presentation));
+ }
+
+ [Fact]
+ public void PerturbedNonGridCentersAreMeasuredAndKeepAuthoredIdentities()
+ {
+ using var scratch = new Scratch();
+ var path = System.IO.Path.Combine(scratch.Path, "asymmetric.firmament");
+ File.WriteAllText(path, File.ReadAllText(Fixture()).Replace("Point2(-36mm, -18mm)", "Point2(-34.125mm, -17.25mm)", StringComparison.Ordinal));
+ var result = FirmamentDrawingCompiler.Generate(path, System.IO.Path.Combine(scratch.Path, "out"));
+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics));
+ var hole = result.Artifacts!.Drawing.DefinitionEvidence!.Holes.Single(h => h.Identity == "H1");
+ Assert.Equal(15.875, hole.X, 8); Assert.Equal(17.75, hole.Y, 8);
+ Assert.Contains(result.Artifacts.Drawing.Pages.Single().Tables.Single().Rows, r => r.SequenceEqual(new[] { "H1", "15.875", "17.75", "D1" }));
+ }
+
+ [Theory]
+ [InlineData("Model Egg { units: mm Sphere Stock { radius: 10mm } }", false)]
+ [InlineData("Model Blind { units: mm Box Stock { size: [40mm, 30mm, 8mm] } Modify Stock { Hole<Shaft> Bore { on: +Z; center: Point2(0mm, 0mm); diameter: 4mm; end: Blind 3mm } } }", true)]
+ public void UncoveredGeometryCannotBecomeACompleteDefinition(string source, bool referenceSupported)
+ {
+ using var scratch = new Scratch(); var path = System.IO.Path.Combine(scratch.Path, "input.firmament"); File.WriteAllText(path, source);
+ var compiled = FirmamentBuildAndExport.CompileSource(source); Assert.True(compiled.IsSuccess, string.Join("\n", compiled.Diagnostics));
+ var result = FirmamentDrawingCompiler.Generate(path, System.IO.Path.Combine(scratch.Path, "out"));
+ Assert.False(result.IsSuccess); Assert.Contains(result.Diagnostics, d => d.StartsWith("drawing-definition-incomplete:", StringComparison.Ordinal));
+ var reference = FirmamentDrawingCompiler.Generate(path, System.IO.Path.Combine(scratch.Path, "reference"), null, new(ReferenceOnly: true));
+ Assert.Equal(referenceSupported, reference.IsSuccess);
+ if (!referenceSupported) { Assert.Contains(reference.Diagnostics, d => d.StartsWith("drawing-projection-unsupported:", StringComparison.Ordinal)); return; }
+ Assert.False(reference.Artifacts!.Drawing.DefinitionEvidence!.NominalGeometryComplete);
+ Assert.Contains(reference.Artifacts.Drawing.Pages[0].Notes, n => n.Contains("NOT FOR MANUFACTURE", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void MissingRequirementsRemainMissing()
+ {
+ using var scratch = new Scratch(); var result = FirmamentDrawingCompiler.Generate(Fixture(), scratch.Path);
+ Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics));
+ var evidence = result.Artifacts!.Drawing.DefinitionEvidence!;
+ Assert.True(evidence.NominalGeometryComplete); Assert.False(evidence.DimensionalTolerancesComplete);
+ Assert.False(evidence.MaterialSpecified); Assert.Null(evidence.LinearToleranceMillimetres); Assert.Null(evidence.AngularToleranceDegrees);
+ Assert.Equal(3, evidence.MissingRequirements.Count);
+ Assert.Contains(result.Artifacts.Drawing.Pages[0].Notes, n => n.Contains("NOT FOR MANUFACTURE", StringComparison.Ordinal));
+ }
+
+ [Theory]
+ [InlineData(.0)]
+ [InlineData(-.1)]
+ [InlineData(double.NaN)]
+ public void InvalidLinearToleranceRejects(double tolerance)
+ {
+ using var scratch = new Scratch();
+ var result = FirmamentDrawingCompiler.Generate(Fixture(), scratch.Path, null, new(LinearToleranceMillimetres: tolerance));
+ Assert.False(result.IsSuccess); Assert.Contains(result.Diagnostics, d => d.StartsWith("drawing-linear-tolerance-invalid:", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void ToleranceLimitsCannotPermitEdgeBreakout()
+ {
+ using var scratch = new Scratch(); var path = System.IO.Path.Combine(scratch.Path, "near-edge.firmament");
+ File.WriteAllText(path, File.ReadAllText(Fixture()).Replace("Point2(-36mm, -18mm)", "Point2(-47.5mm, -18mm)", StringComparison.Ordinal));
+ var result = FirmamentDrawingCompiler.Generate(path, System.IO.Path.Combine(scratch.Path, "out"), null, new(false, 1, "6061-T6", .5));
+ Assert.False(result.IsSuccess); Assert.Contains(result.Diagnostics, d => d.StartsWith("drawing-tolerance-envelope-invalid:", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void ContradictoryDiameterCannotBePrintedAsAControllingSize()
+ {
+ using var scratch = new Scratch(); var path = System.IO.Path.Combine(scratch.Path, "wrong-size.firmament");
+ File.WriteAllText(path, File.ReadAllText(Fixture()).Replace("value: 4mm", "value: 3mm", StringComparison.Ordinal));
+ var result = FirmamentDrawingCompiler.Generate(path, System.IO.Path.Combine(scratch.Path, "out"));
+ Assert.False(result.IsSuccess); Assert.Contains(result.Diagnostics, d => d.StartsWith("drawing-pmi-geometry-mismatch:", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void ReferenceOnlyCannotSilentlyConsumeManufacturingInputs()
+ {
+ using var scratch = new Scratch();
+ var result = FirmamentDrawingCompiler.Generate(Fixture(), scratch.Path, null, new(true, .1));
+ Assert.False(result.IsSuccess); Assert.Contains(result.Diagnostics, d => d.StartsWith("drawing-reference-options-unsupported:", StringComparison.Ordinal));
+ }
+
+ [Theory]
+ [InlineData(3, null)]
+ [InlineData(8, 2)]
+ public void ContradictoryDepthOrQuantityCannotDisappear(double depth, int? quantity)
+ {
+ using var scratch = new Scratch();
+ var compiled = FirmamentBuildAndExport.CompileSource(File.ReadAllText(Fixture())); Assert.True(compiled.IsSuccess);
+ var body = Step242Importer.ImportBody(compiled.Value.StepText).Value;
+ var wall = body.Topology.Faces.First(f => body.TryGetFaceSurfaceGeometry(f.Id, out var s) && s?.Cylinder is not null);
+ var exported = Step242Exporter.ExportBody(body,
+ [new Step242SemanticPmiHole("Stock.H1", 4, depth, "through", .05, .02, quantity) { GeometricFaceIds = [wall.Id.Value] }]);
+ Assert.True(exported.IsSuccess);
+ var path = System.IO.Path.Combine(scratch.Path, "contradiction.step"); File.WriteAllText(path, exported.Value);
+ var result = FirmamentDrawingCompiler.Generate(path, System.IO.Path.Combine(scratch.Path, "out"));
+ Assert.False(result.IsSuccess); Assert.Contains(result.Diagnostics, d => d.StartsWith("drawing-pmi-geometry-mismatch:", StringComparison.Ordinal));
+ Assert.False(Directory.Exists(System.IO.Path.Combine(scratch.Path, "out")));
+ }
+
+ private static string Root()
+ {
+ var directory = new DirectoryInfo(AppContext.BaseDirectory);
+ while (directory is not null && !File.Exists(System.IO.Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;
+ return directory!.FullName;
+ }
+ private static string Fixture() => System.IO.Path.Combine(Root(), "fixtures/Regression/DrawingGeneration/inspection-plate.firmament");
+ private sealed class Scratch : IDisposable
+ {
+ public string Path { get; } = System.IO.Path.Combine(Root(), "artifacts/local/tests/drawing-definition", Guid.NewGuid().ToString("N"));
+ public Scratch() => Directory.CreateDirectory(Path);
+ public void Dispose() => Directory.Delete(Path, true);
+ }
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/DrawingGenerationTests.cs b/Aetheris.Kernel.Firmament.Tests/DrawingGenerationTests.cs
index 8d8843ad..cd110d09 100644
--- a/Aetheris.Kernel.Firmament.Tests/DrawingGenerationTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/DrawingGenerationTests.cs
@@ -20,9 +20,11 @@ public sealed class DrawingGenerationTests
var exchanged = FirmamentDrawingCompiler.Generate(step, Path.Combine(scratch.Path, "step"));
Assert.True(exchanged.IsSuccess, string.Join("\n", exchanged.Diagnostics));
var drawing = part.Artifacts!.Drawing;
- Assert.True(drawing.Pages.Count >= 3); // dense top-view callouts paginate
+ Assert.Single(drawing.Pages); // a complete coordinate schedule avoids duplicate diameter sheets
var annotations = drawing.Pages.SelectMany(p => p.Annotations).ToArray();
- Assert.Equal(10, annotations.Count(a => Enumerable.Range(1, 10).Any(n => a.SemanticReference.EndsWith(":Size" + n, StringComparison.Ordinal))));
+ Assert.Equal(10, drawing.DefinitionEvidence!.Holes.Count);
+ Assert.Equal(10, drawing.DefinitionEvidence.Holes.SelectMany(h => h.SourceReferences).Count());
+ Assert.True(drawing.DefinitionEvidence.NominalGeometryComplete);
Assert.Equal(annotations.Select(a => a.EngineeringDisplay), exchanged.Artifacts!.Drawing.Pages.SelectMany(p => p.Annotations).Select(a => a.EngineeringDisplay));
Assert.Equal(drawing.Pages.SelectMany(p => p.Views).SelectMany(v => v.Primitives).SelectMany(p => p.Points),
exchanged.Artifacts.Drawing.Pages.SelectMany(p => p.Views).SelectMany(v => v.Primitives).SelectMany(p => p.Points));
@@ -30,9 +32,9 @@ public sealed class DrawingGenerationTests
Assert.Equal(0, drawing.LayoutEvidence.TextTextCollisionsAfter);
Assert.Equal(0, drawing.LayoutEvidence.TextLeaderCollisionsAfter);
Assert.Equal(0, drawing.LayoutEvidence.FailedAnnotationCount);
- Assert.Contains(annotations, a => a.EngineeringDisplay.Contains("Ø4 mm +0.05/-0.02", StringComparison.Ordinal));
+ Assert.Contains(annotations, a => a.EngineeringDisplay.Contains("Ø4 +0.05/-0.02", StringComparison.Ordinal));
Assert.Contains(annotations, a => a.DimensionLines.Count > 0);
- Assert.Contains(drawing.Pages.SelectMany(p => p.Views).SelectMany(v => v.Primitives), p => p.Kind == DrawingPrimitiveKind.SurfaceGrid);
+ Assert.Contains(drawing.Pages.SelectMany(p => p.Views).SelectMany(v => v.Primitives), p => p.Kind == DrawingPrimitiveKind.CenterMark);
Assert.True(annotations.Select(a => a.ProjectedAnchor).Distinct().Count() >= 10);
Assert.All(annotations.Where(a => a.SemanticReference.StartsWith("step:", StringComparison.Ordinal)), a => { Assert.Contains("STEP #", a.Provenance); Assert.Equal(a.ProjectedAnchor, a.SelectedCandidate.Leader[0]); });
foreach (var page in drawing.Pages)
@@ -42,7 +44,7 @@ public sealed class DrawingGenerationTests
}
Assert.True(File.Exists(part.Artifacts.PdfPath)); Assert.True(File.Exists(part.Artifacts.PptxPath));
var svg = File.ReadAllText(part.Artifacts.SvgPath);
- Assert.Contains("surfacegrid", svg); Assert.Contains("data-semantic-reference", svg);
+ Assert.Contains("centermark", svg); Assert.Contains("data-semantic-reference", svg);
}
[Fact]
@@ -80,8 +82,9 @@ public sealed class DrawingGenerationTests
File.WriteAllText(path, "Model Plain { units: mm Box Stock { size: [30mm, 20mm, 10mm] } }");
var result = FirmamentDrawingCompiler.Generate(path, Path.Combine(scratch.Path, "out"));
Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics));
- Assert.All(result.Artifacts!.Drawing.Pages.SelectMany(p => p.Annotations), a => Assert.StartsWith("reference:", a.SemanticReference));
- Assert.Contains(result.Artifacts.Drawing.Pages[0].Notes, n => n.Contains("NO SUPPORTED SEMANTIC PMI", StringComparison.Ordinal));
+ Assert.True(result.Artifacts!.Drawing.DefinitionEvidence!.NominalGeometryComplete);
+ Assert.False(result.Artifacts.Drawing.DefinitionEvidence.DimensionalTolerancesComplete);
+ Assert.Contains(result.Artifacts.Drawing.Pages[0].Notes, n => n.Contains("TOLERANCES UNSPECIFIED", StringComparison.Ordinal));
}
[Fact]
@@ -89,7 +92,7 @@ public sealed class DrawingGenerationTests
{
using var scratch = new Scratch(); var path = Path.Combine(scratch.Path, "long.firmament");
File.WriteAllText(path, File.ReadAllText(Fixture()).Replace("Size1 {", "InspectionRequirementForFirstMountingBoreDiameter {", StringComparison.Ordinal));
- var result = FirmamentDrawingCompiler.Generate(path, Path.Combine(scratch.Path, "out"));
+ var result = FirmamentDrawingCompiler.Generate(path, Path.Combine(scratch.Path, "out"), null, new(ReferenceOnly: true));
Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics));
var label = result.Artifacts!.Drawing.Pages.SelectMany(p => p.Annotations).Single(a => a.EngineeringDisplay.StartsWith("InspectionRequirement", StringComparison.Ordinal));
Assert.True(label.SelectedCandidate.Body.Width > 58);
@@ -121,7 +124,8 @@ public sealed class DrawingGenerationTests
var path = Path.Combine(scratch.Path, "depth.step"); File.WriteAllText(path, exported.Value);
var result = FirmamentDrawingCompiler.Generate(path, Path.Combine(scratch.Path, "out"));
Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics));
- Assert.Contains(result.Artifacts!.Drawing.Pages.SelectMany(p => p.Annotations), a => a.EngineeringDisplay.Contains("DEPTH 8 mm", StringComparison.Ordinal));
+ Assert.Equal(8, result.Artifacts!.Drawing.DefinitionEvidence!.StockDimensions["Thickness"]);
+ Assert.All(result.Artifacts.Drawing.DefinitionEvidence.Holes, h => Assert.Equal("THRU", h.Extent));
}
[Fact]
@@ -146,7 +150,7 @@ public sealed class DrawingGenerationTests
{
using var stream = slide.Open(); var xml = System.Xml.Linq.XDocument.Load(stream);
System.Xml.Linq.XNamespace a = "http://schemas.openxmlformats.org/drawingml/2006/main";
- var table = Assert.Single(xml.Descendants(a + "tbl"));
+ var table = Assert.Single(xml.Descendants(a + "tbl"), t => t.Descendants(a + "gridCol").Count() == 6);
Assert.Equal(6, table.Descendants(a + "gridCol").Count());
Assert.All(table.Elements(a + "tr"), row => Assert.Equal(6, row.Elements(a + "tc").Count()));
}
@@ -185,7 +189,7 @@ public sealed class DrawingGenerationTests
}
}
""");
- var result = FirmamentDrawingCompiler.Generate(path, Path.Combine(scratch.Path, "out"));
+ var result = FirmamentDrawingCompiler.Generate(path, Path.Combine(scratch.Path, "out"), null, new(ReferenceOnly: true));
Assert.True(result.IsSuccess, string.Join("\n", result.Diagnostics));
var page = result.Artifacts!.Drawing.Pages.Single(p => p.Annotations.Any(a => a.Kind == DrawingAnnotationKind.DiameterDimension));
var annotation = page.Annotations.Single(a => a.Kind == DrawingAnnotationKind.DiameterDimension);
@@ -242,7 +246,7 @@ public sealed class DrawingGenerationTests
Assert.Equal(admitted, result.IsSuccess);
if (admitted)
Assert.Contains(result.Artifacts!.Drawing.Pages.SelectMany(p => p.Annotations),
- a => a.Kind == DrawingAnnotationKind.DiameterDimension && a.EngineeringDisplay.Contains("Ø4 mm", StringComparison.Ordinal));
+ a => a.Kind == DrawingAnnotationKind.DiameterDimension && a.EngineeringDisplay.Contains("Ø4", StringComparison.Ordinal));
else
{
Assert.Contains(result.Diagnostics, d => d.StartsWith("drawing-pmi-family-unsupported:", StringComparison.Ordinal));
diff --git a/Aetheris.Kernel.Firmament/Drawing/DrawingAnnotationLayout.cs b/Aetheris.Kernel.Firmament/Drawing/DrawingAnnotationLayout.cs
index 7b83dfa9..495ac1ec 100644
--- a/Aetheris.Kernel.Firmament/Drawing/DrawingAnnotationLayout.cs
+++ b/Aetheris.Kernel.Firmament/Drawing/DrawingAnnotationLayout.cs
@@ -21,12 +21,14 @@ internal static class DrawingAnnotationLayout
occupied.AddRange(page.Views.Select(v => new DrawingRect(v.Viewport.X, v.Viewport.Y, v.Viewport.Width, 6)));
occupied.AddRange((page.LocatedNotes ?? []).Select(n => n.Bounds));
if (page.InformationBlock is { } info) occupied.Add(info.Bounds);
+ occupied.AddRange(page.Tables.Select(t => t.Bounds));
var annotations = new List<DrawingAnnotationIr>(page.Annotations);
occupied.AddRange(annotations.Select(a => a.SelectedCandidate.Body));
foreach (var seed in annotations)
{
var owner = page.Views.Single(v => v.Identity == seed.AssignedView);
- if (!Contains(owner.Viewport, seed.SelectedCandidate.Body) || page.Views.Any(v => CollidesModel(seed.SelectedCandidate.Body, v)))
+ if (!Contains(owner.Viewport, seed.SelectedCandidate.Body) || page.Views.Any(v => CollidesModel(seed.SelectedCandidate.Body, v))
+ || page.Tables.Any(t => t.Bounds.Intersects(seed.SelectedCandidate.Body)))
{
failed++;
diagnostics.Add($"{FirmamentDrawingCompiler.DrawingLayoutImpossible}: Reference measurement '{seed.Identity}' exceeds its sheet allocation or overlaps geometry.");
diff --git a/Aetheris.Kernel.Firmament/Drawing/DrawingDimensionPlanning.cs b/Aetheris.Kernel.Firmament/Drawing/DrawingDimensionPlanning.cs
new file mode 100644
index 00000000..778be7f0
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/Drawing/DrawingDimensionPlanning.cs
@@ -0,0 +1,225 @@
+using System.Globalization;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.Queries;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Core.Topology;
+
+namespace Aetheris.Kernel.Firmament.Drawing;
+
+public static partial class FirmamentDrawingCompiler
+{
+ private sealed record HoleGroup(string Identity, double Diameter, double? Plus, double? Minus);
+
+ private static DrawingCompileResult GenerateDefinedPart(string path, string source, string name, string sourceKind,
+ BrepBody body, IReadOnlyList<Step242SemanticPmiInspectionItem> pmi, IReadOnlyDictionary<int, FaceId> faceMap,
+ DrawingSignoffIr? signoff, DrawingGenerationOptions options, string outputDirectory)
+ {
+ if (!BrepRectangularPlateQuery.TryDefine(body, out var plate, out var reason))
+ return Failure($"drawing-definition-incomplete: {reason} Use an authored drawing with complete dimensions, or --reference-only for explicitly incomplete visualization.");
+ var groups = new List<HoleGroup>();
+ var holes = new List<DrawingDefinedHoleIr>();
+ var consumed = new HashSet<int>();
+ foreach (var hole in plate!.Holes)
+ {
+ var sizePmi = pmi.Where(item => (item.Kind == "Diameter" || item.DimensionKind?.ToLowerInvariant() is "diameter" or "holediameter")
+ && item.GeometricFaceEntityIds.Any(id => faceMap.GetValueOrDefault(id) == hole.Wall)).ToArray();
+ if (sizePmi.Any(item => item.Value is not { } value || Math.Abs(value - hole.Diameter) > 1e-7))
+ return Failure($"drawing-pmi-geometry-mismatch: Diameter PMI on face {hole.Wall.Value} disagrees with its exact cylinder. A conflicting dimension was not emitted.");
+ if (sizePmi.Any(item => item.Depth is { } depth && Math.Abs(depth - plate.Thickness) > 1e-7))
+ return Failure($"drawing-pmi-geometry-mismatch: Hole depth PMI on face {hole.Wall.Value} disagrees with the through-hole thickness.");
+ if (sizePmi.Any(item => item.Quantity is { } quantity && quantity != plate.Holes.Count(h => item.GeometricFaceEntityIds.Any(id => faceMap.GetValueOrDefault(id) == h.Wall))))
+ return Failure($"drawing-pmi-geometry-mismatch: Hole quantity PMI on face {hole.Wall.Value} disagrees with its associated physical holes.");
+ if (sizePmi.Select(i => (i.TolerancePlus, i.ToleranceMinus)).Distinct().Count() > 1)
+ return Failure($"drawing-pmi-conflicting-requirements: Face {hole.Wall.Value} has conflicting diameter limits.");
+ var plus = sizePmi.FirstOrDefault()?.TolerancePlus; var minus = sizePmi.FirstOrDefault()?.ToleranceMinus;
+ if (new[] { plus, minus }.Any(v => v is { } n && (!double.IsFinite(n) || n < 0)))
+ return Failure("drawing-pmi-value-unavailable: Diameter tolerance must be finite and nonnegative.");
+ if (minus is { } m && hole.Diameter - m <= 0) return Failure("drawing-pmi-value-unavailable: Diameter limits must be positive.");
+ if (plus is { } p && minus is { } lower && p + lower <= 0) return Failure("drawing-tolerance-zero-width: A zero-width diameter acceptance interval is not an admitted manufacturing requirement.");
+ var group = groups.FirstOrDefault(g => g.Diameter == hole.Diameter && g.Plus == plus && g.Minus == minus);
+ if (group is null) { group = new("D" + (groups.Count + 1), hole.Diameter, plus, minus); groups.Add(group); }
+ var authoredIdentities = sizePmi.Select(i => i.Target.Split('.').Last()).Distinct(StringComparer.Ordinal).ToArray();
+ var authoredIdentity = authoredIdentities.Length == 1 ? authoredIdentities[0] : null;
+ var identity = authoredIdentity is { Length: > 0 } && authoredIdentity.All(c => char.IsLetterOrDigit(c) || c == '_')
+ && holes.All(h => h.Identity != authoredIdentity) ? authoredIdentity : "H" + hole.Wall.Value;
+ if (holes.Any(h => h.Identity == identity)) identity = "Face" + hole.Wall.Value;
+ holes.Add(new(identity, hole.X - plate.Origin.X, hole.Y - plate.Origin.Y, hole.Diameter, "THRU", group.Identity,
+ sizePmi.Select(i => $"STEP #{i.EntityId}: {i.AuthoredName ?? i.Name}; {i.Target}").ToArray()));
+ foreach (var item in sizePmi) consumed.Add(item.EntityId);
+ }
+ var datums = pmi.Where(i => i.Kind == "Datum").ToArray();
+ foreach (var datum in datums) consumed.Add(datum.EntityId);
+ var unconsumed = pmi.Where(i => !consumed.Contains(i.EntityId)).ToArray();
+ if (unconsumed.Length > 0) return Failure($"drawing-definition-pmi-unsupported: Complete plate planning cannot yet place these requirements without losing their meaning: {string.Join(", ", unconsumed.Select(i => i.AuthoredName ?? i.Name))}. They were not omitted; use an authored drawing or --reference-only.");
+ if (groups.Count > 4) return Failure("drawing-layout-impossible: More than four distinct hole specifications require an authored hole-schedule sheet.");
+
+ var missing = new List<string>();
+ if (options.LinearToleranceMillimetres is null) missing.Add("Stock-size and X/Y coordinate tolerances are unspecified.");
+ if (options.AngularToleranceDegrees is null) missing.Add("General angular tolerance is unspecified.");
+ if (groups.Any(g => g.Plus is null || g.Minus is null)) missing.Add("One or more hole diameter tolerances are unspecified.");
+ if (string.IsNullOrWhiteSpace(options.Material)) missing.Add("Material is unspecified.");
+ var web = MinimumHoleWeb(plate, holes, groups, options);
+ if (web is <= 0 || options.LinearToleranceMillimetres is { } stockTolerance && stockTolerance >= Math.Min(plate.Width, Math.Min(plate.Height, plate.Thickness)))
+ return Failure("drawing-tolerance-envelope-invalid: Declared limits permit zero stock thickness, intersecting holes or an edge breakout. Revise the requirements; a nominal picture does not establish admissible limits.");
+ var evidence = new DrawingDefinitionEvidenceIr(true, options.LinearToleranceMillimetres.HasValue && options.AngularToleranceDegrees.HasValue && groups.All(g => g.Plus.HasValue && g.Minus.HasValue),
+ !string.IsNullOrWhiteSpace(options.Material), false, "RectangularPlateWithZThroughHoles", plate.CoveredFaces.Select(f => f.Value).ToArray(), missing,
+ new Dictionary<string, double> { ["Width"] = plate.Width, ["Height"] = plate.Height, ["Thickness"] = plate.Thickness }, holes, options.LinearToleranceMillimetres)
+ { AngularToleranceDegrees = options.AngularToleranceDegrees, MinimumHoleWebAtDeclaredLimitsMillimetres = web };
+ var metadata = new DrawingMetadataIr(name + " - dimensioned plate", name, null, null, options.Material,
+ name + "Drawing", "CompletePlateDimensions", Author: signoff?.Drawn.Name, Date: signoff?.Drawn.Date,
+ Description: "Exact nominal dimensions; manufacturing release and process capability require engineering review") { Signoff = signoff };
+ var notes = new List<string> { "DIMENSIONS IN mm. DO NOT SCALE DRAWING.", "X FROM LEFT FINISHED EDGE; Y FROM BOTTOM FINISHED EDGE.",
+ options.LinearToleranceMillimetres is { } tol ? $"STOCK SIZES AND X/Y COORDINATES: ±{Number(tol)} mm." : "STOCK / COORDINATE TOLERANCES UNSPECIFIED - NOT FOR MANUFACTURE.",
+ options.AngularToleranceDegrees is { } a ? $"UNLESS SPECIFIED: ANGLES ±{Number(a)}°." : "ANGULAR TOLERANCE UNSPECIFIED - NOT FOR MANUFACTURE.",
+ "X/Y AT TOP FACE; HOLE AXES NOMINALLY NORMAL; THRU.",
+ "NOMINAL GEOMETRY COMPLETE. PROCESS CAPABILITY NOT VERIFIED." };
+ if (string.IsNullOrWhiteSpace(options.Material)) notes.Add("MATERIAL UNSPECIFIED - NOT FOR MANUFACTURE.");
+ if (groups.Any(g => g.Plus is null || g.Minus is null)) notes.Add("HOLE SIZE TOLERANCES UNSPECIFIED - NOT FOR MANUFACTURE.");
+ var chunks = holes.Count == 0 ? new[] { Array.Empty<DrawingDefinedHoleIr>() } : holes.Chunk(12).ToArray();
+ var pages = new List<DrawingPageIr>();
+ var scale = StandardScale(Math.Min(Math.Min(105 / plate.Width, 75 / plate.Height), 12 / plate.Thickness));
+ var top = PlaceDefinitionView(body, name, "TOP", [0, 0, 1], new(30, 40, 110, 75), scale, new(12, 18, 273, 135));
+ var front = PlaceDefinitionView(body, name, "FRONT", [0, -1, 0], new(30, 136, 110, 12), scale, new(12, 123, 273, 30));
+ var annotations = new List<DrawingAnnotationIr>();
+ DrawingPoint2 Project(DrawingViewIr view, Point3D point) => new(view.Camera!.OriginX + view.Scale * (point.X * view.Camera.Right[0] + point.Y * view.Camera.Right[1] + point.Z * view.Camera.Right[2]),
+ view.Camera.OriginY - view.Scale * (point.X * view.Camera.Up[0] + point.Y * view.Camera.Up[1] + point.Z * view.Camera.Up[2]));
+ string Linear(double value) => Number(value) + (options.LinearToleranceMillimetres is { } t ? " ±" + Number(t) : "");
+ var b = top.GeometryBounds; var f = front.GeometryBounds;
+ annotations.Add(Measure("Width", "TOP", Linear(plate.Width), new(b.X, b.Y), new(b.Right, b.Y), b.Y - 9, true));
+ annotations.Add(Measure("Height", "TOP", Linear(plate.Height), new(b.Right, b.Y), new(b.Right, b.Bottom), b.Right + 8, false));
+ annotations.Add(Measure("Thickness", "FRONT", Linear(plate.Thickness), new(f.Right, f.Y), new(f.Right, f.Bottom), f.Right + 8, false));
+ var primitives = top.Primitives.ToList();
+ foreach (var hole in holes)
+ {
+ var point = Project(top, new(plate.Origin.X + hole.X, plate.Origin.Y + hole.Y, plate.Origin.Z + plate.Thickness));
+ var r = hole.Diameter * scale / 2;
+ primitives.Add(new($"center:{hole.Identity}:x", DrawingPrimitiveKind.CenterMark, [new(point.X - r - 1, point.Y), new(point.X + r + 1, point.Y)], name, 0));
+ primitives.Add(new($"center:{hole.Identity}:y", DrawingPrimitiveKind.CenterMark, [new(point.X, point.Y - r - 1), new(point.X, point.Y + r + 1)], name, 0));
+ annotations.Add(DefinedLabel(hole.Identity, "TOP", hole.Identity, new(point.X + r + 1.5, point.Y - r - 5), [], point,
+ $"Coordinate schedule: {hole.X:R}, {hole.Y:R}; {string.Join("; ", hole.SourceReferences)}"));
+ }
+ top = top with { Primitives = primitives };
+ // The qualified family proves these internal cylinder silhouettes. A cylindrical
+ // parameter seam is not an external physical edge in a manufacturing side view.
+ var stockIds = plate.StockEdges.Select(e => $"edge:{e.Value}").ToHashSet();
+ var frontEdges = front.Primitives.Where(p => p.SourceEdgeIdentity is { } id && stockIds.Contains(id)).ToList();
+ var hiddenLines = new HashSet<(double X, double Radius)>();
+ foreach (var hole in holes)
+ {
+ if (!hiddenLines.Add((hole.X, hole.Diameter / 2))) continue;
+ foreach (var dx in new[] { -hole.Diameter / 2, hole.Diameter / 2 })
+ {
+ var x = plate.Origin.X + hole.X + dx;
+ frontEdges.Add(new($"internal:{hole.Identity}:{dx:R}", DrawingPrimitiveKind.Hidden,
+ [Project(front, new(x, plate.Origin.Y, plate.Origin.Z)), Project(front, new(x, plate.Origin.Y, plate.Origin.Z + plate.Thickness))], name, 0));
+ }
+ }
+ front = front with { Primitives = frontEdges };
+ foreach (var datum in datums)
+ {
+ var faceIds = datum.GeometricFaceEntityIds.Where(faceMap.ContainsKey).Select(id => faceMap[id]).Distinct().ToArray();
+ if (faceIds.Length != 1 || !body.TryGetFaceSurfaceGeometry(faceIds[0], out var support) || support?.Plane is not { } plane)
+ return Failure($"drawing-pmi-target-unlocated: Datum '{datum.Name}' does not identify a unique plate plane.");
+ var n = plane.Normal.ToVector();
+ var view = Math.Abs(n.Z) > .9 ? front : top;
+ var location = Math.Abs(n.Z) > .9 ? new Point3D(plate.Origin.X + plate.Width * .75, plate.Origin.Y, plane.Origin.Z)
+ : Math.Abs(n.X) > .9 ? new(plane.Origin.X, plate.Origin.Y + plate.Height * .75, plate.Origin.Z + plate.Thickness)
+ : new(plate.Origin.X + plate.Width * .75, plane.Origin.Y, plate.Origin.Z + plate.Thickness);
+ var anchor = Project(view, location);
+ var label = DefinedLabel("datum:" + datum.Name, view.Identity, datum.Name, new(anchor.X - 3, anchor.Y - 12), [anchor, new(anchor.X, anchor.Y - 6)], anchor,
+ $"STEP #{datum.EntityId}; face {faceIds[0].Value}; plane {plane.Origin}") with { Kind = DrawingAnnotationKind.Datum };
+ annotations.Add(label);
+ }
+ for (var i = 0; i < groups.Count; i++)
+ {
+ var group = groups[i]; var members = holes.Where(h => h.Group == group.Identity).ToArray();
+ var limits = group.Plus is { } plus && group.Minus is { } minus ? $" +{Number(plus)}/-{Number(minus)}" : " (TOL UNSPECIFIED)";
+ var display = $"{group.Identity}: {members.Length}X Ø{Number(group.Diameter)}{limits} THRU";
+ annotations.Add(DefinedLabel("group:" + group.Identity, "TOP", display, new(190, 116 + i * 8), [], default,
+ string.Join("; ", members.SelectMany(h => h.SourceReferences))) with { Kind = DrawingAnnotationKind.DiameterDimension });
+ }
+ foreach (var (chunk, index) in chunks.Select((c, i) => (c, i)))
+ {
+ var number = index + 1;
+ var zones = Zones(297, 210);
+ IReadOnlyList<DrawingTableIr> tables = chunk.Length == 0 ? [] : [new("HOLE COORDINATES (mm)", ["HOLE", "X", "Y", "TYPE"],
+ chunk.Select(h => (IReadOnlyList<string>)new[] { h.Identity, Number(h.X), Number(h.Y), h.Group }).ToArray(), name,
+ "Exact cylinder axes relative to finished stock planes; no sampled or chained dimensions.", DrawingTableKind.HoleCoordinates,
+ new(190, 30, 95, 7 * (chunk.Length + 1)), new(number, "B5"))];
+ if (tables.SelectMany(t => t.Rows).SelectMany(r => r).Any(value => DrawingInterFont.Load().MeasureMillimetres(value, 2.8) > 95d / 4 - 2))
+ return Failure("drawing-layout-impossible: A hole-schedule value exceeds its measured cell width. Use an authored wider schedule; values were not truncated.");
+ var fields = new Dictionary<string, string> { ["Units"] = "mm", ["Scale"] = "×" + Number(scale), ["Sheet"] = $"{number}/{chunks.Length}",
+ ["Status"] = missing.Count == 0 ? "DIMENSIONED - REVIEW" : "INCOMPLETE REQUIREMENTS" };
+ pages.Add(new(number, DrawingPageOrientation.Landscape, 297, 210, new(12, 18, 273, 135),
+ index == 0 ? [top, front] : [], index == 0 ? annotations : [], tables, notes, zones,
+ DrawingTitleBlockLayout.Create(metadata, fields, 297, 210, new(number, "D5")),
+ LocateNotes(notes, number, zones, DrawingTitleBlockLayout.NotesArea(297, 210))));
+ }
+ var layout = DrawingAnnotationLayout.Layout(pages, new Dictionary<string, PmiPresentation>());
+ if (layout.Diagnostics.Count > 0) return new(false, null, layout.Diagnostics);
+ var result = new DrawingIr(name + "Drawing", metadata, new(name, null, "CompletePlateDimensions",
+ new Dictionary<string, string> { ["Source"] = path, ["SHA256"] = StableHash(source), ["Requirements"] = $"linear={options.LinearToleranceMillimetres?.ToString("R", CultureInfo.InvariantCulture) ?? "unspecified"}; angular={options.AngularToleranceDegrees?.ToString("R", CultureInfo.InvariantCulture) ?? "unspecified"}; material={options.Material ?? "unspecified"}" },
+ StableHash(source)[..16], [], sourceKind), LocateAnnotations(layout.Pages), layout.Evidence, new(0, 0, 0, 0, 0), [],
+ "Exact analytic plate definition; shared trimmed-curve wireframe; coordinate dimensions from finished left/bottom edges.") { DefinitionEvidence = evidence };
+ return WriteArtifacts(result, Path.GetFullPath(outputDirectory), 1, 0);
+ }
+
+ private static DrawingViewIr PlaceDefinitionView(BrepBody body, string name, string identity, double[] direction, DrawingRect slot, double scale, DrawingRect allocation)
+ {
+ var view = DrawingProjectionEngine.Project([new(name, name, body)], identity, DrawingProjectionKind.Orthographic, DrawingHiddenLinePolicy.Wireframe,
+ direction, [], new(slot.X, slot.Y, Math.Max(slot.Width, 25), Math.Max(slot.Height, 25)), new(1, "B2"));
+ view = AtScale(view, scale);
+ var dx = slot.Center.X - view.GeometryBounds.Center.X; var dy = slot.Center.Y - view.GeometryBounds.Center.Y;
+ DrawingPoint2 Move(DrawingPoint2 p) => new(p.X + dx, p.Y + dy);
+ return view with { Viewport = allocation, GeometryBounds = view.GeometryBounds with { X = view.GeometryBounds.X + dx, Y = view.GeometryBounds.Y + dy },
+ Primitives = view.Primitives.Select(p => p with { Points = p.Points.Select(Move).ToArray() }).ToArray(),
+ Camera = view.Camera! with { OriginX = view.Camera.OriginX + dx, OriginY = view.Camera.OriginY + dy } };
+ }
+
+ private static DrawingAnnotationIr Measure(string identity, string view, string text, DrawingPoint2 a, DrawingPoint2 b, double offset, bool horizontal)
+ {
+ var start = horizontal ? new DrawingPoint2(a.X, offset) : new(offset, a.Y);
+ var end = horizontal ? new DrawingPoint2(b.X, offset) : new(offset, b.Y);
+ var width = DrawingInterFont.Load().MeasureMillimetres(text, 3.2) + 3;
+ var body = horizontal ? new DrawingRect((a.X + b.X - width) / 2, offset - 3, width, 6)
+ : new DrawingRect(offset + 2, (a.Y + b.Y) / 2 - 3, width, 6);
+ return DefinedLabel("dimension:" + identity, view, text, new(body.X, body.Y), [], a, "Exact distance between stock planes; no display-envelope measurement.") with
+ { Kind = DrawingAnnotationKind.LinearDimension, DimensionLines = [new(start, end, true, true), new(a, start), new(b, end)] };
+ }
+
+ private static DrawingAnnotationIr DefinedLabel(string identity, string view, string text, DrawingPoint2 at, IReadOnlyList<DrawingPoint2> leader,
+ DrawingPoint2 anchor, string provenance)
+ {
+ var width = DrawingInterFont.Load().MeasureMillimetres(text, 3.2) + 3;
+ var candidate = new DrawingAnnotationCandidateIr("definition:" + identity, new(at.X, at.Y, width, 6), leader, "definition", 0, 0, []);
+ return new(identity, identity, view, DrawingAnnotationKind.Note, text, anchor, candidate, [candidate], provenance);
+ }
+
+ private static string Number(double number) => number.ToString("R", CultureInfo.InvariantCulture);
+
+ private static double? MinimumHoleWeb(RectangularPlateDefinition plate, IReadOnlyList<DrawingDefinedHoleIr> holes, IReadOnlyList<HoleGroup> groups, DrawingGenerationOptions options)
+ {
+ if (holes.Count == 0 || options.LinearToleranceMillimetres is not { } t || options.AngularToleranceDegrees is not { } angle
+ || groups.Any(g => g.Plus is null)) return null;
+ // Independent Cartesian entry-center limits plus maximum cylinder-axis lean.
+ // The screen assumes orthogonal planar stock; it does not qualify stock form,
+ // surface finish, general angular stacks, inspection uncertainty or a process.
+ var lean = (plate.Thickness + t) * Math.Tan(angle * Math.PI / 180);
+ double Radius(DrawingDefinedHoleIr h) => (h.Diameter + groups.Single(g => g.Identity == h.Group).Plus!.Value) / (2 * Math.Cos(angle * Math.PI / 180));
+ var minimum = double.PositiveInfinity;
+ for (var i = 0; i < holes.Count; i++)
+ {
+ var h = holes[i]; var r = Radius(h);
+ minimum = Math.Min(minimum, new[] { h.X - t - lean - r, h.Y - t - lean - r,
+ plate.Width - t - h.X - t - lean - r, plate.Height - t - h.Y - t - lean - r }.Min());
+ foreach (var other in holes.Skip(i + 1))
+ {
+ var dx = Math.Max(0, Math.Abs(h.X - other.X) - 2 * t - 2 * lean);
+ var dy = Math.Max(0, Math.Abs(h.Y - other.Y) - 2 * t - 2 * lean);
+ minimum = Math.Min(minimum, Math.Sqrt(dx * dx + dy * dy) - r - Radius(other));
+ }
+ }
+ return minimum;
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/Drawing/DrawingGeneration.cs b/Aetheris.Kernel.Firmament/Drawing/DrawingGeneration.cs
index 73934e61..2f84f388 100644
--- a/Aetheris.Kernel.Firmament/Drawing/DrawingGeneration.cs
+++ b/Aetheris.Kernel.Firmament/Drawing/DrawingGeneration.cs
@@ -14,13 +14,22 @@ public static partial class FirmamentDrawingCompiler
/// <summary>Generate sheets from an admitted part or the supported AP242 semantic PMI subset.
/// No manufacturing tolerances, datum schemes or missing dimensions are inferred.</summary>
public static DrawingCompileResult Generate(string sourcePath, string outputDirectory, DrawingSignoffIr? signoff = null)
+ => Generate(sourcePath, outputDirectory, signoff, new());
+
+ public static DrawingCompileResult Generate(string sourcePath, string outputDirectory, DrawingSignoffIr? signoff, DrawingGenerationOptions options)
{
if (DrawingTitleBlockLayout.ValidateSignoff(signoff) is { } error) return Failure(error);
- try { return GenerateCore(sourcePath, outputDirectory, signoff); }
+ if (options.LinearToleranceMillimetres is { } tolerance && (!double.IsFinite(tolerance) || tolerance <= 0))
+ return Failure("drawing-linear-tolerance-invalid: Supply a finite positive tolerance in millimetres.");
+ if (options.AngularToleranceDegrees is { } angle && (!double.IsFinite(angle) || angle <= 0 || angle >= 45))
+ return Failure("drawing-angular-tolerance-invalid: Supply a finite positive angle below 45 degrees.");
+ if (options.ReferenceOnly && (options.LinearToleranceMillimetres.HasValue || options.AngularToleranceDegrees.HasValue || options.Material is not null))
+ return Failure("drawing-reference-options-unsupported: Reference-only visualization cannot consume manufacturing requirements. Omit --reference-only to plan dimensions.");
+ try { return GenerateCore(sourcePath, outputDirectory, signoff, options); }
catch (InvalidOperationException e) when (e.Message.StartsWith("drawing-", StringComparison.Ordinal)) { return Failure(e.Message); }
}
- private static DrawingCompileResult GenerateCore(string sourcePath, string outputDirectory, DrawingSignoffIr? signoff)
+ private static DrawingCompileResult GenerateCore(string sourcePath, string outputDirectory, DrawingSignoffIr? signoff, DrawingGenerationOptions options)
{
var path = Path.GetFullPath(sourcePath);
if (!File.Exists(path)) return Failure($"drawing-source-file-missing: {path}");
@@ -31,7 +40,11 @@ public static partial class FirmamentDrawingCompiler
IReadOnlyList<string> expectedPmi = [];
if (Path.GetExtension(path).Equals(".firmament", StringComparison.OrdinalIgnoreCase))
{
- if (IsDrawingSource(source)) return Compile(path, outputDirectory, signoff);
+ if (IsDrawingSource(source))
+ {
+ if (options != new DrawingGenerationOptions()) return Failure("drawing-authored-options-unsupported: Generation options apply to automatic part/STEP drawings; keep authored drawing requirements in its metadata.");
+ return Compile(path, outputDirectory, signoff);
+ }
var compiled = FirmamentBuildAndExport.CompileSource(source, Path.GetDirectoryName(path));
if (!compiled.IsSuccess) return new(false, null, compiled.Diagnostics.Select(d => $"{d.Source}: {d.Message}").ToArray());
var bound = compiled.Value.RuntimeAdmissionDocument?.BoundPmi;
@@ -65,7 +78,12 @@ public static partial class FirmamentDrawingCompiler
var body = imported.Value;
var faceMap = body.FaceOrientationReport?.Faces.Where(f => f.SourceEvidence.SourceEntityId.HasValue)
.ToDictionary(f => f.SourceEvidence.SourceEntityId!.Value, f => f.FaceId) ?? [];
- var samples = BrepWireframeSvgRenderer.SampleGeometry(body, new(CurveSamples: 64, Density: 5));
+ if (ValidateDrawingPmi(inspected.Items, faceMap) is { } pmiError) return Failure(pmiError);
+ if (!options.ReferenceOnly)
+ return GenerateDefinedPart(path, source, name, sourceKind, body, inspected.Items, faceMap, signoff, options, outputDirectory);
+ BrepWireframeGeometry samples;
+ try { samples = BrepWireframeSvgRenderer.SampleGeometry(body, new(CurveSamples: 64, Density: 5)); }
+ catch (InvalidOperationException e) { return Failure("drawing-projection-unsupported: " + e.Message); }
if (samples.Evidence.UnsupportedCurveFamilies.Count > 0)
return Failure($"drawing-edge-projection-unsupported: {string.Join(", ", samples.Evidence.UnsupportedCurveFamilies)}");
var definitions = new[]
@@ -82,12 +100,8 @@ public static partial class FirmamentDrawingCompiler
{
var item = inspectedItem with { Name = inspectedItem.AuthoredName ?? inspectedItem.Name };
var dimensionKind = item.DimensionKind?.ToLowerInvariant();
- if (item.Kind == "Dimension" && dimensionKind is not ("distance" or "lineardistancetodatum" or "diameter" or "holediameter"))
- return Failure($"drawing-pmi-family-unsupported: Dimension '{item.Name}' has unqualified kind '{item.DimensionKind ?? "unknown"}'. A millimetre label was not guessed.");
var reference = $"step:{item.EntityId}:{item.Name}";
var faces = item.GeometricFaceEntityIds.Where(faceMap.ContainsKey).Select(id => body.Topology.GetFace(faceMap[id])).ToArray();
- if (faces.Length == 0)
- return Failure($"drawing-pmi-target-unlocated: '{item.Name}' (STEP #{item.EntityId}, target '{item.Target}') has no imported geometric face association. Attach explicit PMI to a supported semantic face; a model-center leader would be misleading.");
var edges = faces.SelectMany(f => f.LoopIds).Select(body.Topology.GetLoop).SelectMany(l => l.CoedgeIds)
.Select(body.Topology.GetCoedge).Select(c => c.EdgeId.Value).ToHashSet();
var points = samples.Boundaries.Where(line => line.EdgeId is { } id && edges.Contains(id)).SelectMany(line => line.Points).ToArray();
@@ -100,12 +114,6 @@ public static partial class FirmamentDrawingCompiler
"Annotation" => DrawingAnnotationKind.Note,
_ => DrawingAnnotationKind.LinearDimension
};
- if (kind is DrawingAnnotationKind.DiameterDimension or DrawingAnnotationKind.LinearDimension or DrawingAnnotationKind.FeatureControlFrame
- && (item.Value is null || !double.IsFinite(item.Value.Value)
- || kind == DrawingAnnotationKind.DiameterDimension && item.Value <= 0))
- return Failure($"drawing-pmi-value-unavailable: '{item.Name}' (STEP #{item.EntityId}) has no admitted finite nominal value. The drawing did not substitute zero.");
- if (item.Depth is { } depth && (!double.IsFinite(depth) || depth <= 0))
- return Failure($"drawing-pmi-value-unavailable: '{item.Name}' has an invalid hole depth.");
var display = FormatStepPmi(item);
pmi.Add(reference, new(reference, kind, display, item.Value, item.Target, $"{path}; STEP #{item.EntityId}; faces {string.Join(",", item.GeometricFaceEntityIds)}; source SHA256 {StableHash(source)}"));
targets.Add(reference, points);
@@ -128,7 +136,7 @@ public static partial class FirmamentDrawingCompiler
Description: "Semantic PMI projection; manufacturing release requires engineering review") { Signoff = signoff };
var envelope = samples.Boundaries.SelectMany(line => line.Points).ToArray();
var notes = new[] { "DIMENSIONS: mm. PMI VALUES AND TOLERANCES RETAIN SOURCE AUTHORITY.",
- "ENGINEERING REVIEW REQUIRED; NO MISSING TOLERANCES ARE INFERRED.",
+ "INCOMPLETE GEOMETRY DEFINITION - NOT FOR MANUFACTURE.",
FormattableString.Invariant($"REFERENCE ENVELOPE (mm): X ~{envelope.Max(p => p.X) - envelope.Min(p => p.X):0.###} / Y ~{envelope.Max(p => p.Y) - envelope.Min(p => p.Y):0.###} / Z ~{envelope.Max(p => p.Z) - envelope.Min(p => p.Z):0.###}. SAMPLED; NO TOLERANCE."),
inspected.Items.Count == 0 ? "NO SUPPORTED SEMANTIC PMI FOUND. GEOMETRY VIEWS ONLY." : "LEADERS IDENTIFY ASSOCIATED FACES; LINEAR CALLOUTS DO NOT INFER MEASUREMENT ENDPOINTS." };
var requested = new List<(string Name, double[] Direction, DrawingProjectionKind Projection, string[] Pmi)>();
@@ -153,7 +161,7 @@ public static partial class FirmamentDrawingCompiler
var overviewScheme = Zones(width, height);
pages.Add(new(1, DrawingPageOrientation.Landscape, width, height, new(12, 20, 273, 145), overview, [], [], notes, overviewScheme,
DrawingTitleBlockLayout.Create(metadata, new Dictionary<string, string> { ["Product"] = name, ["Units"] = "mm", ["Scale"] = "SEE VIEWS",
- ["View"] = "OVERVIEW", ["Sheet"] = $"1/{requested.Count + 1}", ["Status"] = "ENGINEERING REVIEW" }, width, height, new(1, "D5")),
+ ["View"] = "OVERVIEW", ["Sheet"] = $"1/{requested.Count + 1}", ["Status"] = "REFERENCE ONLY" }, width, height, new(1, "D5")),
LocateNotes(notes, 1, overviewScheme, DrawingTitleBlockLayout.NotesArea(width, height))));
foreach (var request in requested)
{
@@ -175,7 +183,7 @@ public static partial class FirmamentDrawingCompiler
.OrderByDescending(p => p.X).ThenBy(p => p.Y).First(), StringComparer.Ordinal);
view = view with { Viewport = viewport, SemanticAnchors = anchors };
var fields = new Dictionary<string, string> { ["Product"] = name, ["Units"] = "mm", ["Scale"] = view.Scale.ToString("0.###", CultureInfo.InvariantCulture),
- ["View"] = request.Name, ["Sheet"] = $"{page}/{requested.Count + 1}", ["Status"] = "ENGINEERING REVIEW" };
+ ["View"] = request.Name, ["Sheet"] = $"{page}/{requested.Count + 1}", ["Status"] = "REFERENCE ONLY" };
var info = DrawingTitleBlockLayout.Create(metadata, fields, width, height, new(page, "D5"));
pages.Add(new(page, DrawingPageOrientation.Landscape, width, height, new(12, 20, 273, 145), [view], ReferenceEnvelope(view), [], notes,
scheme, info, LocateNotes(notes, page, scheme, DrawingTitleBlockLayout.NotesArea(width, height))));
@@ -207,7 +215,8 @@ public static partial class FirmamentDrawingCompiler
new(name, null, "AutomaticPmiSheets", new Dictionary<string, string> { ["Source"] = path, ["SHA256"] = StableHash(source) }, StableHash(source)[..16], [], sourceKind),
LocateAnnotations(dimensioned), layout.Evidence, new(0, 0, 0, 0, 0), [],
"Shared BRepWireframe sampler: trimmed exact edge curves and optional surface isolines. Wireframe intentionally displays rear edges; no HLR completeness claim.",
- new("Inter", "Embedded TrueType / Type0 Identity-H", "Embedded Inter advance widths", new Dictionary<string, double> { ["body"] = 2.8, ["label"] = 3.2, ["title"] = 4.0 }));
+ new("Inter", "Embedded TrueType / Type0 Identity-H", "Embedded Inter advance widths", new Dictionary<string, double> { ["body"] = 2.8, ["label"] = 3.2, ["title"] = 4.0 }))
+ { DefinitionEvidence = new(false, false, false, false, "ReferenceOnly", [], ["Complete nominal dimensions and manufacturing requirements were not planned."], new Dictionary<string, double>(), []) };
return WriteArtifacts(drawing, Path.GetFullPath(outputDirectory), 1, 0);
}
@@ -217,6 +226,25 @@ public static partial class FirmamentDrawingCompiler
return new[] { 1d, 2d, 5d }.Where(m => m * decade <= fit * (1 + 1e-12)).Max() * decade;
}
+ private static string? ValidateDrawingPmi(IReadOnlyList<Step242SemanticPmiInspectionItem> items,
+ IReadOnlyDictionary<int, Aetheris.Kernel.Core.Topology.FaceId> faceMap)
+ {
+ foreach (var item in items)
+ {
+ var name = item.AuthoredName ?? item.Name;
+ var kind = item.DimensionKind?.ToLowerInvariant();
+ if (item.Kind == "Dimension" && kind is not ("distance" or "lineardistancetodatum" or "diameter" or "holediameter"))
+ return $"drawing-pmi-family-unsupported: Dimension '{name}' has unqualified kind '{item.DimensionKind ?? "unknown"}'. A millimetre label was not guessed.";
+ if (!item.GeometricFaceEntityIds.Any(faceMap.ContainsKey))
+ return $"drawing-pmi-target-unlocated: '{name}' (STEP #{item.EntityId}, target '{item.Target}') has no imported geometric face association. A model-center leader would be misleading.";
+ if (item.Kind is "Dimension" or "Diameter" or "Position" && (item.Value is not { } value || !double.IsFinite(value)
+ || (item.Kind == "Diameter" || kind is "diameter" or "holediameter") && value <= 0))
+ return $"drawing-pmi-value-unavailable: '{name}' (STEP #{item.EntityId}) has no admitted finite nominal value. The drawing did not substitute zero.";
+ if (item.Depth is { } depth && (!double.IsFinite(depth) || depth <= 0)) return $"drawing-pmi-value-unavailable: '{name}' has an invalid hole depth.";
+ }
+ return null;
+ }
+
private static DrawingViewIr AtScale(DrawingViewIr view, double scale)
{
var ratio = scale / view.Scale; var center = view.GeometryBounds.Center;
diff --git a/Aetheris.Kernel.Firmament/Drawing/DrawingIr.cs b/Aetheris.Kernel.Firmament/Drawing/DrawingIr.cs
index f2ff6566..690bc576 100644
--- a/Aetheris.Kernel.Firmament/Drawing/DrawingIr.cs
+++ b/Aetheris.Kernel.Firmament/Drawing/DrawingIr.cs
@@ -5,9 +5,9 @@ namespace Aetheris.Kernel.Firmament.Drawing;
public enum DrawingPageOrientation { Portrait, Landscape }
public enum DrawingProjectionKind { Orthographic, Isometric }
public enum DrawingHiddenLinePolicy { VisibleOnly, VisibleAndHidden, Wireframe }
-public enum DrawingPrimitiveKind { Visible, Silhouette, Hidden, SurfaceGrid }
+public enum DrawingPrimitiveKind { Visible, Silhouette, Hidden, SurfaceGrid, CenterMark }
public enum DrawingAnnotationKind { LinearDimension, DiameterDimension, RadiusDimension, Datum, FeatureControlFrame, Note }
-public enum DrawingTableKind { Design, BillOfMaterials }
+public enum DrawingTableKind { Design, BillOfMaterials, HoleCoordinates }
public readonly record struct DrawingPoint2(double X, double Y);
public readonly record struct DrawingRect(double X, double Y, double Width, double Height)
@@ -209,6 +209,23 @@ public sealed record DrawingPerformanceIr(
double PdfMilliseconds,
double BomMilliseconds = 0);
+/// <summary>Explicit authoring inputs, not inferred process capability or approval.
+/// Linear tolerance applies to stock sizes and ordinate coordinates, never overrides PMI.</summary>
+public sealed record DrawingGenerationOptions(bool ReferenceOnly = false, double? LinearToleranceMillimetres = null, string? Material = null,
+ double? AngularToleranceDegrees = null);
+
+public sealed record DrawingDefinedHoleIr(string Identity, double X, double Y, double Diameter, string Extent,
+ string Group, IReadOnlyList<string> SourceReferences);
+public sealed record DrawingDefinitionEvidenceIr(bool NominalGeometryComplete, bool DimensionalTolerancesComplete,
+ bool MaterialSpecified, bool ProcessCapabilityVerified, string Family, IReadOnlyList<int> CoveredFaces,
+ IReadOnlyList<string> MissingRequirements, IReadOnlyDictionary<string, double> StockDimensions,
+ IReadOnlyList<DrawingDefinedHoleIr> Holes, double? LinearToleranceMillimetres = null)
+{
+ public double? AngularToleranceDegrees { get; init; }
+ public double? MinimumHoleWebAtDeclaredLimitsMillimetres { get; init; }
+ public string ToleranceScreenScope { get; init; } = "Stock size and Cartesian entry-center intervals with cylinder-axis lean on ideal orthogonal planar stock; stock form, general angular stacks and process capability are unqualified.";
+}
+
public sealed record DrawingIr(
string Identity,
DrawingMetadataIr Metadata,
@@ -220,7 +237,10 @@ public sealed record DrawingIr(
string ProjectionPolicy,
DrawingTypographyIr? Typography = null,
ReviewIr? Reviews = null,
- string SchemaVersion = "aetheris-drawing-m0b");
+ string SchemaVersion = "aetheris-drawing-m0b")
+{
+ public DrawingDefinitionEvidenceIr? DefinitionEvidence { get; init; }
+}
public sealed record DrawingCompileArtifacts(
DrawingIr Drawing,
diff --git a/Aetheris.Kernel.Firmament/Drawing/DrawingPptxWriter.cs b/Aetheris.Kernel.Firmament/Drawing/DrawingPptxWriter.cs
index f09b1485..2fe30398 100644
--- a/Aetheris.Kernel.Firmament/Drawing/DrawingPptxWriter.cs
+++ b/Aetheris.Kernel.Firmament/Drawing/DrawingPptxWriter.cs
@@ -83,8 +83,8 @@ public static partial class DrawingPptxWriter
foreach (var primitive in view.Primitives)
for (var index = 1; index < primitive.Points.Count; index++)
group.Line($"View.{view.Identity}.Edge.{Safe(primitive.StableId)}.{index}", primitive.Points[index - 1].X, primitive.Points[index - 1].Y, primitive.Points[index].X, primitive.Points[index].Y,
- primitive.Kind == DrawingPrimitiveKind.SurfaceGrid ? "94A3B8" : "111111", primitive.Kind == DrawingPrimitiveKind.SurfaceGrid ? .12 : .35,
- dashed: primitive.Kind == DrawingPrimitiveKind.Hidden);
+ primitive.Kind == DrawingPrimitiveKind.SurfaceGrid ? "94A3B8" : "111111", primitive.Kind is DrawingPrimitiveKind.SurfaceGrid or DrawingPrimitiveKind.CenterMark ? .12 : .35,
+ dashed: primitive.Kind is DrawingPrimitiveKind.Hidden or DrawingPrimitiveKind.CenterMark);
});
foreach (var annotation in page.Annotations)
slide.Group($"PMI.{Safe(annotation.Identity)}", group =>
@@ -96,7 +96,7 @@ public static partial class DrawingPptxWriter
var body = annotation.SelectedCandidate.Body;
group.Text($"PMI.{Safe(annotation.Identity)}.Text", annotation.EngineeringDisplay, body.X, body.Y, body.Width, body.Height, 3.2, centered: true, border: annotation.Kind is DrawingAnnotationKind.Datum or DrawingAnnotationKind.FeatureControlFrame);
});
- foreach (var table in page.Tables) slide.Table($"Table.{(table.Kind == DrawingTableKind.BillOfMaterials ? "BOM" : "Design")}.{Safe(table.Identity)}", table);
+ foreach (var table in page.Tables) slide.Table($"Table.{(table.Kind == DrawingTableKind.BillOfMaterials ? "BOM" : table.Kind.ToString())}.{Safe(table.Identity)}", table);
if (page.InformationBlock is not null)
slide.Group("Metadata.DrawingInfo", group =>
{
diff --git a/Aetheris.Kernel.Firmament/Drawing/DrawingSvgRenderer.cs b/Aetheris.Kernel.Firmament/Drawing/DrawingSvgRenderer.cs
index de251f1e..4e336871 100644
--- a/Aetheris.Kernel.Firmament/Drawing/DrawingSvgRenderer.cs
+++ b/Aetheris.Kernel.Firmament/Drawing/DrawingSvgRenderer.cs
@@ -12,7 +12,7 @@ public static class DrawingSvgRenderer
var height = drawing.Pages.Sum(page => page.HeightMillimetres + 8) - 8;
var builder = new StringBuilder();
builder.AppendLine($"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{F(width)}mm\" height=\"{F(height)}mm\" viewBox=\"0 0 {F(width)} {F(height)}\" data-drawing-schema=\"{drawing.SchemaVersion}\">");
- builder.AppendLine("<style>.sheet{fill:white;stroke:#aab2bd;stroke-width:.25}.border,.zone-tick{fill:none;stroke:#334155;stroke-width:.25}.visible,.silhouette{fill:none;stroke:#111827;stroke-width:.35;stroke-linecap:round;stroke-linejoin:round}.silhouette{stroke-width:.5}.surfacegrid{fill:none;stroke:#94a3b8;stroke-width:.14}.hidden{fill:none;stroke:#64748b;stroke-width:.25;stroke-dasharray:2 1}.leader{fill:none;stroke:#374151;stroke-width:.22}.annotation{font:3.2px Inter,Arial,sans-serif;fill:#111827}.label{font:600 3.2px Inter,Arial,sans-serif;fill:#334155}.meta,.zone-label{font:2.8px Inter,Arial,sans-serif;fill:#334155}.zone-label{font-size:2.4px}.table-header{font:600 3px Inter,Arial,sans-serif}.table-cell{font:2.8px Inter,Arial,sans-serif}.info-key{font:2px Inter,Arial,sans-serif;fill:#64748b}.info-value{font:2.6px Inter,Arial,sans-serif;fill:#111827}</style>");
+ builder.AppendLine("<style>.sheet{fill:white;stroke:#aab2bd;stroke-width:.25}.border,.zone-tick{fill:none;stroke:#334155;stroke-width:.25}.visible,.silhouette{fill:none;stroke:#111827;stroke-width:.35;stroke-linecap:round;stroke-linejoin:round}.silhouette{stroke-width:.5}.surfacegrid{fill:none;stroke:#94a3b8;stroke-width:.14}.centermark{fill:none;stroke:#334155;stroke-width:.12;stroke-dasharray:2 1}.hidden{fill:none;stroke:#64748b;stroke-width:.25;stroke-dasharray:2 1}.leader{fill:none;stroke:#374151;stroke-width:.22}.annotation{font:3.2px Inter,Arial,sans-serif;fill:#111827}.label{font:600 3.2px Inter,Arial,sans-serif;fill:#334155}.meta,.zone-label{font:2.8px Inter,Arial,sans-serif;fill:#334155}.zone-label{font-size:2.4px}.table-header{font:600 3px Inter,Arial,sans-serif}.table-cell{font:2.8px Inter,Arial,sans-serif}.info-key{font:2px Inter,Arial,sans-serif;fill:#64748b}.info-value{font:2.6px Inter,Arial,sans-serif;fill:#111827}</style>");
var offset = 0d;
foreach (var page in drawing.Pages)
{
diff --git a/Aetheris.Kernel.Firmament/Drawing/DrawingVectorPdfWriter.cs b/Aetheris.Kernel.Firmament/Drawing/DrawingVectorPdfWriter.cs
index 9b481c3b..a4a83c7c 100644
--- a/Aetheris.Kernel.Firmament/Drawing/DrawingVectorPdfWriter.cs
+++ b/Aetheris.Kernel.Firmament/Drawing/DrawingVectorPdfWriter.cs
@@ -56,7 +56,7 @@ public static class DrawingVectorPdfWriter
foreach (var primitive in view.Primitives)
{
b.Append(primitive.Kind == DrawingPrimitiveKind.SurfaceGrid ? "0.58 0.64 0.70 RG\n" : "0.07 0.09 0.12 RG\n");
- for (var index = 1; index < primitive.Points.Count; index++) Line(primitive.Points[index - 1], primitive.Points[index], primitive.Kind == DrawingPrimitiveKind.SurfaceGrid ? .12 : primitive.Kind == DrawingPrimitiveKind.Silhouette ? .5 : .35, primitive.Kind == DrawingPrimitiveKind.Hidden);
+ for (var index = 1; index < primitive.Points.Count; index++) Line(primitive.Points[index - 1], primitive.Points[index], primitive.Kind is DrawingPrimitiveKind.SurfaceGrid or DrawingPrimitiveKind.CenterMark ? .12 : primitive.Kind == DrawingPrimitiveKind.Silhouette ? .5 : .35, primitive.Kind is DrawingPrimitiveKind.Hidden or DrawingPrimitiveKind.CenterMark);
}
b.Append("0 0 0 RG\n");
}
diff --git a/Aetheris.Kernel.Firmament/Drawing/FirmamentDrawingCompiler.cs b/Aetheris.Kernel.Firmament/Drawing/FirmamentDrawingCompiler.cs
index 7c127192..34420e2f 100644
--- a/Aetheris.Kernel.Firmament/Drawing/FirmamentDrawingCompiler.cs
+++ b/Aetheris.Kernel.Firmament/Drawing/FirmamentDrawingCompiler.cs
@@ -175,6 +175,7 @@ public static partial class FirmamentDrawingCompiler
pageCount = drawing.Pages.Count, a4Only = drawing.Pages.All(page => (page.WidthMillimetres, page.HeightMillimetres) is (210, 297) or (297, 210)),
vectorPdf = true, rasterImages = 0, embeddedFont = "Inter", searchableText = true,
titleBlockTables = drawing.Pages.Count(page => page.InformationBlock?.Table is not null), signoff = drawing.Metadata.Signoff,
+ definition = drawing.DefinitionEvidence,
pptx = DrawingPptxWriter.Inspect(pptxPath), reviewPptx = reviewPptxPath is null ? null : DrawingPptxWriter.Inspect(reviewPptxPath),
occurrenceCount, bomRows,
visibleSegments = drawing.Pages.SelectMany(page => page.Views).Sum(view => view.VisibilityEvidence?.VisibleSegments ?? 0),
diff --git a/aetheris.client/src/drawing/drawingDocument.css b/aetheris.client/src/drawing/drawingDocument.css
index db24ae3e..b42889d1 100644
--- a/aetheris.client/src/drawing/drawingDocument.css
+++ b/aetheris.client/src/drawing/drawingDocument.css
@@ -5,6 +5,7 @@
background: #dbe2ea;
padding: 12mm;
}
+.drawing-content .centermark { fill: none; stroke: #334155; stroke-width: .12; stroke-dasharray: 2 1; }
.drawing-page {
font-family: Inter, ui-sans-serif, system-ui, sans-serif;
position: relative;
diff --git a/aetheris.client/src/drawing/drawingIr.ts b/aetheris.client/src/drawing/drawingIr.ts
index e1495f17..886694f2 100644
--- a/aetheris.client/src/drawing/drawingIr.ts
+++ b/aetheris.client/src/drawing/drawingIr.ts
@@ -18,6 +18,21 @@ export type DrawingIr = {
templateIdentity: string;
};
pages: DrawingPageIr[];
+ definitionEvidence?: {
+ nominalGeometryComplete: boolean;
+ dimensionalTolerancesComplete: boolean;
+ materialSpecified: boolean;
+ processCapabilityVerified: boolean;
+ family: string;
+ coveredFaces: number[];
+ missingRequirements: string[];
+ stockDimensions: Record<string, number>;
+ holes: { identity: string; x: number; y: number; diameter: number; extent: string; group: string; sourceReferences: string[] }[];
+ linearToleranceMillimetres?: number | null;
+ angularToleranceDegrees?: number | null;
+ minimumHoleWebAtDeclaredLimitsMillimetres?: number | null;
+ toleranceScreenScope: string;
+ } | null;
};
export type DrawingPageIr = {
@@ -64,7 +79,7 @@ export type DrawingViewIr = {
viewport: DrawingRect;
primitives: {
stableId: string;
- kind: "Visible" | "Silhouette" | "Hidden" | "SurfaceGrid";
+ kind: "Visible" | "Silhouette" | "Hidden" | "SurfaceGrid" | "CenterMark";
points: DrawingPoint2[];
occurrenceIdentity?: string;
definitionIdentity?: string;
@@ -86,7 +101,7 @@ export type DrawingTableIr = {
columns: string[];
rows: string[][];
sourceIdentity: string;
- kind?: "Design" | "BillOfMaterials";
+ kind?: "Design" | "BillOfMaterials" | "HoleCoordinates";
bounds?: DrawingRect;
location?: DrawingLocationIr;
};
diff --git a/docs/development/DRAWING-DEFINITION-QUALIFICATION.md b/docs/development/DRAWING-DEFINITION-QUALIFICATION.md
new file mode 100644
index 00000000..1c75351d
--- /dev/null
+++ b/docs/development/DRAWING-DEFINITION-QUALIFICATION.md
@@ -0,0 +1,180 @@
+# Drawing definition and PDF reconstruction qualification
+
+## Engineering review and replacement acceptance gate
+
+The earlier drawing integration preserved diameter PMI and produced readable
+vectors, but its example did not define hole locations or a controlling thickness.
+Approximate REF envelopes did not specify stock acceptance. Zero annotation
+collisions and successful export were insufficient acceptance tests. The original
+integration report is retained with a superseding review note.
+
+The replacement gate asks whether a reader can reconstruct the nominal part from
+the PDF alone, then distinguishes specified limits from actual process capability
+and engineering approval. A 3D nominal model is not evidence of manufacturing
+capability. No source geometry was changed for this correction.
+
+## Ownership and implementation
+
+`BrepRectangularPlateQuery` is a read-only kernel query. It admits six stock planes
+with exact rectangular boundaries and separated, inward-oriented circular
+Z-through-hole walls. Every face, outer loop, opening, seam and edge count is
+accounted for. Bound straight curves agree with their vertices; full circle trims
+and axis directions are checked. Imported shell orientation must be qualified.
+No sampled display bounds, source-name heuristic, history reconstruction or new
+geometry operation establishes completeness.
+
+The drawing dimension planner consumes those facts and associated PMI. It emits
+controlling stock/thickness dimensions, an entry-face coordinate schedule from
+finished edges, hole IDs/center marks and grouped size/limit/THRU callouts. Source
+PMI identities survive grouping. An associated plane datum is shown in a useful
+view, rather than attached ambiguously to a plan-view corner. The side view uses
+qualified internal cylinder silhouettes as dashed lines, excluding parameter
+seams from the exterior outline.
+
+Both generation modes share numeric, kind and face-association PMI admission.
+The default path does not execute the old overlay planner first. Reference-only
+views remain an explicit visualization mode marked incomplete/not for manufacture.
+Unhandled geometry or additional PMI families reject the default complete-plan
+path; there is no implicit success fallback. Source Drawing declarations still
+delegate to their authored owner and have no automatic completeness assessment.
+
+PDF/SVG/PPTX/React project shared IR. The title/signoff table is retained, and hole
+schedules are native editable tables. Notes, tables, dimensions, labels and leaders
+participate in layout keepouts/audits. Long table values and impossible allocations
+reject instead of truncating data. Round-trip numeric text avoids rounding small
+tolerances to zero.
+
+## Requirements and bounded tolerance screen
+
+The demonstration supplies explicit drawing inputs: 6061-T6 aluminium, bilateral
+stock/coordinate tolerance 0.1 mm and general angular tolerance 0.5 degrees.
+These are example authoring choices, not inferred source facts. The original
+diameter requirement remains 4 +0.05/-0.02 mm (3.98-4.05 mm); it is not advertised
+as a clearance fit for a 4 mm shaft. AP242 body geometry and original PMI are not
+rewritten with the additional drawing inputs.
+
+The compiler records nominal completeness, specified dimensional tolerances,
+material, missing requirements and process capability separately. Missing linear,
+angular, material or hole-size requirements stay visible. Checked/Approved names
+and dates remain blank. The source-record and CLI signoff paths remain compatible.
+
+The arithmetic screen checks positive stock/diameter intervals and hole web limits
+for independent Cartesian entry-center limits and cylinder-axis lean on ideal
+orthogonal planar stock. Projected bore radius accounts for lean. Its assumptions
+are explicit in IR. It does not qualify stock form, general angular stacks,
+surface finish, a functional fit, measurement uncertainty or machining capability.
+Diameter/depth/quantity contradictions and zero-width diameter limits reject.
+
+For the example's 4 mm bore through 8 mm stock, a finishing/inspection operation
+would need to be selected and qualified. The 0.07 mm size band is not a guarantee
+for ordinary drilling. The [Protolabs material/process capability table](https://www.protolabs.com/services/cnc-machining/precision-machining-tolerances/)
+distinguishes ordinary holes from specified bore tolerances. That is feasibility
+context, not evidence that this part has been made or inspected. Functional fit
+and release remain engineering decisions; `processCapabilityVerified` is false.
+
+## Independent PDF reconstruction witness
+
+`fixtures/Regression/DrawingGeneration/reconstruct_from_pdf.py` receives only a
+PDF, output directory and optional CLI executable. It reads visible dimension
+text and coordinate/type tables, then writes and compiles a fresh Firmament part.
+It does not access the original source, Drawing IR or embedded attachments. The
+reader convention is bounded to the documented dimensioned plate layout; it is
+not general-purpose drawing OCR.
+
+`qualify_pdf_roundtrip.py` freezes that independent reconstruction before reading
+the reference STEP. It then uses the real CLI to compare topology, normalized
+bounds, surface families and volume. A verification-only adapter independently
+reads canonical STEP cylinder placements/radii, checking every hole's center and
+size, so misplaced holes cannot pass merely by preserving volume and counts.
+Global rigid placement is irrelevant to the local part definition.
+
+Qualification runs the original ten-hole plate and a non-grid variant with one
+center changed to (-34.125, -17.25) mm. Four incomplete PDF text variants must be
+rejected: absent stock size, absent coordinate row, missing extent, and missing
+coordinate tolerance. No fixture expectations or original part dimensions are
+hard-coded into the independent reader.
+
+```powershell
+python fixtures/Regression/DrawingGeneration/qualify_pdf_roundtrip.py --pdf artifacts/local/drawing-definition/final/InspectionPlateDrawing.pdf --reference-step artifacts/local/drawing-definition/final/InspectionPlate.step --out-dir artifacts/local/drawing-definition/roundtrip --cli Aetheris.CLI/bin/Release/net10.0/aetheris.exe
+```
+
+## Qualification results
+
+Raw evidence belongs in ignored `artifacts/local/drawing-definition/`; the
+independent readers are durable fixture support. Public usage and boundaries are
+maintained in `docs/public/drawings.md`.
+
+| Gate | Result |
+| --- | --- |
+| Full solution Release build | `build-full.log`: zero errors, 30 pre-existing warning occurrences |
+| Focused Firmament drawings | `focused-final.log`: 49 passed, including Open XML validation |
+| Focused CLI drawings | `cli-final.log`: 7 passed |
+| Core fast lane | `fast-final.log`: 1,087 passed |
+| Complete solution regression | `full-final.log`: 5,660 passed, zero failures/skips; FrictionLab reports no discovered tests |
+| Client TypeScript / complete Vitest | Typecheck passed; 19 files / 91 tests passed |
+| Existing FrontendX4 corpus | `corpus-final.log`: 32/32 passed; no baseline recording |
+| Independent reconstruction | Original and non-grid PDF-only reconstructions compile and match all cylinder axes/radii, topology, bounds and reported volume |
+| Missing-data mutation checks | All four rejected for each of the two PDFs |
+| Geometry preservation | Original 414 STEP geometric entities byte-identical to pre-refactor baseline; SHA256 `c7ec5a43100cdf5368016315bbd02bbca59c82855f68cb50737f8845a73efe9c` |
+| Part / STEP presentation parity | PDF, SVG and PPTX bytes identical |
+| Final visual inspection | Original and non-grid variants each fit one A4 landscape page; both PDFs rendered and inspected |
+| Layout evidence | Zero text/model, text/text or text/stroke collisions and zero failed annotations for both examples |
+
+`git diff --check` passes. The solution lanes ran serially with
+`MSBUILDDISABLENODEREUSE=1`, `DOTNET_PROCESSOR_COUNT=2`, `-m:1`,
+`-nr:false`, `UseSharedCompilation=false` and the prescribed full solution test
+command. At closeout no dotnet, testhost, MSBuild, VBCSCompiler or aetheris runtime
+hosts remain. Skill frontmatter/UI metadata validation also passes.
+
+The CLI mass-property volume is explicitly `NumericalWithBound` with a triangulated
+boundary integral, not an authoritative exact volume assertion. Its agreement is
+a parity check. Independent analytic volumes from the printed stock/hole recipe
+and reference primitive parameters are also compared; the plate's analytic nominal
+volume is approximately 54,994.6903508513 mm3. This drawing pass does not change the
+verification engine's numerical integration policy.
+
+Final example files are under `final/InspectionPlateDrawing.*`. The frozen
+reconstructions, PDF-only extracted definitions and comparison evidence are under
+`roundtrip/` and `asymmetric-roundtrip/`. No original geometry expectations or source
+part fixtures were rewritten. PowerPoint desktop rendering/editing was not tested;
+native package validity, PDF rendering and shared presentation data were checked.
+
+The focused gate includes successful geometry/coordinate coverage and native PPTX
+validation, perturbed non-grid centers, unsupported sphere/blind geometry, missing
+requirements, invalid tolerances, edge breakout, contradictory diameter/depth/
+quantity, reference-only admission and preservation of previous drawing behavior.
+
+## Remaining limits and code-quality review
+
+The complete-plan family is rectangular stock with disjoint Z-through holes.
+Other outlines, blends, blind/counterbored/countersunk holes, oblique holes,
+sections and automatic Assembly planning require their own qualified production
+owners. The current layout supports four distinct hole size/limit groups and
+paginates coordinate schedules after twelve rows; dense labels can reject.
+These are named stops, not evidence that an incomplete drawing defines a part.
+
+This pass introduces no DSL parser, rewrite, diagnostic allowlist, geometry solver
+or UI-side dimension inference. Kernel queries own geometric facts; the drawing
+planner owns coverage/presentation; backends consume shared data. Authored drawing
+and old reference-view tests remain, with changed automatic expectations reflecting
+the new one-sheet complete definition rather than duplicate diameter sheets.
+
+A reusable `mechanical-drawing-review` skill was created and validated in the
+user's Codex skill directory. It requires reconstruction from the exported artifact,
+function-driven limits, process/inspection distinction and truthful signoff. It
+supports review rather than becoming a parallel compiler validator. Layout choices
+follow [MIT's completeness/nonredundancy guidance](https://ocw.mit.edu/courses/2-007-design-and-manufacturing-i-spring-2009/pages/related-resources/drawing_and_sketching/).
+
+## Verdict
+
+**Success for the qualified plate/through-hole family.** The corrected one-page
+PDF contains enough visible information to reconstruct the nominal part, with
+explicit dimensional requirements and material rather than inferred defaults.
+An independent PDF-only reader reconstructs both the original and irregular
+variants, and geometry comparisons pass. The source body's exact geometry is
+unchanged; unsupported automatic families stop explicitly.
+
+This is not a general manufacturing-release or process-capability certification.
+Qualified shop execution, stock form/finish, functional fit, inspection uncertainty
+and engineering signoff remain distinct from the successful drawing-definition
+gate. The implementation and public documentation preserve that distinction.
diff --git a/docs/development/DRAWING-GENERATION-2026-10-18.md b/docs/development/DRAWING-GENERATION-2026-10-18.md
index 5c04caa2..3dd48888 100644
--- a/docs/development/DRAWING-GENERATION-2026-10-18.md
+++ b/docs/development/DRAWING-GENERATION-2026-10-18.md
@@ -2,6 +2,13 @@
Date: 2026-10-18.
+> Subsequent engineering review rejected the specimen as a manufacturing drawing:
+> it omitted hole coordinates and controlling stock/thickness requirements. The
+> success below qualifies integration and presentation only. See
+> [dimension completeness qualification](DRAWING-DEFINITION-QUALIFICATION.md) for
+> the replacement gate and corrected drawing. The original findings are retained.
+
+
## Existing owners and observed gaps
The repository already contained a Drawing IR, authored Part/Assembly drawing
diff --git a/docs/public/drawings.md b/docs/public/drawings.md
index 85e26d56..7f3e8a93 100644
--- a/docs/public/drawings.md
+++ b/docs/public/drawings.md
@@ -1,112 +1,137 @@
-# Generate engineering drawings
+# Generate dimensioned engineering drawings
-Use the existing drawing compiler to produce searchable vector PDF, SVG and
-editable PPTX from a Firmament part or supported AP242 semantic PMI:
+A drawing must define the nominal part without requiring its CAD file or measuring
+its picture. The compiler distinguishes nominal geometry coverage, specified
+limits, material and actual process qualification. Searchable PDF text and a clean
+layout are presentation checks, not manufacturing approval.
+
+## Generate a dimensioned plate
```powershell
-aetheris drawing generate fixtures/Regression/DrawingGeneration/inspection-plate.firmament --out-dir artifacts/local/drawing/inspection-plate --drawn-by "Codex (AI)" --date 2026-10-18 --json
-aetheris drawing generate inspection-plate.step --out-dir artifacts/local/drawing/from-step --json
+aetheris drawing generate fixtures/Regression/DrawingGeneration/inspection-plate.firmament --out-dir artifacts/local/drawing/inspection-plate --linear-tolerance 0.1 --angular-tolerance 0.5 --material "6061-T6 aluminium" --drawn-by "Codex (AI)" --date 2026-10-18 --json
```
-The default output directory is `artifacts/local/drawing/<source-name>`.
-Generation preserves the source and writes a Drawing IR and validation evidence
-beside the three presentation formats. PDF is a vector document with an embedded
-Inter font and searchable dimension text. SVG and editable PPTX consume the same
-positions and annotation strokes. Inter must be available in a PPTX editor to retain
-matching text metrics. Changes in a presentation never change geometry
-or PMI.
-
-## What automatic generation does
-
-An overview sheet combines top, front and right orthographic views with an isometric
-wireframe. Its orthographic views share a scale. Enlarged PMI sheets follow only
-for views with annotations; dense callouts paginate.
-Surface lines come from the same BRep wireframe sampler as `aetheris wireframe`;
-orthographic views retain topology edges without the denser surface grid. Rear
-edges are intentionally visible. These are wireframe views, not a claim of complete
-hidden-line removal or standards certification.
-
-The generator reads the existing Aetheris AP242 semantic PMI subset: named
-diameters with bilateral tolerances, datum features and supported face-associated
-annotations/position controls. Datum and hole callouts retain source identities
-and STEP entity/face references. Diameter callouts choose the orthographic view
-closest to the cylindrical axis. A face-on circular diameter receives a two-arrow
-diameter witness when its surface radius agrees with the semantic nominal.
-
-The X/Y/Z envelope measurements prefixed `~` and marked `REF` describe sampled
-projected curves. They are approximate reference measurements, with no implied
-manufacturing tolerance. They do not replace explicit PMI. A linear PMI callout
-can identify an associated face but does not invent measurement endpoints.
-
-Labels use embedded-font widths. Layout reserves view titles, notes, information
-blocks, geometry, other labels and leader clearances. Placement uses the existing
-JudgmentEngine with deterministic costs and rejection reasons. Dense PMI is split
-into batches of at most six per view sheet. Layout failure is an error, not
-permission to shrink, clip or silently omit a dimension.
-
-## Authored drawings
-
-Keep using `aetheris drawing compile <drawing.firmament> --out-dir <directory>` for
-explicit Drawing/Templates, selected views, engineering metadata, design tables,
-assembly BOMs and reviews. `generate` honors a source's existing Drawing declaration
-by using that compilation path. Assembly drawing authoring remains explicit.
-
-Within an authored View, `HiddenLines: Wireframe` selects the shared wireframe
-projection; `VisibleOnly` and `VisibleAndHidden` retain their existing bounded
-occlusion behavior. This adds a presentation policy, not a new geometry frontend.
-
-## Engineering authority and current boundaries
-
-Generated sheets communicate available source facts and require engineering
-review before manufacturing release. They do not infer material, missing dimensions,
-datum schemes, fits, general tolerances or revision metadata. A geometry-only input
-is explicitly labeled as having no supported semantic PMI.
-
-Automatic generation currently admits one imported BRep body and millimetre PMI.
-Foreign PMI units, unsupported standard AP242 dimension/tolerance families and
-missing face associations produce named errors. Geometry-only imports can use the
-existing unit normalization. The generator does not claim universal third-party
-AP242 PMI interpretation. A datum axis-face port must resolve uniquely; multiple
-same-facing planes remain ambiguous.
-
-General section/detail views, automatic assembly annotation, standards certification
-and DXF drawing export are not qualified by this pass. PDF, SVG and PPTX are the
-implemented outputs.
-
-Use multiline fields inside PMI declarations. The current PMI frontend still
-rejects some otherwise equivalent semicolon-separated inline fields; generation
-does not introduce a second parser to work around that inconsistency.
-
-For labeling conventions, see MIT's
-[Engineering Drawing and Sketching](https://ocw.mit.edu/courses/2-007-design-and-manufacturing-i-spring-2009/pages/related-resources/drawing_and_sketching/):
-choose informative views, avoid redundant controlling dimensions, and place readable
-dimension text and leaders near the relevant feature. These references guide layout;
-they are not a claim of ISO/ASME compliance.
+`generate` also accepts `.step` / `.stp`. The default output directory is
+`artifacts/local/drawing/<source-name>`. PDF, SVG, editable PPTX, Drawing IR and a
+validation report share the same dimension plan. The compiler preserves source and
+body geometry. Generation options are explicit drawing authoring inputs; they do
+not rewrite the part or add these requirements to its AP242 PMI.
+
+The current complete-definition family is an axis-aligned rectangular plate/box
+with disjoint circular Z-through holes. Recognition accounts for every face,
+rectangular stock boundary, full circular opening and cylinder seam. Fillets,
+chamfers, blind holes, counterbores, nonrectangular outlines, oblique holes and other
+families require an authored complete drawing until their dimension planners are
+qualified. They fail automatic generation with `drawing-definition-incomplete`;
+a sampled bounding box is never used to claim complete dimensions.
+
+A qualified plate receives:
+
+- Exact controlling width and height dimensions, and thickness on an aligned edge
+ view. These values come from stock planes, not sampled display bounds.
+- Hole center marks and IDs, a coordinate schedule from the left and bottom
+ finished edges, entry-face/orientation information, and explicit THRU extents.
+- Grouped diameter/limit callouts only when size, limits and extent agree.
+ Original PMI names, targets and face identities remain in provenance.
+- A datum indication on the actual associated plane in a useful view. Coordinate
+ edge references do not silently create extra GD&T datums.
+- Light internal hole-wall lines in the side view, rather than treating a
+ cylinder's parameter seam as an exterior edge.
+
+Coordinates are independent baseline dimensions. No row/column pattern is guessed
+from an apparently regular picture. Irregular coordinates remain individual values.
+Hole schedules paginate beyond twelve rows; more than four distinct size/limit
+groups currently requires authored sheet allocation. Crowded labels or oversized
+values reject instead of clipping, shrinking or omitting engineering information.
+
+## Tolerances and manufacturing authority
+
+`--linear-tolerance <mm>` explicitly specifies bilateral stock-size and X/Y
+coordinate limits. `--angular-tolerance <degrees>` specifies the general angular
+allowance. `--material <name>` supplies the material for the drawing. These are
+not defaults and never override existing diameter PMI.
+
+Without these inputs, nominal dimensions are still complete for a recognized part,
+but the sheet prominently identifies missing requirements and is not for
+manufacture. Missing hole diameter tolerances remain missing as well. JSON reports
+`nominalGeometryComplete`, `dimensionalTolerancesComplete`, `materialSpecified`,
+`processCapabilityVerified` and `missingRequirements` independently. Authored
+Drawing compilation has no automatic coverage assessment; its evidence remains
+unassessed rather than implicitly complete.
+
+The planner checks positive stock/diameter intervals and screens remaining hole
+webs against Cartesian entry-center limits and cylinder-axis lean on ideal
+orthogonal stock. The evidence records that assumption. This bounded interference
+screen does not qualify stock form, general angular stacks, surface finish,
+inspection uncertainty, a manufacturing process or functional fit. It is not
+permission to declare a part manufacture-ready.
+
+For the example, the retained source diameter limits are 3.98-4.05 mm. Those are
+source requirements, not a claim that ordinary drilling will meet them, nor an M4
+clearance-fit designation. A suitable finishing/inspection process must be agreed.
+See the material/process-dependent [Protolabs machining capability table](https://www.protolabs.com/services/cnc-machining/precision-machining-tolerances/).
+
+Conflicting diameter, depth or quantity PMI rejects. Unknown dimension kinds,
+unlocated PMI and unqualified AP242 families also reject; semantic requirements
+cannot disappear because nominal geometry looks plausible. Automatic PMI readback
+currently admits the existing Aetheris millimetre subset, not universal third-party
+AP242 PMI. Use multiline fields inside source PMI declarations; some semicolon
+forms remain frontend debt.
+
+## Explicit reference visualization
-## Title table and traceability
+```powershell
+aetheris drawing generate model.step --reference-only --out-dir artifacts/local/drawing/reference --json
+```
+
+This retains the earlier PMI/wireframe review sheets with approximate `REF`
+envelopes. Sheets are marked **REFERENCE ONLY / NOT FOR MANUFACTURE**, and nominal
+completeness is false. Manufacturing generation options are rejected in this mode.
+Unsupported wireframe geometry also reports a named error. A reference view is not
+a substitute for complete dimensions.
+
+## Authored drawings and formats
-Every sheet has a shared title table with merged title/identity cells, material,
-part number, revision, scale, units, sheet number and status. Its final rows contain
-separate **Drawn by / Checked by / Approved by** and corresponding date boxes.
-PPTX exports a native editable table; the browser uses an HTML table. PDF and SVG
-project the same measured cells and line hierarchy.
+`aetheris drawing compile <drawing.firmament> --out-dir <directory>` retains explicit
+Drawing/Templates, selected views, metadata Records, design tables, Assembly BOMs
+and reviews. `generate` delegates a source's explicit Drawing declaration to that
+owner. Automatic generation options cannot silently alter an authored drawing.
-Names and dates must be supplied together. Missing review/approval roles remain
-blank. For example, `--drawn-by "Codex (AI)" --date 2026-10-18` credits preparation
-of this drawing without claiming that anyone checked or approved it. These flags
-also work with authored `drawing compile`:
+Within an authored View, `HiddenLines: Wireframe` uses the shared trimmed BRep
+wireframe sampler. `VisibleOnly` and `VisibleAndHidden` retain existing bounded
+occlusion behavior. Wireframe can show rear geometry but cannot replace dimensions
+or supply an unstated hole depth.
+
+PDF uses embedded Inter, searchable text and vector strokes. SVG, React and editable
+PPTX consume the same annotation geometry and table data. PPTX requires Inter in the
+editor for matching metrics. Text/leader/model and table keepouts are checked;
+layout errors reject. DXF and general automatic section/detail/Assembly planning
+remain separate work. No general ISO/ASME certification is claimed.
+
+## Title table and traceability
+
+Every sheet has a merged-cell title table for title/identity, material, part number,
+revision, scale, units, sheet and status. Separate Drawn / Checked / Approved names
+and dates are explicit paired inputs:
- `--drawn-by <name> --date <yyyy-MM-dd>`
- `--checked-by <name> --checked-date <yyyy-MM-dd>`
- `--approved-by <name> --approved-date <yyyy-MM-dd>`
-The authored metadata Record can also supply `DrawnBy` / `DrawnDate`, `CheckedBy` /
-`CheckedDate` and `ApprovedBy` / `ApprovedDate`; declare and populate both members
-for each provided role. Existing `Author` and `Date` remain the fallback for Drawn.
-These are traceability records, not digital signatures or an automatic manufacturing
-release decision. Preparation credit does not replace the model's source provenance.
+These flags also work with `drawing compile`. The authored metadata Record can
+supply `DrawnBy`/`DrawnDate`, `CheckedBy`/`CheckedDate` and
+`ApprovedBy`/`ApprovedDate`; legacy `Author`/`Date` remain the Drawn fallback.
+Unperformed reviews remain blank. Preparation credit, including AI assistance,
+is traceability rather than a digital signature or automatic engineering approval.
+
+## Reconstruction qualification
+
+The regression reader `fixtures/Regression/DrawingGeneration/reconstruct_from_pdf.py`
+reads only visible PDF dimensions and tables, writes a fresh Firmament source and
+can compile it through the real CLI. It does not read the original source, Drawing
+IR or embedded attachments. Compare that frozen reconstruction with the original
+only afterward. The witness is bounded to this plate convention, not general OCR
+or an automatic engineering reviewer.
-Text is measured before wrapping; a title-table or notes overflow rejects rather
-than silently truncating a name, date or engineering note. Line weights use paper
-millimetres consistently: heavier model boundaries, light surface grids, finer
-dimension/leader strokes, muted field labels and a stronger outer table frame.
+The layout follows the completeness and nonredundancy principles in
+[MIT's engineering drawing guide](https://ocw.mit.edu/courses/2-007-design-and-manufacturing-i-spring-2009/pages/related-resources/drawing_and_sketching/).
diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.md
index 67298c80..6b5853f6 100644
--- a/docs/public/firmament/syntax.md
+++ b/docs/public/firmament/syntax.md
@@ -57,7 +57,7 @@ reports `BoundNotSolved` (`status: "bound-not-solved"`). `build` runs the same
analysis compiler and the existing solver, writing analysis artifacts to the
`--out` directory. `fea --out-dir` remains the dedicated spelling. Static binding
does not promise solver convergence. Drawing sources also dispatch through their production owner in `validate` and
-`build`; `drawing compile --out-dir` remains available. [Automatic drawing generation](../drawings.md) also accepts admitted parts and supported AP242 PMI through `drawing generate`. Their output is a
+`build`; `drawing compile --out-dir` remains available. [Automatic drawing generation](../drawings.md) requires a qualified nominal dimension plan for `drawing generate` (currently rectangular plates/boxes and disjoint Z-through holes); `--reference-only` explicitly requests incomplete visualization. Their output is a
manufacturing drawing artifact directory. Passing a `.step` output path to an
Analysis or Drawing build rejects explicitly; export the geometry source separately.
diff --git a/docs/public/reference/cli.md b/docs/public/reference/cli.md
index 7d253d90..24d74f17 100644
--- a/docs/public/reference/cli.md
+++ b/docs/public/reference/cli.md
@@ -52,4 +52,4 @@ Generic STEP analysis reports analytic placement and size information where it i
## Generate engineering drawings
-`aetheris drawing generate <part.firmament|model.step> --out-dir <directory> --json` creates PDF, SVG, editable PPTX, Drawing IR and validation evidence. See [drawing generation](../drawings.md) for PMI admission and layout boundaries. Use `drawing compile` for authored drawings and assembly BOMs.
+`aetheris drawing generate <part.firmament|model.step> --out-dir <directory> --json` creates PDF, SVG, editable PPTX, Drawing IR and validation evidence. The default automatic path requires a complete nominal dimension plan; currently rectangular plates/boxes with disjoint Z-through holes are qualified. `--linear-tolerance`, `--angular-tolerance` and `--material` are explicit drawing requirements. `--reference-only` emits clearly incomplete visualization. See [drawing generation](../drawings.md) for admission, reconstruction qualification and manufacturing limits. Use `drawing compile` for authored drawings and assembly BOMs.
diff --git a/docs/public/reference/diagnostics.md b/docs/public/reference/diagnostics.md
index ff7357cf..059ad6ed 100644
--- a/docs/public/reference/diagnostics.md
+++ b/docs/public/reference/diagnostics.md
@@ -1,5 +1,14 @@
# Diagnostics and failure recovery
+Drawing generation reports `drawing-definition-incomplete` when no qualified plan
+accounts for the complete nominal body. `--reference-only` requests explicitly
+incomplete review views. `drawing-pmi-geometry-mismatch` identifies conflicting
+diameter/depth/quantity requirements; `drawing-tolerance-envelope-invalid` and
+`drawing-tolerance-zero-width` reject contradictory dimensional limits. Missing
+material, linear or angular requirements are recorded independently in definition
+evidence and visibly marked on the PDF. Process capability is not inferred from a
+successful export. See [drawing generation](../drawings.md).
+
Generic V2 build/validation errors use structured objects with `code`, `severity`, `message`, `sourceFile`, optional `sourceSpan`, `line`, `column`, and `locationNote`. The existing `fatal` spelling means an error that prevents admission; `warning` remains nonfatal. Parser route metadata is for debugging. An enclosing-declaration span is explicitly labelled when the legacy producer supplied no precise original-source provenance. Monaco consumes the same compiler presentation. Specialized domain commands are not yet all migrated to this representation.
Unknown canonical statements and Box fields are errors. `profile-layout-placement-unsupported` rejects unsupported Concept Struct layout planes instead of substituting XY. Use a traced Construction Plane for supported oriented profile workflows. `SemanticSourceNotFound` preserves the missing source and the provenance explanation. An accidental through-depth Pocket fails; explicit `end: ThroughAll` selects the admitted through cut. Box top-boundary Fillet with disjoint ThroughAll shaft/counterbore holes is supported; `CombinedFeatureInteractionUnsupported` identifies a hole touching the finish band or another hole. Unsupported combined selectors retain `CombinedFeatureSelectionLost` at the EdgeFinish declaration.
diff --git a/docs/public/reference/supported-features.md b/docs/public/reference/supported-features.md
index 6fc2133f..5297c593 100644
--- a/docs/public/reference/supported-features.md
+++ b/docs/public/reference/supported-features.md
@@ -5,7 +5,7 @@
| Area | Status | Preview 3 boundary |
|---|---|---|
| Firmament V2 native primitives/profiles | Bounded | Named Box/Cylinder/Frustum/RoundedBox, exact Ellipsoid, regular Polyhedron<4/6/8/12/20>, and admitted line/arc profile construction/composition |
-| Drawing generation | Bounded | Automatic PDF/SVG/editable PPTX from a part or supported face-associated AP242 PMI, shared wireframe, measured label layout and native title/signoff tables. Authored Assembly drawings remain available. See [drawings](../drawings.md). |
+| Drawing generation | Bounded | Complete nominal PDF/SVG/editable PPTX for rectangular plates/boxes with disjoint Z-through holes: stock/thickness dimensions, coordinate schedule and grouped limits. Explicit reference-only mode for incomplete PMI views; no process-capability or manufacturing-release claim. Authored Assembly drawings remain available. See [drawings](../drawings.md). |
| Uniform stock fillet | Bounded | `EdgeFinish<Fillet> { target: AllEdges; radius: ... }` on untouched Box or regular Polyhedron stock; all edge/corner patches together. Arbitrary bodies and mixed edits reject. |
| Profile rim fillet/chamfer | Bounded ordinary CAD | Top/bottom rims of convex polygons (including non-right-angle corners), admitted tangent line/arc loops, and circular segments formed by one arc and chord. Source-bound Judgment selects qualified construction; shared analytic-support intersections, certified finite fillet miter curves and exact quadratic chamfer miters. Collapsed caps and unqualified sharp curved junction families reject. See [fillets and chamfers](../firmament/fillet-profiles.md). |
| Box top-boundary finish with holes | Bounded | One complete +Z Boundary Chamfer or constant-radius Fillet with disjoint ThroughAll shaft/counterbore holes; exact cylindrical fillets and elliptical corner seams. Intersecting holes/finish bands, other combined selectors and general feature chains remain unsupported. See [geometry](../firmament/geometry.md#box-top-fillet-with-holes). |
diff --git a/fixtures/Regression/DrawingGeneration/qualify_pdf_roundtrip.py b/fixtures/Regression/DrawingGeneration/qualify_pdf_roundtrip.py
new file mode 100644
index 00000000..51b079de
--- /dev/null
+++ b/fixtures/Regression/DrawingGeneration/qualify_pdf_roundtrip.py
@@ -0,0 +1,89 @@
+#!/usr/bin/env python3
+"""Freeze a PDF-only reconstruction, then compare it with a canonical mm STEP.
+Requires pypdf and the real Aetheris CLI. No baselines are rewritten.
+"""
+import argparse
+import hashlib
+import json
+import math
+from pathlib import Path
+import re
+import subprocess
+import sys
+
+
+def run(cli, *args):
+ p = subprocess.run([str(cli), *map(str, args)], capture_output=True, text=True)
+ if p.returncode:
+ raise RuntimeError(p.stdout + p.stderr)
+ return json.loads(p.stdout)
+
+
+def cylinders(step, bounds):
+ # Verification-only readback of canonical emitted primitives. This is deliberately
+ # independent of both the dimension planner and its geometric recognition query.
+ text = step.read_text(encoding='utf-8')
+ if '.MILLI.,.METRE.' not in text:
+ raise ValueError('This verification adapter requires canonical millimetre STEP.')
+ entities = {int(i): value for i, value in re.findall(r'(?m)^#(\d+)=(.*);\s*$', text)}
+ result = []
+ for value in entities.values():
+ if not value.startswith('CYLINDRICAL_SURFACE('):
+ continue
+ placement = entities[int(re.findall(r'#(\d+)', value)[0])]
+ point = entities[int(re.findall(r'#(\d+)', placement)[0])]
+ coordinates = [float(n) for n in point[point.rfind('(') + 1:].rstrip(')').split(',')]
+ radius = float(value[value.rfind(',') + 1:].rstrip(')'))
+ result.append((coordinates[0] - bounds['min']['x'], coordinates[1] - bounds['min']['y'], radius))
+ return sorted(result)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--pdf', type=Path, required=True)
+ parser.add_argument('--reference-step', type=Path, required=True)
+ parser.add_argument('--out-dir', type=Path, required=True)
+ parser.add_argument('--cli', type=Path, required=True)
+ args = parser.parse_args()
+ cli = args.cli.resolve()
+ reader = Path(__file__).with_name('reconstruct_from_pdf.py')
+ # The child receives only a PDF and an output directory, and compiles a fresh source.
+ subprocess.run([sys.executable, str(reader), '--pdf', str(args.pdf), '--out-dir', str(args.out_dir), '--cli', str(cli)], check=True)
+ frozen = args.out_dir / 'reconstructed.firmament'
+ frozen_hash = hashlib.sha256(frozen.read_bytes()).hexdigest()
+ # Original model data is read only AFTER the independent reconstruction is frozen.
+ rebuilt = args.out_dir / 'reconstructed.step'
+ a = run(cli, 'inspect', args.reference_step, '--json')['summary']
+ b = run(cli, 'inspect', rebuilt, '--json')['summary']
+ for field in ('bodyCount', 'shellCount', 'faceCount', 'edgeCount', 'vertexCount', 'surfaceFamilies', 'structuralAssessment'):
+ assert a[field] == b[field], (field, a[field], b[field])
+ for axis in 'xyz':
+ extent_a = a['boundingBox']['max'][axis] - a['boundingBox']['min'][axis]
+ extent_b = b['boundingBox']['max'][axis] - b['boundingBox']['min'][axis]
+ assert abs(extent_a - extent_b) < 1e-8
+ ca = cylinders(args.reference_step, a['boundingBox'])
+ cb = cylinders(rebuilt, b['boundingBox'])
+ assert len(ca) == len(cb) and all(abs(x-y) < 1e-8 for left, right in zip(ca, cb) for x, y in zip(left, right)), (ca, cb)
+ ma = run(cli, 'verify', args.reference_step, '--json', '--evidence-dir', args.out_dir / 'verify-reference')['brepMassProperties']
+ mb = run(cli, 'verify', rebuilt, '--json', '--evidence-dir', args.out_dir / 'verify-rebuilt')['brepMassProperties']
+ va, vb = ma['absoluteVolume'], mb['absoluteVolume']
+ assert abs(va-vb) <= 1e-9 * max(1, abs(va)), (va, vb)
+ definition = json.loads((args.out_dir / 'pdf-definition.json').read_text(encoding='utf-8'))['definition']
+ analytic_pdf = definition['width'] * definition['height'] * definition['thickness'] - sum(math.pi * h['diameter']**2 / 4 * definition['thickness'] for h in definition['holes'])
+ extents = [a['boundingBox']['max'][axis] - a['boundingBox']['min'][axis] for axis in 'xyz']
+ analytic_step = math.prod(extents) - sum(math.pi * radius**2 * extents[2] for _, _, radius in ca)
+ assert abs(analytic_pdf - analytic_step) <= 1e-9 * max(1, abs(analytic_step))
+ assert hashlib.sha256(frozen.read_bytes()).hexdigest() == frozen_hash
+ evidence = {'success': True, 'reconstructionFrozenBeforeReferenceRead': True, 'reconstructedSourceSha256': frozen_hash,
+ 'matchingTopology': {k: a[k] for k in ('bodyCount', 'shellCount', 'faceCount', 'edgeCount', 'vertexCount')},
+ 'matchingCylinderAxesXYAndRadii': ca, 'referenceVolume': va, 'reconstructedVolume': vb,
+ 'kernelVolumeStatus': ma['status'], 'analyticNominalVolumeFromPdf': analytic_pdf,
+ 'analyticNominalVolumeFromReferencePrimitives': analytic_step,
+ 'kernelReportedMinusAnalyticVolume': va - analytic_step,
+ 'numericComparisonToleranceMillimetres': 1e-8, 'absoluteVolumeRelativeTolerance': 1e-9}
+ (args.out_dir / 'roundtrip-qualification.json').write_text(json.dumps(evidence, indent=2), encoding='utf-8')
+ print(json.dumps(evidence, indent=2))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/fixtures/Regression/DrawingGeneration/reconstruct_from_pdf.py b/fixtures/Regression/DrawingGeneration/reconstruct_from_pdf.py
new file mode 100644
index 00000000..590dab07
--- /dev/null
+++ b/fixtures/Regression/DrawingGeneration/reconstruct_from_pdf.py
@@ -0,0 +1,110 @@
+#!/usr/bin/env python3
+"""Independent reader for the visible dimensioned-plate PDF convention.
+
+Requires pypdf. Input is ONLY the PDF, never the source part or Drawing IR.
+Reads width/height/thickness size lines in their visible view sequence and the
+hole coordinate/type schedule; emits and optionally builds a fresh Firmament part.
+This is a bounded reconstruction witness, not a general drawing OCR system.
+"""
+from __future__ import annotations
+import argparse
+from decimal import Decimal
+import hashlib
+import json
+import math
+from pathlib import Path
+import re
+import subprocess
+from pypdf import PdfReader
+
+NUMBER = r"(?:\d+(?:\.\d*)?|\.\d+)(?:[Ee][+-]?\d+)?"
+
+
+def read_definition(text: str) -> dict:
+ sizes = re.findall(rf"(?m)^({NUMBER})\s+±({NUMBER})\s*$", text)
+ if len(sizes) != 3:
+ raise ValueError('Expected three controlling stock size/limit dimensions; reference envelopes do not qualify.')
+ width, height, thickness = [float(pair[0]) for pair in sizes]
+ if min(width, height, thickness) <= 0:
+ raise ValueError('Stock dimensions must be positive.')
+ if 'X FROM LEFT FINISHED EDGE; Y FROM BOTTOM FINISHED EDGE.' not in text:
+ raise ValueError('The coordinate reference edges are missing.')
+ if 'X/Y AT TOP FACE; HOLE AXES NOMINALLY NORMAL; THRU.' not in text:
+ raise ValueError('Hole entry plane, orientation or extent is missing.')
+ groups = {}
+ for identity, count, diameter, plus, minus in re.findall(rf"(?m)^(D\d+): (\d+)X Ø({NUMBER}) \+({NUMBER})/-({NUMBER}) THRU\s*$", text):
+ groups[identity] = {'count': int(count), 'diameter': float(diameter), 'plus': float(plus), 'minus': float(minus), 'extent': 'THRU'}
+ if not groups:
+ raise ValueError('No complete through-hole size/limit specification was found.')
+ holes = []
+ for identity, x, y, group in re.findall(rf"(?m)^([A-Za-z_]\w*) ({NUMBER}) ({NUMBER}) (D\d+)\s*$", text):
+ if group not in groups:
+ raise ValueError('A hole refers to an undefined size/extent group.')
+ holes.append({'identity': identity, 'x': float(x), 'y': float(y), 'group': group, **groups[group]})
+ if len({h['identity'] for h in holes}) != len(holes):
+ raise ValueError('Duplicate hole identities.')
+ for identity, specification in groups.items():
+ if sum(h['group'] == identity for h in holes) != specification['count']:
+ raise ValueError('The hole table does not account for the specified quantity.')
+ coordinates = re.search(rf'STOCK SIZES AND X/Y COORDINATES: ±({NUMBER}) mm\.', text)
+ angles = re.search(rf'UNLESS SPECIFIED: ANGLES ±({NUMBER})°\.', text)
+ if not coordinates or not angles:
+ raise ValueError('General dimensional acceptance requirements are missing.')
+ values = [width, height, thickness] + [float(v) for pair in sizes for v in pair] + [h[k] for h in holes for k in ('x', 'y', 'diameter', 'plus', 'minus')]
+ if not all(math.isfinite(v) for v in values):
+ raise ValueError('Nonfinite dimension.')
+ return {'width': width, 'height': height, 'thickness': thickness, 'stockTolerances': [float(pair[1]) for pair in sizes],
+ 'coordinateTolerance': float(coordinates[1]), 'angularToleranceDegrees': float(angles[1]), 'groups': groups, 'holes': holes}
+
+
+def reconstruct(definition: dict) -> str:
+ def number(n):
+ return format(Decimal(str(n)), 'f')
+ width, height, thickness = (definition[k] for k in ('width', 'height', 'thickness'))
+ lines = ['// Reconstructed from visible PDF dimensions and hole schedule only.', 'Model ReconstructedPlate {', ' units: mm',
+ f' Box Stock {{ size: [{number(width)}mm, {number(height)}mm, {number(thickness)}mm] }}', ' Modify Stock {']
+ for hole in definition['holes']:
+ lines += [f" Hole<Shaft> {hole['identity']} {{", ' on: +Z',
+ f" center: Point2({number(hole['x'] - width / 2)}mm, {number(hole['y'] - height / 2)}mm)",
+ f" diameter: {number(hole['diameter'])}mm", ' end: ThroughAll', ' }']
+ return '\n'.join(lines + [' }', '}']) + '\n'
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--pdf', type=Path, required=True)
+ parser.add_argument('--out-dir', type=Path, required=True)
+ parser.add_argument('--cli', type=Path, help='Optional real aetheris executable; builds the independently reconstructed part.')
+ args = parser.parse_args()
+ text = '\n'.join(page.extract_text() for page in PdfReader(args.pdf).pages)
+ definition = read_definition(text)
+ # Missing stock sizes, centers, extent and location tolerance must fail reconstruction.
+ mutations = {
+ 'missing_stock_size': re.sub(rf'(?m)^{NUMBER}\s+±{NUMBER}\s*$', '', text, count=1),
+ 'missing_hole_row': re.sub(rf'(?m)^[A-Za-z_]\w* {NUMBER} {NUMBER} D\d+\s*$', '', text, count=1),
+ 'missing_extent': text.replace(' THRU', ''),
+ 'missing_coordinate_tolerance': text.replace('STOCK SIZES AND X/Y COORDINATES:', 'REFERENCE COORDINATES:'),
+ }
+ for name, mutant in mutations.items():
+ try:
+ read_definition(mutant)
+ except ValueError:
+ continue
+ raise AssertionError(f'Incomplete drawing was admitted: {name}')
+ args.out_dir.mkdir(parents=True, exist_ok=True)
+ source = args.out_dir / 'reconstructed.firmament'
+ source.write_text(reconstruct(definition), encoding='utf-8')
+ evidence = {'sourcePdfSha256': hashlib.sha256(args.pdf.read_bytes()).hexdigest(), 'inputAuthority': 'visible PDF text only',
+ 'definition': definition, 'negativeCasesRejected': list(mutations),
+ 'reconstructionSha256': hashlib.sha256(source.read_bytes()).hexdigest()}
+ # Persist the reconstruction BEFORE any optional comparison outside this reader.
+ (args.out_dir / 'pdf-definition.json').write_text(json.dumps(evidence, indent=2), encoding='utf-8')
+ if args.cli:
+ result = subprocess.run([str(args.cli.resolve()), 'build', str(source.resolve()), '--output', str((args.out_dir / 'reconstructed.step').resolve())], capture_output=True, text=True)
+ if result.returncode:
+ raise RuntimeError(result.stdout + result.stderr)
+ print(json.dumps({'success': True, 'holes': len(definition['holes']), 'negativeCasesRejected': len(mutations), 'source': str(source)}))
+
+
+if __name__ == '__main__':
+ main()